1 /* "CodeWorker": a scripting language for parsing and generating text.
2
3 Copyright (C) 1996-1997, 1999-2008 C�dric Lemaire
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 To contact the author: codeworker@free.fr
20 */
21
22 #ifdef WIN32
23 #pragma warning(disable : 4786)
24 #endif
25
26 //##markup##"EXECUTABLE_VERSION"
27 //##begin##"EXECUTABLE_VERSION"
28 //##protect##"EXECUTABLE_VERSION"
29 #define EXECUTABLE_VERSION "4.5.3"
30 //##protect##"EXECUTABLE_VERSION"
31 //##end##"EXECUTABLE_VERSION"
32 #define EXECUTABLE_NAME "CodeWorker"
33
34 //for 'open' constants
35 #include <fcntl.h>
36
37 //for 'fstat' and 'stat'
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 //for 'mktime'
41 #include <time.h>
42
43 #include <errno.h>
44
45 #ifdef CODEWORKER_GNU_READLINE
46 # include <stdio.h> // fix for Red Hat 9 - thanks to Justin Cinkelj
47 # include <readline/readline.h>
48 # include <readline/history.h>
49 #endif
50
51 //for 'chdir'
52 #ifdef WIN32
53 # include <direct.h>
54 // for 'environ'
55 # include <stdlib.h>
56 //for 'utime'
57 # include <sys/utime.h>
58 //for 'chmod', 'access', 'open' and 'close'
59 # include <io.h>
60 //for 'kbhit()'
61 # include <conio.h>
62 //for 'Sleep'
63 # include <windows.h>
64 #else
65 # include <cstdio>
66 # if defined(__cplusplus) // && __GNUC_PREREQ (4, 3)
67 # include <cstdlib>
68 # endif
69 # include <unistd.h>
70 # include <utime.h>
71 # ifndef _O_RDONLY
72 # define _O_RDONLY O_RDONLY // for Debian/gcc 2.95.4
73 # endif
74 # include "UtlString.h" // for Debian/gcc 2.95.4
75 #endif
76
77 // for MD5 routines
78 #include "md5.h"
79
80 // Import the process's environement if it has not been done in one
81 // of the system headers already.
82 // Fixed by: Eric Nicolas
83 #ifndef environ
84 extern "C" char **environ;
85 #endif
86
87 #ifndef WIN32
88 // Reading of the keyboard under Linux
89 // -----------------------------------
90 // source code: "http://linux-sxs.org/programming/kbhit.html"
91 # include <termios.h>
92 # include <unistd.h> // for read()
93 # include <signal.h> // for signal()
94
95 static termios initial_settings;
96 static termios new_settings;
97 static int peek_character = -1;
98
99 // this function is used to catch
100 // SIGINT, SIGHUP and SIGTERM signal
101 // and restore tty settings for STDIN
102 // before quit.
catch_sig(int foo)103 void catch_sig(int foo)
104 {
105 #ifndef CODEWORKER_GNU_READLINE
106 tcsetattr(0, TCSANOW, &initial_settings);
107 #endif
108 _exit(EXIT_FAILURE);
109 }
110
initKeyboard()111 void initKeyboard() {
112 tcgetattr(0,&initial_settings);
113 new_settings = initial_settings;
114 new_settings.c_lflag &= ~(ICANON | ECHO);
115 new_settings.c_iflag &= ~(ISTRIP | IGNCR | ICRNL | INLCR | IXOFF | IXON);
116 new_settings.c_cc[VMIN] = 0;
117 new_settings.c_cc[VTIME] = 0;
118 #ifndef CODEWORKER_GNU_READLINE
119 tcsetattr(0, TCSANOW, &new_settings);
120 #endif
121 signal(SIGINT, catch_sig);
122 signal(SIGHUP, catch_sig);
123 signal(SIGTERM, catch_sig);
124 }
125
closeKeyboard()126 void closeKeyboard() {
127 #ifndef CODEWORKER_GNU_READLINE
128 tcsetattr(0, TCSANOW, &initial_settings);
129 #endif
130 }
131
kbhit()132 int kbhit() {
133 unsigned char ch;
134 int nread;
135
136 if (peek_character != -1) return 1;
137 new_settings.c_cc[VMIN]=0;
138 new_settings.c_cc[VTIME] = 1;
139 #ifndef CODEWORKER_GNU_READLINE
140 tcsetattr(0, TCSANOW, &new_settings);
141 #endif
142 nread = read(0,&ch,1);
143 new_settings.c_cc[VMIN]=0;
144 new_settings.c_cc[VTIME] = 0;
145 #ifndef CODEWORKER_GNU_READLINE
146 tcsetattr(0, TCSANOW, &new_settings);
147 #endif
148 if (nread == 1) {
149 peek_character = ch;
150 return 1;
151 }
152 return 0;
153 }
154
readch()155 int readch() {
156 char ch;
157
158 if(peek_character != -1) {
159 ch = peek_character;
160 peek_character = -1;
161 return ch;
162 }
163 read(0,&ch,1);
164 return ch;
165 }
166 #endif
167
168 #include <math.h>
169 #include <time.h>
170 #include <fstream>
171
172 #include "UtlTrace.h"
173 #include "UtlDate.h"
174 #include "UtlDirectory.h"
175 #include "ScpStream.h"
176 #include "UtlXMLStream.h"
177
178 #include "GrfLoadProject.h"
179 #include "GrfSaveProject.h"
180 #include "DtaAttributeType.h"
181 #include "CGExternalHandling.h"
182 #include "DtaArrayIterator.h"
183 #include "GrfSaveProjectTypes.h"
184 #include "GrfReadonlyHook.h"
185 #include "GrfWritefileHook.h"
186 #include "CppCompilerEnvironment.h"
187 #include "DtaProtectedAreasBag.h"
188
189 #include "HTTPRequest.h"
190 #include "NetSocket.h"
191
192 #include "CGRuntime.h"
193 #include "DtaProject.h"
194 #include "CppParsingTree.h"
195 #include "DtaPatternScript.h"
196 #include "DtaTranslateScript.h"
197 #include "Workspace.h"
198
199 namespace CodeWorker {
200 #ifndef MAX_PATH
201 # define MAX_PATH 1024
202 #endif
203
~EXECUTE_FUNCTION()204 EXECUTE_FUNCTION::~EXECUTE_FUNCTION() {}
205
206
207 char CGRuntime::_tcHexa[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
208
209 std::string CGRuntime::_sFrozenTime;
210 std::string CGRuntime::_sLogFile;
211 ScpStream* CGRuntime::_pOutputStream = NULL;
212 ScpStream* CGRuntime::_pInputStream = NULL;
213 GrfJointPoint* CGRuntime::_pJointPoint = NULL;
214 CppParsingTree_var CGRuntime::_pThisTree = CppParsingTree_var(DtaProject::createRootInstance());
215 std::list<DtaPatternScript*> CGRuntime::_listOfPatternScripts;
216 CGExternalHandling* CGRuntime::_pExternalHandling = NULL;
217
218
getRootTree()219 CppParsingTree_var CGRuntime::getRootTree() {
220 return DtaProject::getInstance();
221 }
222
toString(double dValue)223 std::string CGRuntime::toString(double dValue) {
224 char tcNumber[300];
225 double dFloor = floor(dValue);
226 if (dValue == dFloor) {
227 int iValue = (int) dFloor;
228 sprintf(tcNumber, "%d", iValue);
229 } else {
230 double dAbs = fabs(dValue);
231 if ((dAbs <= 1.0e-12) || (dAbs >= 1.0e12)) {
232 sprintf(tcNumber, "%.12e", dValue);
233 } else {
234 sprintf(tcNumber, "%.24f", dValue);
235 char* u = tcNumber + strlen(tcNumber);
236 u--;
237 while ((*u == '0') && (u != tcNumber)) {
238 *u = '\0';
239 u--;
240 }
241 if ((u != tcNumber) && (u != tcNumber + 1)) {
242 if ((u[-1] == '0') && (*u >= '0') && (*u <= '9')) {
243 // superfluous '0' series ended by a non-zero digit?
244 char* v = u - 2;
245 int iZero = 1;
246 while ((*v == '0') && (v != tcNumber)) {
247 iZero++;
248 v--;
249 }
250 if (iZero >= 6) {
251 // yes! a superfluous series of at least '000000'
252 char* w = v;
253 int iPoint = 0;
254 while ((*v != '.') && (v != tcNumber)) {
255 iPoint++;
256 v--;
257 }
258 if ((iPoint > 0) && (iZero + iPoint >= 12)) {
259 // truncate if at least 12 digits after the comma,
260 // and if we weren't just on the dot (this case is
261 // handled further)
262 w[1] = '\0';
263 u = w;
264 }
265 }
266 } else if ((u[-1] == '9') && (*u >= '0') && (*u <= '9')) {
267 // superfluous '9' series ended by any digit?
268 char* v = u - 2;
269 int iNine = 1;
270 while ((*v == '9') && (v != tcNumber)) {
271 iNine++;
272 v--;
273 }
274 if (iNine >= 6) {
275 // yes! a superfluous series of at least '999999'
276 char* w = v;
277 int iPoint = 0;
278 while ((*v != '.') && (v != tcNumber)) {
279 iPoint++;
280 v--;
281 }
282 if ((*v == '.') && (iNine + iPoint >= 12)) {
283 // truncate if at least 12 digits after the comma
284 u = w + 1;
285 *u = '\0';
286 do {
287 u--;
288 char a = *u;
289 if (a == '9') *u = '0';
290 else if (a != '.') {
291 *u = a + 1;
292 break;
293 }
294 } while (u != tcNumber);
295 if (*u == '0') {
296 // if '0', we are necessary at the beginning
297 // of the number, and we have to insert '1'
298 // just before!
299 memmove(u + 1, tcNumber, strlen(tcNumber));
300 *u = '1';
301 }
302 }
303 }
304 }
305 }
306 if (*u == '.') {
307 if (u == tcNumber) *u = '0';
308 else *u = '\0';
309 }
310 }
311 }
312 return tcNumber;
313 }
314
toString(int iValue)315 std::string CGRuntime::toString(int iValue) {
316 char sNumber[32];
317 sprintf(sNumber, "%d", iValue);
318 return sNumber;
319 }
320
toInteger(const std::string & sText)321 int CGRuntime::toInteger(const std::string& sText) {
322 return atoi(sText.c_str());
323 }
324
toInteger(double dValue)325 int CGRuntime::toInteger(double dValue) {
326 return (int) dValue;
327 }
328
toDouble(int iValue)329 double CGRuntime::toDouble(int iValue) {
330 return (double) iValue;
331 }
332
toDouble(const std::string & sText)333 double CGRuntime::toDouble(const std::string& sText) {
334 return atof(sText.c_str());
335 }
336
337
getApplicationName()338 const char* CGRuntime::getApplicationName() { return EXECUTABLE_NAME; }
getVersionNumber()339 const char* CGRuntime::getVersionNumber() { return EXECUTABLE_VERSION; }
340
registerExternalFunction(const std::string & sKey,EXTERNAL_FUNCTION externalFunction)341 void CGRuntime::registerExternalFunction(const std::string& sKey, EXTERNAL_FUNCTION externalFunction) {
342 getExternalFunctionsRegister()[sKey] = externalFunction;
343 }
344
registerExternalTemplateDispatcherFunction(const std::string & sKey,EXTERNAL_TEMPLATE_DISPATCHER_FUNCTION externalFunction)345 void CGRuntime::registerExternalTemplateDispatcherFunction(const std::string& sKey, EXTERNAL_TEMPLATE_DISPATCHER_FUNCTION externalFunction) {
346 getExternalTemplateDispatcherFunctionsRegister()[sKey] = externalFunction;
347 }
348
getExternalFunction(const std::string & sKey)349 EXTERNAL_FUNCTION CGRuntime::getExternalFunction(const std::string& sKey) {
350 EXTERNAL_FUNCTION externalFunction;
351 std::map<std::string, EXTERNAL_FUNCTION>::const_iterator cursor = getExternalFunctionsRegister().find(sKey);
352 if (cursor == getExternalFunctionsRegister().end()) externalFunction = NULL;
353 else externalFunction = cursor->second;
354 return externalFunction;
355 }
356
throwBNFExecutionError(const std::string & sBNFToken,const char * tcComment)357 void CGRuntime::throwBNFExecutionError(const std::string& sBNFToken, const char* tcComment) throw(UtlException) {
358 std::string sText;
359 if (!_pInputStream->readIdentifier(sText)) {
360 int iChar = _pInputStream->readChar();
361 if (iChar < 0) {
362 std::string sMessage = "BNF token '" + composeCLikeString(sBNFToken) + "' can't match the end of file";
363 if (tcComment != NULL) sMessage += std::string(": ") + tcComment;
364 throw UtlException(sMessage);
365 }
366 sText.assign(1, (char) iChar);
367 sText = composeCLikeString(sText);
368 } else {
369 int iOldLocation = _pInputStream->getInputLocation();
370 int iLocation = iOldLocation - sText.size();
371 for(;;) {
372 iLocation--;
373 _pInputStream->setInputLocation(iLocation);
374 char a = _pInputStream->peekChar();
375 if (((a < 'A') || (a > 'Z')) && ((a < 'a') || (a > 'z')) && (a != '_')) break;
376 sText = a + sText;
377 }
378 _pInputStream->setInputLocation(iOldLocation);
379 }
380 std::string sMessage = "the BNF token '" + sBNFToken + "' doesn't match '" + sText + "' and the following characters";
381 if (tcComment != NULL) sMessage += std::string(": ") + tcComment;
382 throw UtlException(sMessage);
383 }
384
entryPoint(int iNargs,char ** tsArgs,EXECUTE_FUNCTION * executeFunction)385 int CGRuntime::entryPoint(int iNargs, char** tsArgs, EXECUTE_FUNCTION* executeFunction) {
386 UtlTraceSession traceSession;
387 Workspace workspace;
388 try {
389 if (workspace.checkArguments(iNargs, tsArgs, executeFunction)) {
390 if (!workspace.noLogo() && !workspace.quietMode()) {
391 if (executeFunction == NULL) {
392 traceLine(EXECUTABLE_NAME " v" EXECUTABLE_VERSION " (LGPL), parses and generates source code easily;");
393 } else {
394 traceLine("This application has been written in C++ entirely by " EXECUTABLE_NAME " v" EXECUTABLE_VERSION);
395 }
396 traceLine("Copyright (C) 1996-2008 Cedric Lemaire; see 'http://www.codeworker.org'.");
397 }
398 if (!workspace.execute(executeFunction)) return workspace.executionHasFailed();
399 }
400 } catch (UtlException& exception) {
401 traceLine(exception.getMessage());
402 traceText(exception.getTraceStack());
403 return workspace.executionHasFailed();
404 } catch (UtlExitException& exit) {
405 return exit.getCode();
406 } catch (std::exception& except) {
407 traceLine("Fatal error: " + std::string(except.what()));
408 return workspace.executionHasFailed();
409 } catch (...) {
410 traceLine("Fatal error: ellipsis exception");
411 return workspace.executionHasFailed();
412 }
413 return 0;
414 }
415
executeScript(int iNargs,char ** tsArgs,EXECUTE_FUNCTION * executeFunction)416 bool CGRuntime::executeScript(int iNargs, char** tsArgs, EXECUTE_FUNCTION* executeFunction) throw(UtlException) {
417 UtlTraceSession traceSession;
418 Workspace workspace;
419 if (workspace.checkArguments(iNargs, tsArgs, executeFunction)) {
420 if (!workspace.noLogo() && !workspace.quietMode()) {
421 if (getExternalHandling() == NULL) {
422 traceLine(EXECUTABLE_NAME " for parsing and generating source code easily;");
423 traceLine("Copyright (C) 1996-2008 Cedric Lemaire; see 'http://www.codeworker.org'.");
424 } else {
425 getExternalHandling()->traceLine(EXECUTABLE_NAME " for parsing and generating source code easily;");
426 getExternalHandling()->traceLine("Copyright (C) 1996-2008 Cedric Lemaire; see 'http://www.codeworker.org'.");
427 }
428 }
429 workspace.execute(executeFunction);
430 return true;
431 }
432 return false;
433 }
434
registerScript(const char * sRegistration,EXECUTE_FUNCTION * executeFunction)435 void CGRuntime::registerScript(const char* sRegistration, EXECUTE_FUNCTION* executeFunction) {
436 DtaScript::registerScript(sRegistration, executeFunction);
437 }
438
registerReadonlyHook(READONLYHOOK_FUNCTION readonlyHook)439 void CGRuntime::registerReadonlyHook(READONLYHOOK_FUNCTION readonlyHook) {
440 DtaProject::getInstance().setReadonlyHook(new GrfReadonlyHook(readonlyHook));
441 }
442
registerWritefileHook(WRITEFILEHOOK_FUNCTION writefileHook)443 void CGRuntime::registerWritefileHook(WRITEFILEHOOK_FUNCTION writefileHook) {
444 DtaProject::getInstance().setWritefileHook(new GrfWritefileHook(writefileHook));
445 }
446
expand(EXECUTE_FUNCTION * executeFunction,CppParsingTree_var pThisTree,const std::string & sFilename)447 void CGRuntime::expand(EXECUTE_FUNCTION* executeFunction, CppParsingTree_var pThisTree, const std::string& sFilename) {
448 std::auto_ptr<DtaPatternScript> pPatternScript(new DtaPatternScript(executeFunction));
449 pPatternScript->expand(sFilename.c_str(), *(pThisTree._pInternalNode));
450 }
451
expand(const std::string & sScriptFile,CppParsingTree_var pThisTree,const std::string & sFilename)452 void CGRuntime::expand(const std::string& sScriptFile, CppParsingTree_var pThisTree, const std::string& sFilename) {
453 std::auto_ptr<DtaPatternScript> pPatternScript(new DtaPatternScript/*(_pThisTree._pInternalNode, NULL)*/);
454 pPatternScript->parseFile(sScriptFile.c_str());
455 pPatternScript->expand(sFilename.c_str(), *(pThisTree._pInternalNode));
456 }
457
autoexpand(const std::string & sFileName,CppParsingTree_var pThisTree)458 void CGRuntime::autoexpand(const std::string& sFileName, CppParsingTree_var pThisTree) {
459 DtaPatternScript patternScript;
460 patternScript.autoexpand(sFileName.c_str(), *(pThisTree._pInternalNode));
461 }
462
generate(EXECUTE_FUNCTION * executeFunction,CppParsingTree_var pThisTree,const std::string & sFilename)463 void CGRuntime::generate(EXECUTE_FUNCTION* executeFunction, CppParsingTree_var pThisTree, const std::string& sFilename) {
464 std::auto_ptr<DtaPatternScript> pPatternScript(new DtaPatternScript(executeFunction));
465 pPatternScript->generate(sFilename.c_str(), *(pThisTree._pInternalNode));
466 }
467
generate(const std::string & sScriptFile,CppParsingTree_var pThisTree,const std::string & sFilename)468 void CGRuntime::generate(const std::string& sScriptFile, CppParsingTree_var pThisTree, const std::string& sFilename) {
469 std::auto_ptr<DtaPatternScript> pPatternScript(new DtaPatternScript/*(_pThisTree._pInternalNode, NULL)*/);
470 pPatternScript->parseFile(sScriptFile.c_str());
471 pPatternScript->generate(sFilename.c_str(), *(pThisTree._pInternalNode));
472 }
473
generateString(EXECUTE_FUNCTION * executeFunction,CppParsingTree_var pThisTree,CppParsingTree_var pOutput)474 void CGRuntime::generateString(EXECUTE_FUNCTION* executeFunction, CppParsingTree_var pThisTree, CppParsingTree_var pOutput) {
475 std::auto_ptr<DtaPatternScript> pPatternScript(new DtaPatternScript(executeFunction));
476 std::string sOutput;
477 if (pPatternScript->generateString(sOutput, *(pThisTree._pInternalNode)) == NO_INTERRUPTION) pOutput.setValue(sOutput);
478 }
479
parseFree(EXECUTE_FUNCTION * executeFunction,CppParsingTree_var pThisTree,const std::string & sFilename)480 void CGRuntime::parseFree(EXECUTE_FUNCTION* executeFunction, CppParsingTree_var pThisTree, const std::string& sFilename) {
481 CGThisModifier pThis(pThisTree);
482 ScpStream* pStream = new ScpStream(sFilename, ScpStream::IN | ScpStream::PATH);
483 ScpStream* pOldInputStream = _pInputStream;
484 _pInputStream = pStream;
485 try {
486 executeFunction->run();
487 } catch(UtlException& e) {
488 int iLine = _pInputStream->getLineCount();
489 _pInputStream->close();
490 delete _pInputStream;
491 _pInputStream = pOldInputStream;
492 std::string sException = e.getMessage();
493 std::string sMessage;
494 sMessage += sFilename;
495 char tcNumber[32];
496 sprintf(tcNumber, "(%d):", iLine);
497 sMessage += tcNumber;
498 sMessage += endl() + sException;
499 throw UtlException(e.getTraceStack(), sMessage);
500 } catch (std::exception&) {
501 _pInputStream->close();
502 delete _pInputStream;
503 _pInputStream = pOldInputStream;
504 throw;
505 }
506 _pInputStream->close();
507 delete _pInputStream;
508 _pInputStream = pOldInputStream;
509 }
510
parseAsBNF(EXECUTE_FUNCTION * executeFunction,CppParsingTree_var pThisTree,const std::string & sFilename)511 void CGRuntime::parseAsBNF(EXECUTE_FUNCTION* executeFunction, CppParsingTree_var pThisTree, const std::string& sFilename) {
512 CGRuntimeOutputStream noOutput(NULL);
513 CGThisModifier pThis(pThisTree);
514 ScpStream* pStream = new ScpStream(sFilename, ScpStream::IN | ScpStream::PATH);
515 ScpStream* pOldInputStream = _pInputStream;
516 _pInputStream = pStream;
517 try {
518 executeFunction->run();
519 } catch(UtlException& exception) {
520 int iLine = _pInputStream->getLineCount();
521 int iCol = _pInputStream->getColCount();
522 _pInputStream->close();
523 delete _pInputStream;
524 _pInputStream = pOldInputStream;
525 std::string sException = exception.getMessage();
526 std::string sMessage = sFilename;
527 char tcNumber[64];
528 sprintf(tcNumber, "(%d,%d):", iLine, iCol);
529 sMessage += tcNumber + endl() + sException;
530 throw UtlException(exception.getTraceStack(), sMessage);
531 } catch (std::exception&) {
532 _pInputStream->close();
533 delete _pInputStream;
534 _pInputStream = pOldInputStream;
535 throw;
536 }
537 _pInputStream->close();
538 delete _pInputStream;
539 _pInputStream = pOldInputStream;
540 }
541
parseAsBNF(const std::string & sGrammarFile,CppParsingTree_var pThisTree,const std::string & sFilename)542 void CGRuntime::parseAsBNF(const std::string& sGrammarFile, CppParsingTree_var pThisTree, const std::string& sFilename) {
543 std::auto_ptr<DtaBNFScript> pBNFScript(new DtaBNFScript/*(pThisTree._pInternalNode, NULL)*/);
544 pBNFScript->parseFile(sGrammarFile.c_str());
545 pBNFScript->generate(sFilename.c_str(), *(pThisTree._pInternalNode));
546 }
547
parseStringAsBNF(EXECUTE_FUNCTION * executeFunction,CppParsingTree_var pThisTree,const std::string & sContent)548 void CGRuntime::parseStringAsBNF(EXECUTE_FUNCTION* executeFunction, CppParsingTree_var pThisTree, const std::string& sContent) {
549 CGRuntimeOutputStream noOutput(NULL);
550 CGThisModifier pThis(pThisTree);
551 ScpStream* pStream = new ScpStream;
552 (*pStream) << sContent;
553 ScpStream* pOldInputStream = _pInputStream;
554 _pInputStream = pStream;
555 try {
556 executeFunction->run();
557 } catch(UtlException& exception) {
558 int iLine = _pInputStream->getLineCount();
559 int iCol = _pInputStream->getColCount();
560 _pInputStream->close();
561 delete _pInputStream;
562 _pInputStream = pOldInputStream;
563 std::string sException = exception.getMessage();
564 std::string sMessage;
565 if (!sContent.empty()) {
566 sMessage += endl() + "----------------- content -----------------" +
567 endl() + sContent + endl() + "-------------------------------------------" + endl();
568 }
569 char tcNumber[64];
570 sprintf(tcNumber, "line %d, col %d:", iLine, iCol);
571 sMessage += tcNumber + endl() + sException;
572 throw UtlException(exception.getTraceStack(), sMessage);
573 } catch (std::exception&) {
574 _pInputStream->close();
575 delete _pInputStream;
576 _pInputStream = pOldInputStream;
577 throw;
578 }
579 _pInputStream->close();
580 delete _pInputStream;
581 _pInputStream = pOldInputStream;
582 }
583
translate(EXECUTE_FUNCTION * executeFunction,CppParsingTree_var pThisTree,const std::string & sInputFilename,const std::string & sOutputFilename)584 void CGRuntime::translate(EXECUTE_FUNCTION* executeFunction, CppParsingTree_var pThisTree, const std::string& sInputFilename, const std::string& sOutputFilename) {
585 std::auto_ptr<DtaTranslateScript> pTranslateScript(new DtaTranslateScript(executeFunction));
586 pTranslateScript->translate(sInputFilename, sOutputFilename, *(pThisTree._pInternalNode));
587 }
588
writeText(const char * sText)589 SEQUENCE_INTERRUPTION_LIST CGRuntime::writeText(const char* sText) {
590 _pOutputStream->writeBinaryData(sText, strlen(sText));
591 return NO_INTERRUPTION;
592 }
593
writeText(int iValue)594 SEQUENCE_INTERRUPTION_LIST CGRuntime::writeText(int iValue) {
595 (*_pOutputStream) << iValue;
596 return NO_INTERRUPTION;
597 }
598
writeText(double dValue)599 SEQUENCE_INTERRUPTION_LIST CGRuntime::writeText(double dValue) {
600 (*_pOutputStream) << dValue;
601 return NO_INTERRUPTION;
602 }
603
writeText(const CppParsingTree_var & pValue)604 SEQUENCE_INTERRUPTION_LIST CGRuntime::writeText(const CppParsingTree_var& pValue) {
605 const char* tcText = pValue.getValue();
606 if (tcText != NULL) {
607 _pOutputStream->writeBinaryData(tcText, pValue.getValueLength());
608 }
609 return NO_INTERRUPTION;
610 }
611
writeBinaryData(const char * sText,int iLength)612 SEQUENCE_INTERRUPTION_LIST CGRuntime::writeBinaryData(const char* sText, int iLength) {
613 _pOutputStream->writeBinaryData(sText, iLength);
614 return NO_INTERRUPTION;
615 }
616
writeBinaryData(unsigned char cChar)617 SEQUENCE_INTERRUPTION_LIST CGRuntime::writeBinaryData(unsigned char cChar) {
618 _pOutputStream->writeBinaryData((const char*) &cChar, 1);
619 return NO_INTERRUPTION;
620 }
621
readNumeric()622 std::string CGRuntime::readNumeric() {
623 std::string sNumeric;
624 if (_pInputStream->isEqualTo('+')) sNumeric = "+";
625 sNumeric += readInteger();
626 if (_pInputStream->isEqualTo('.')) {
627 sNumeric += "." + readPositiveInteger();
628 if (sNumeric.size() == 1 || (sNumeric == "+.")) {
629 _pInputStream->setInputLocation(_pInputStream->getInputLocation() - sNumeric.size());
630 return "";
631 }
632 } else if (sNumeric == "+") {
633 _pInputStream->goBack();
634 return "";
635 }
636 if (!sNumeric.empty()) {
637 int iChar = _pInputStream->readChar();
638 if ((iChar == (int) 'e') || (iChar == (int) 'E')) {
639 std::string sPrefix(1, (char) iChar);
640 iChar = _pInputStream->peekChar();
641 if ((iChar == (int) '+') || (iChar == (int) '-')) {
642 sPrefix += (char) iChar;
643 iChar = _pInputStream->readChar();
644 }
645 std::string sExponent = readPositiveInteger();
646 if (sExponent.empty()) _pInputStream->setInputLocation(_pInputStream->getInputLocation() - sPrefix.size());
647 else sNumeric += sPrefix + sExponent;
648 } else if (iChar >= 0) _pInputStream->goBack();
649 }
650 return sNumeric;
651 }
652
readInteger()653 std::string CGRuntime::readInteger() {
654 std::string sInteger;
655 if (_pInputStream->isEqualTo('-')) {
656 sInteger = "-" + readPositiveInteger();
657 if (sInteger.size() == 1) {
658 _pInputStream->goBack();
659 return "";
660 }
661 } else {
662 sInteger = readPositiveInteger();
663 }
664 return sInteger;
665 }
666
readEndOfLine()667 std::string CGRuntime::readEndOfLine() {
668 if (_pInputStream->isEqualTo('\r')) {
669 if (_pInputStream->isEqualTo('\n')) {
670 return "\r\n";
671 }
672 _pInputStream->goBack();
673 } else if (_pInputStream->isEqualTo('\n')) {
674 return "\n";
675 } else {
676 _pInputStream->goBack();
677 }
678 return "";
679 }
680
readPositiveInteger()681 std::string CGRuntime::readPositiveInteger() {
682 std::string sInteger;
683 int iChar = _pInputStream->readChar();
684 while ((iChar >= (int) '0') && (iChar <= (int) '9')) {
685 sInteger += (char) iChar;
686 iChar = _pInputStream->readChar();
687 }
688 if (iChar >= 0) _pInputStream->goBack();
689 return sInteger;
690 }
691
readCompleteIdentifier()692 std::string CGRuntime::readCompleteIdentifier() {
693 int iLocation = _pInputStream->getInputLocation();
694 while (_pInputStream->goBack()) {
695 int iChar = _pInputStream->peekChar();
696 if ((iChar < (int) '0') || (iChar > '9')) {
697 if (((iChar >= (int) 'A') && (iChar <= (int) 'Z')) ||
698 ((iChar >= (int) 'a') && (iChar <= (int) 'z')) ||
699 (iChar == '_')) {
700 _pInputStream->setInputLocation(iLocation);
701 return "";
702 }
703 break;
704 }
705 }
706 std::string sIdentifier;
707 _pInputStream->setInputLocation(iLocation);
708 _pInputStream->readIdentifier(sIdentifier);
709 return sIdentifier;
710 }
711
readIfEqualTo(char cChar)712 bool CGRuntime::readIfEqualTo(char cChar) {
713 return _pInputStream->isEqualTo(cChar);
714 }
715
nextIteration(std::list<DtaScriptVariable * >::const_iterator i)716 std::list<DtaScriptVariable*>::const_iterator CGRuntime::nextIteration(std::list<DtaScriptVariable*>::const_iterator i) {
717 i++;
718 return i;
719 }
720
nextIteration(std::map<std::string,DtaScriptVariable * >::const_iterator i)721 std::map<std::string, DtaScriptVariable*>::const_iterator CGRuntime::nextIteration(std::map<std::string, DtaScriptVariable*>::const_iterator i) {
722 i++;
723 return i;
724 }
725
726 //##markup##"functions and procedures"
727 //##begin##"functions and procedures"
appendFile(const std::string & sFilename,const std::string & sContent)728 SEQUENCE_INTERRUPTION_LIST CGRuntime::appendFile(const std::string& sFilename, const std::string& sContent) {
729 //##protect##"appendFile"
730 ScpStream theStream(sContent.size() + 1);
731 theStream.writeBinaryData(sContent.c_str(), sContent.size());
732 theStream.appendFile(sFilename, true);
733 return NO_INTERRUPTION;
734 //##protect##"appendFile"
735 }
736
clearVariable(DtaScriptVariable * pNode)737 SEQUENCE_INTERRUPTION_LIST CGRuntime::clearVariable(DtaScriptVariable* pNode) {
738 //##protect##"clearVariable"
739 if (pNode != NULL) pNode->clearContent();
740 return NO_INTERRUPTION;
741 //##protect##"clearVariable"
742 }
743
clearVariable(CppParsingTree_var pNode)744 SEQUENCE_INTERRUPTION_LIST CGRuntime::clearVariable(CppParsingTree_var pNode) {
745 SEQUENCE_INTERRUPTION_LIST result = clearVariable(pNode._pInternalNode);
746 return result;
747 }
748
compileToCpp(const std::string & sScriptFileName,const std::string & sProjectDirectory,const std::string & sCodeWorkerDirectory)749 SEQUENCE_INTERRUPTION_LIST CGRuntime::compileToCpp(const std::string& sScriptFileName, const std::string& sProjectDirectory, const std::string& sCodeWorkerDirectory) {
750 //##protect##"compileToCpp"
751 CppCompilerEnvironment theCompilerEnvironment(sProjectDirectory);
752 DtaScript script(NULL);
753 script.parseFile(sScriptFileName.c_str());
754 script.compileCpp(theCompilerEnvironment, sScriptFileName);
755 return NO_INTERRUPTION;
756 //##protect##"compileToCpp"
757 }
758
copyFile(const std::string & sSourceFileName,const std::string & sDestinationFileName)759 SEQUENCE_INTERRUPTION_LIST CGRuntime::copyFile(const std::string& sSourceFileName, const std::string& sDestinationFileName) {
760 //##protect##"copyFile"
761 std::auto_ptr<ScpStream> pInput(new ScpStream(sSourceFileName, ScpStream::IN | ScpStream::PATH));
762 pInput->saveIntoFile(sDestinationFileName, true);
763 return NO_INTERRUPTION;
764 //##protect##"copyFile"
765 }
766
copyGenerableFile(const std::string & sSourceFileName,const std::string & sDestinationFileName)767 SEQUENCE_INTERRUPTION_LIST CGRuntime::copyGenerableFile(const std::string& sSourceFileName, const std::string& sDestinationFileName) {
768 //##protect##"copyGenerableFile"
769 CppParsingTree_value isDone;
770 std::string sScriptHandle = createVirtualTemporaryFile("@set this = true;");
771 std::string sFileHandle1 = createVirtualTemporaryFile(loadFile(sSourceFileName, -1));
772 expand(sScriptHandle, isDone, sFileHandle1);
773 if (!isDone.getBooleanValue()) generate(sScriptHandle, isDone, sFileHandle1);
774 bool bDifferent = !existFile(sDestinationFileName);
775 if (!bDifferent) {
776 std::string sFileHandle2 = createVirtualTemporaryFile(loadFile(sDestinationFileName, -1));
777 isDone.setValue("");
778 expand(sScriptHandle, isDone, sFileHandle2);
779 if (!isDone.getBooleanValue()) generate(sScriptHandle, isDone, sFileHandle2);
780 bDifferent = (loadFile(sFileHandle1, -1) != loadFile(sFileHandle2, -1));
781 deleteVirtualFile(sFileHandle2);
782 }
783 deleteVirtualFile(sScriptHandle);
784 if (bDifferent) copyFile(sFileHandle1, sDestinationFileName);
785 deleteVirtualFile(sFileHandle1);
786 return NO_INTERRUPTION;
787 //##protect##"copyGenerableFile"
788 }
789
copySmartDirectory(const std::string & sSourceDirectory,const std::string & sDestinationPath)790 SEQUENCE_INTERRUPTION_LIST CGRuntime::copySmartDirectory(const std::string& sSourceDirectory, const std::string& sDestinationPath) {
791 //##protect##"copySmartDirectory"
792 UtlDirectory sourceDir(sSourceDirectory);
793 if (!sourceDir.scanRecursively()) throw UtlException("unable to open directory '" + sSourceDirectory + "'");
794 if (sDestinationPath.empty() || (sDestinationPath[sDestinationPath.size() - 1] == '/') || (sDestinationPath[sDestinationPath.size() - 1] == '\\'))
795 copySmartDirectory(sourceDir, sDestinationPath);
796 else
797 copySmartDirectory(sourceDir, sDestinationPath + "/");
798 return NO_INTERRUPTION;
799 //##protect##"copySmartDirectory"
800 }
801
cutString(const std::string & sText,const std::string & sSeparator,std::list<std::string> & slList)802 SEQUENCE_INTERRUPTION_LIST CGRuntime::cutString(const std::string& sText, const std::string& sSeparator, std::list<std::string>& slList) {
803 //##protect##"cutString"
804 slList.clear();
805 int iPos = sText.find(sSeparator);
806 int iPrec = 0;
807 while (iPos >= 0) {
808 std::string sValue = sText.substr(iPrec, iPos - iPrec);
809 slList.push_back(sValue);
810 iPrec = iPos + sSeparator.size();
811 iPos = sText.find(sSeparator, iPrec);
812 }
813 std::string sLastValue = sText.substr(iPrec);
814 slList.push_back(sLastValue);
815 return NO_INTERRUPTION;
816 //##protect##"cutString"
817 }
818
cutString(const std::string & sText,const std::string & sSeparator,CppParsingTree_var pList)819 SEQUENCE_INTERRUPTION_LIST CGRuntime::cutString(const std::string& sText, const std::string& sSeparator, CppParsingTree_var pList) {
820 std::list<std::string> slList;
821 SEQUENCE_INTERRUPTION_LIST result = cutString(sText, sSeparator, slList);
822 pList.setValue(slList);
823 return result;
824 }
825
environTable(DtaScriptVariable * pTable)826 SEQUENCE_INTERRUPTION_LIST CGRuntime::environTable(DtaScriptVariable* pTable) {
827 //##protect##"environTable"
828 pTable->clearContent();
829 int i = 0;
830 // If a syntax error occurs on the next line with your compiler,
831 // try -D __USE_GNU as a preprocessor directive.
832 // If the error doesn't disappear, please find the declaration
833 // 'extern char **environ;' amongst your system includes and send me an email
834 // (codeworker@free.fr).
835 while (environ[i] != NULL) {
836 pTable->pushItem(environ[i])->setValue(environ[i]);
837 i++;
838 }
839 return NO_INTERRUPTION;
840 //##protect##"environTable"
841 }
842
environTable(CppParsingTree_var pTable)843 SEQUENCE_INTERRUPTION_LIST CGRuntime::environTable(CppParsingTree_var pTable) {
844 SEQUENCE_INTERRUPTION_LIST result = environTable(pTable._pInternalNode);
845 return result;
846 }
847
extendExecutedScript(const std::string & sScriptContent)848 SEQUENCE_INTERRUPTION_LIST CGRuntime::extendExecutedScript(const std::string& sScriptContent) {
849 //##protect##"extendExecutedScript"
850 ScpStream stream(sScriptContent);
851 DtaProject::getInstance().getScript()->parseStream(stream, false, "");
852 return NO_INTERRUPTION;
853 //##protect##"extendExecutedScript"
854 }
855
insertElementAt(DtaScriptVariable * pList,const std::string & sKey,int iPosition)856 SEQUENCE_INTERRUPTION_LIST CGRuntime::insertElementAt(DtaScriptVariable* pList, const std::string& sKey, int iPosition) {
857 //##protect##"insertElementAt"
858 if (pList != NULL) {
859 pList->insertElementAt(sKey, iPosition);
860 }
861 return NO_INTERRUPTION;
862 //##protect##"insertElementAt"
863 }
864
insertElementAt(CppParsingTree_var pList,const std::string & sKey,int iPosition)865 SEQUENCE_INTERRUPTION_LIST CGRuntime::insertElementAt(CppParsingTree_var pList, const std::string& sKey, int iPosition) {
866 SEQUENCE_INTERRUPTION_LIST result = insertElementAt(pList._pInternalNode, sKey, iPosition);
867 return result;
868 }
869
invertArray(DtaScriptVariable * pArray)870 SEQUENCE_INTERRUPTION_LIST CGRuntime::invertArray(DtaScriptVariable* pArray) {
871 //##protect##"invertArray"
872 pArray->invertArray();
873 return NO_INTERRUPTION;
874 //##protect##"invertArray"
875 }
876
invertArray(CppParsingTree_var pArray)877 SEQUENCE_INTERRUPTION_LIST CGRuntime::invertArray(CppParsingTree_var pArray) {
878 SEQUENCE_INTERRUPTION_LIST result = invertArray(pArray._pInternalNode);
879 return result;
880 }
881
listAllGeneratedFiles(DtaScriptVariable * pFiles)882 SEQUENCE_INTERRUPTION_LIST CGRuntime::listAllGeneratedFiles(DtaScriptVariable* pFiles) {
883 //##protect##"listAllGeneratedFiles"
884 if (pFiles == NULL) {
885 throw UtlException("the tree parameter passed to the procedure 'listAllGeneratedFiles' doesn't exist");
886 }
887 pFiles->clearContent();
888 const std::map<std::string, std::set<std::string> >& listOfGeneratedFiles = DtaProject::getInstance().getCapturedOutputFiles();
889 for (std::map<std::string, std::set<std::string> >::const_iterator i = listOfGeneratedFiles.begin(); i != listOfGeneratedFiles.end(); ++i) {
890 DtaScriptVariable* pOutputFile = pFiles->addElement(i->first);
891 pOutputFile->setValue(i->first.c_str());
892 DtaScriptVariable* pScripts = pOutputFile->insertNode("scripts");
893 for (std::set<std::string>::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
894 pScripts->addElement(*j)->setValue(j->c_str());
895 }
896 }
897 return NO_INTERRUPTION;
898 //##protect##"listAllGeneratedFiles"
899 }
900
listAllGeneratedFiles(CppParsingTree_var pFiles)901 SEQUENCE_INTERRUPTION_LIST CGRuntime::listAllGeneratedFiles(CppParsingTree_var pFiles) {
902 SEQUENCE_INTERRUPTION_LIST result = listAllGeneratedFiles(pFiles._pInternalNode);
903 return result;
904 }
905
loadProject(const std::string & sXMLorTXTFileName,DtaScriptVariable * pNodeToLoad)906 SEQUENCE_INTERRUPTION_LIST CGRuntime::loadProject(const std::string& sXMLorTXTFileName, DtaScriptVariable* pNodeToLoad) {
907 //##protect##"loadProject"
908 std::string sCompleteFileName;
909 std::ifstream* pFile = CodeWorker::openInputFileFromIncludePath(sXMLorTXTFileName.c_str(), sCompleteFileName);
910 if (pFile == NULL) throw UtlException("unable to open file \"" + sXMLorTXTFileName + "\" for reading");
911 if (sXMLorTXTFileName.rfind(".xml") == sXMLorTXTFileName.size() - 4) {
912 throw UtlException("loadProject() isn't able to load yet a parse tree previously saved to XML");
913 } else {
914 GrfLoadProject::parseTextFile(*pFile, pNodeToLoad);
915 }
916 pFile->close();
917 return NO_INTERRUPTION;
918 //##protect##"loadProject"
919 }
920
loadProject(const std::string & sXMLorTXTFileName,CppParsingTree_var pNodeToLoad)921 SEQUENCE_INTERRUPTION_LIST CGRuntime::loadProject(const std::string& sXMLorTXTFileName, CppParsingTree_var pNodeToLoad) {
922 SEQUENCE_INTERRUPTION_LIST result = loadProject(sXMLorTXTFileName, pNodeToLoad._pInternalNode);
923 return result;
924 }
925
openLogFile(const std::string & sFilename)926 SEQUENCE_INTERRUPTION_LIST CGRuntime::openLogFile(const std::string& sFilename) {
927 //##protect##"openLogFile"
928 _sLogFile = sFilename;
929 if (!sFilename.empty()) {
930 saveToFile(sFilename, EXECUTABLE_NAME " v" EXECUTABLE_VERSION " -- " + getNow() + endl());
931 }
932 return NO_INTERRUPTION;
933 //##protect##"openLogFile"
934 }
935
produceHTML(const std::string & sScriptFileName,const std::string & sHTMLFileName)936 SEQUENCE_INTERRUPTION_LIST CGRuntime::produceHTML(const std::string& sScriptFileName, const std::string& sHTMLFileName) {
937 //##protect##"produceHTML"
938 /* std::ifstream* pScriptFile = openInputFileFromIncludePath(sScriptFileName.c_str());
939 if (pScriptFile == NULL) throw UtlException(std::string("unable to open file \"") + sScriptFileName + "\" for reading");
940 std::fstream* pHTMLFile = DtaScript::openOutputFile(sHTMLFileName.c_str(), false);
941 if (pHTMLFile == NULL) {
942 pScriptFile->close();
943 throw UtlException("unable to open file \"" + sHTMLFileName + "\" for writing");
944 }
945
946 (*pHTMLFile) << "<HTML>" << std::endl;
947 (*pHTMLFile) << "<BODY>" << std::endl;
948 bool bExecMode = false;
949 int iChar = CodeWorker::readChar((*pScriptFile));
950 bool bFirstOfLine = true;
951 std::string sColor = "#000000";
952 while (iChar > 0) {
953 bool bRead = true;
954 if (bFirstOfLine) {
955 (*pHTMLFile) << "<FONT SIZE=3><FONT COLOR=\"" << sColor << "\">";
956 if (!bExecMode) (*pHTMLFile) << "<B>";
957 bFirstOfLine = false;
958 }
959 if (iChar == (int) '@') {
960 if (bExecMode) {
961 bExecMode = false;
962 sColor = "#000000";
963 } else {
964 (*pHTMLFile) << "</B>";
965 bExecMode = true;
966 sColor = "#0000ff";
967 }
968 (*pHTMLFile) << "</FONT><FONT SIZE=1 COLOR=\"";
969 if (bExecMode) (*pHTMLFile) << "#00ff00";
970 else (*pHTMLFile) << "#ff0000";
971 (*pHTMLFile) << "\">@</FONT><FONT SIZE=3 COLOR=\"" << sColor << "\">";
972 if (!bExecMode) (*pHTMLFile) << "<B>";
973 } else if (iChar == (int) '\\') {
974 (*pHTMLFile) << "\\";
975 iChar = CodeWorker::readChar((*pScriptFile));
976 if (iChar == (int) '@') {
977 (*pHTMLFile) << "@";
978 } else if (iChar > 0) {
979 (*pHTMLFile) << (char) iChar;
980 }
981 } else if (iChar == ' ') {
982 (*pHTMLFile) << " ";
983 } else if (iChar == '\t') {
984 (*pHTMLFile) << " ";
985 } else if (iChar == '\r') {
986 if (!bExecMode) (*pHTMLFile) << "</B>";
987 (*pHTMLFile) << "</FONT></FONT><BR>" << std::endl;
988 iChar = CodeWorker::readChar((*pScriptFile));
989 if (iChar != '\n') bRead = false;
990 bFirstOfLine = true;
991 } else if (iChar == '\n') {
992 if (!bExecMode) (*pHTMLFile) << "</B>";
993 (*pHTMLFile) << "</FONT></FONT><BR>" << std::endl;
994 iChar = CodeWorker::readChar((*pScriptFile));
995 if (iChar != '\r') bRead = false;
996 bFirstOfLine = true;
997 } else if (iChar == '<') {
998 (*pHTMLFile) << "‹";
999 } else if (iChar == '>') {
1000 (*pHTMLFile) << "›";
1001 } else {
1002 (*pHTMLFile) << (char) iChar;
1003 }
1004 if (bRead) iChar = CodeWorker::readChar((*pScriptFile));
1005 }
1006 if (!bFirstOfLine) {
1007 if (!bExecMode) (*pHTMLFile) << "</B>";
1008 (*pHTMLFile) << "</FONT></FONT><BR>" << std::endl;
1009 }
1010 (*pHTMLFile) << "</BODY>" << std::endl;
1011 (*pHTMLFile) << "</HTML>" << std::endl;
1012
1013 pScriptFile->close();
1014 pHTMLFile->close();
1015 */ return NO_INTERRUPTION;
1016 //##protect##"produceHTML"
1017 }
1018
putEnv(const std::string & sName,const std::string & sValue)1019 SEQUENCE_INTERRUPTION_LIST CGRuntime::putEnv(const std::string& sName, const std::string& sValue) {
1020 //##protect##"putEnv"
1021 std::string sLine = sName + "=" + sValue;
1022 #ifdef WIN32
1023 if (_putenv(sLine.c_str()) == -1)
1024 #else
1025 //!!! under Linux and Mac OS X
1026 // if (setenv(sName.c_str(), sValue.c_str(), 1) == -1)
1027 //!!! under Unix, we have to use putenv()
1028 static std::map<std::string, char*> keepPointers;
1029 std::map<std::string, char*>::const_iterator cursor = keepPointers.find(sName);
1030 if (cursor != keepPointers.end()) free(cursor->second);
1031 char* tcLine = strdup(sLine.c_str());
1032 keepPointers[sName] = tcLine;
1033 if (putenv(tcLine) != 0)
1034 #endif
1035 throw UtlException("error while trying to put environment entry '" + sLine + "'");
1036 return NO_INTERRUPTION;
1037 //##protect##"putEnv"
1038 }
1039
randomSeed(int iSeed)1040 SEQUENCE_INTERRUPTION_LIST CGRuntime::randomSeed(int iSeed) {
1041 //##protect##"randomSeed"
1042 if (iSeed >= 0) srand((unsigned) iSeed);
1043 else srand((unsigned) time(NULL));
1044 return NO_INTERRUPTION;
1045 //##protect##"randomSeed"
1046 }
1047
removeAllElements(DtaScriptVariable * pVariable)1048 SEQUENCE_INTERRUPTION_LIST CGRuntime::removeAllElements(DtaScriptVariable* pVariable) {
1049 //##protect##"removeAllElements"
1050 if (pVariable != NULL) pVariable->removeArrayElement();
1051 return NO_INTERRUPTION;
1052 //##protect##"removeAllElements"
1053 }
1054
removeAllElements(CppParsingTree_var pVariable)1055 SEQUENCE_INTERRUPTION_LIST CGRuntime::removeAllElements(CppParsingTree_var pVariable) {
1056 SEQUENCE_INTERRUPTION_LIST result = removeAllElements(pVariable._pInternalNode);
1057 return result;
1058 }
1059
removeElement(DtaScriptVariable * pVariable,const std::string & sKey)1060 SEQUENCE_INTERRUPTION_LIST CGRuntime::removeElement(DtaScriptVariable* pVariable, const std::string& sKey) {
1061 //##protect##"removeElement"
1062 if (pVariable != NULL) pVariable->removeArrayElement(sKey.c_str());
1063 return NO_INTERRUPTION;
1064 //##protect##"removeElement"
1065 }
1066
removeElement(CppParsingTree_var pVariable,const std::string & sKey)1067 SEQUENCE_INTERRUPTION_LIST CGRuntime::removeElement(CppParsingTree_var pVariable, const std::string& sKey) {
1068 SEQUENCE_INTERRUPTION_LIST result = removeElement(pVariable._pInternalNode, sKey);
1069 return result;
1070 }
1071
removeFirstElement(DtaScriptVariable * pList)1072 SEQUENCE_INTERRUPTION_LIST CGRuntime::removeFirstElement(DtaScriptVariable* pList) {
1073 //##protect##"removeFirstElement"
1074 if (pList != NULL) pList->removeFirstElement();
1075 return NO_INTERRUPTION;
1076 //##protect##"removeFirstElement"
1077 }
1078
removeFirstElement(CppParsingTree_var pList)1079 SEQUENCE_INTERRUPTION_LIST CGRuntime::removeFirstElement(CppParsingTree_var pList) {
1080 SEQUENCE_INTERRUPTION_LIST result = removeFirstElement(pList._pInternalNode);
1081 return result;
1082 }
1083
removeLastElement(DtaScriptVariable * pList)1084 SEQUENCE_INTERRUPTION_LIST CGRuntime::removeLastElement(DtaScriptVariable* pList) {
1085 //##protect##"removeLastElement"
1086 if (pList != NULL) pList->removeLastElement();
1087 return NO_INTERRUPTION;
1088 //##protect##"removeLastElement"
1089 }
1090
removeLastElement(CppParsingTree_var pList)1091 SEQUENCE_INTERRUPTION_LIST CGRuntime::removeLastElement(CppParsingTree_var pList) {
1092 SEQUENCE_INTERRUPTION_LIST result = removeLastElement(pList._pInternalNode);
1093 return result;
1094 }
1095
removeRecursive(DtaScriptVariable * pVariable,const std::string & sAttribute)1096 SEQUENCE_INTERRUPTION_LIST CGRuntime::removeRecursive(DtaScriptVariable* pVariable, const std::string& sAttribute) {
1097 //##protect##"removeRecursive"
1098 pVariable->removeRecursive(sAttribute.c_str());
1099 return NO_INTERRUPTION;
1100 //##protect##"removeRecursive"
1101 }
1102
removeRecursive(CppParsingTree_var pVariable,const std::string & sAttribute)1103 SEQUENCE_INTERRUPTION_LIST CGRuntime::removeRecursive(CppParsingTree_var pVariable, const std::string& sAttribute) {
1104 SEQUENCE_INTERRUPTION_LIST result = removeRecursive(pVariable._pInternalNode, sAttribute);
1105 return result;
1106 }
1107
removeVariable(DtaScriptVariable * pNode)1108 SEQUENCE_INTERRUPTION_LIST CGRuntime::removeVariable(DtaScriptVariable* pNode) {
1109 //##protect##"removeVariable"
1110 DtaScriptVariable* pVariable = pNode;
1111 // while (pVariable->getReferencedVariable() != NULL) pVariable = pVariable->getReferencedVariable();
1112 DtaScriptVariable* pParent = pVariable->getParent();
1113 if (pParent == NULL) throw UtlException("It is forbidden to remove the main tree or a local variable");
1114 if (pVariable->isLocal()) {
1115 std::string strError = "It is forbidden to remove a local variable: '";
1116 strError += pVariable->getName();
1117 strError += "'";
1118 throw UtlException(strError);
1119 }
1120 if (strncmp(pVariable->getName(), "##", 2) == 0) throw UtlException("It is forbidden to remove a scope");
1121 pParent->remove(pVariable);
1122 return NO_INTERRUPTION;
1123 //##protect##"removeVariable"
1124 }
1125
removeVariable(CppParsingTree_var pNode)1126 SEQUENCE_INTERRUPTION_LIST CGRuntime::removeVariable(CppParsingTree_var pNode) {
1127 SEQUENCE_INTERRUPTION_LIST result = removeVariable(pNode._pInternalNode);
1128 return result;
1129 }
1130
saveBinaryToFile(const std::string & sFilename,const std::string & sContent)1131 SEQUENCE_INTERRUPTION_LIST CGRuntime::saveBinaryToFile(const std::string& sFilename, const std::string& sContent) {
1132 //##protect##"saveBinaryToFile"
1133 int iLength = sContent.size();
1134 if ((iLength % 2) != 0) throw UtlException("saveBinaryToFile(\"" + sFilename + "\"): a binary content cannot have an odd length");
1135 iLength >>= 1;
1136 unsigned char* tcBinary = new unsigned char[iLength];
1137 if (!convertBytesToChars(sContent, tcBinary, iLength)) {
1138 delete [] tcBinary;
1139 throw UtlException("saveBinaryToFile(\"" + sFilename + "\"): about the binary content, invalid hexadecimal digit encountered");
1140 }
1141 ScpStream theStream;
1142 theStream.writeBinaryData((char*) tcBinary, iLength);
1143 delete [] tcBinary;
1144 theStream.saveIntoFile(sFilename, true);
1145 return NO_INTERRUPTION;
1146 //##protect##"saveBinaryToFile"
1147 }
1148
saveProject(const std::string & sXMLorTXTFileName,DtaScriptVariable * pNodeToSave)1149 SEQUENCE_INTERRUPTION_LIST CGRuntime::saveProject(const std::string& sXMLorTXTFileName, DtaScriptVariable* pNodeToSave) {
1150 //##protect##"saveProject"
1151 if (pNodeToSave == NULL) throw UtlException("cannot save an empty node to a file");
1152 std::ofstream* pFile = CodeWorker::openOutputFile(sXMLorTXTFileName.c_str());
1153 if (pFile == NULL) throw UtlException("unable to open file \"" + sXMLorTXTFileName + "\" for writing");
1154 if (sXMLorTXTFileName.rfind(".xml") == sXMLorTXTFileName.size() - 4) {
1155 UtlXMLStream myXMLStream(*pFile);
1156 GrfSaveProject::generateXMLFile(myXMLStream, *pNodeToSave);
1157 } else {
1158 GrfSaveProject::generateTextFile(*pFile, *pNodeToSave);
1159 }
1160 pFile->close();
1161 return NO_INTERRUPTION;
1162 //##protect##"saveProject"
1163 }
1164
saveProject(const std::string & sXMLorTXTFileName,CppParsingTree_var pNodeToSave)1165 SEQUENCE_INTERRUPTION_LIST CGRuntime::saveProject(const std::string& sXMLorTXTFileName, CppParsingTree_var pNodeToSave) {
1166 SEQUENCE_INTERRUPTION_LIST result = saveProject(sXMLorTXTFileName, pNodeToSave._pInternalNode);
1167 return result;
1168 }
1169
saveProjectTypes(const std::string & sXMLFileName)1170 SEQUENCE_INTERRUPTION_LIST CGRuntime::saveProjectTypes(const std::string& sXMLFileName) {
1171 //##protect##"saveProjectTypes"
1172 std::ofstream* pXMLFile = CodeWorker::openOutputFile(sXMLFileName.c_str());
1173 if (pXMLFile == NULL) throw UtlException("unable to open file \"" + sXMLFileName + "\" for writing");
1174 UtlXMLStream myXMLStream(*pXMLFile);
1175 DtaAttributeType& myType = DtaAttributeType::extractProjectTypes(DtaProject::getInstance());
1176 std::set<std::string> listForAvoidingCycles;
1177 GrfSaveProjectTypes::generateXMLFile(myXMLStream, myType, listForAvoidingCycles);
1178 pXMLFile->close();
1179 return NO_INTERRUPTION;
1180 //##protect##"saveProjectTypes"
1181 }
1182
saveToFile(const std::string & sFilename,const std::string & sContent)1183 SEQUENCE_INTERRUPTION_LIST CGRuntime::saveToFile(const std::string& sFilename, const std::string& sContent) {
1184 //##protect##"saveToFile"
1185 ScpStream theStream(sContent.size() + 1);
1186 theStream.writeBinaryData(sContent.c_str(), sContent.size());
1187 theStream.saveIntoFile(sFilename, true);
1188 return NO_INTERRUPTION;
1189 //##protect##"saveToFile"
1190 }
1191
setCommentBegin(const std::string & sCommentBegin)1192 SEQUENCE_INTERRUPTION_LIST CGRuntime::setCommentBegin(const std::string& sCommentBegin) {
1193 //##protect##"setCommentBegin"
1194 DtaProject::getInstance().setCommentBegin(sCommentBegin);
1195 return NO_INTERRUPTION;
1196 //##protect##"setCommentBegin"
1197 }
1198
setCommentEnd(const std::string & sCommentEnd)1199 SEQUENCE_INTERRUPTION_LIST CGRuntime::setCommentEnd(const std::string& sCommentEnd) {
1200 //##protect##"setCommentEnd"
1201 DtaProject::getInstance().setCommentEnd(sCommentEnd);
1202 return NO_INTERRUPTION;
1203 //##protect##"setCommentEnd"
1204 }
1205
setGenerationHeader(const std::string & sComment)1206 SEQUENCE_INTERRUPTION_LIST CGRuntime::setGenerationHeader(const std::string& sComment) {
1207 //##protect##"setGenerationHeader"
1208 DtaProject::getInstance().setGenerationHeader(sComment);
1209 return NO_INTERRUPTION;
1210 //##protect##"setGenerationHeader"
1211 }
1212
setIncludePath(const std::string & sPath)1213 SEQUENCE_INTERRUPTION_LIST CGRuntime::setIncludePath(const std::string& sPath) {
1214 //##protect##"setIncludePath"
1215 std::list<std::string> includePath;
1216 std::string::size_type iStart = 0;
1217 std::string::size_type iEnd = sPath.find(';');
1218 while (iEnd != std::string::npos) {
1219 std::string sOnePath = sPath.substr(iStart, iEnd - iStart);
1220 if (!sOnePath.empty()) {
1221 char c = sOnePath[sOnePath.size() - 1];
1222 if ((c != '/') && (c != '\\')) sOnePath += "/";
1223 includePath.push_back(sOnePath);
1224 }
1225 iStart = iEnd + 1;
1226 iEnd = sPath.find(';', iStart);
1227 }
1228 std::string sOnePath = sPath.substr(iStart);
1229 if (!sOnePath.empty()) {
1230 char c = sOnePath[sOnePath.size() - 1];
1231 if ((c != '/') && (c != '\\')) sOnePath += "/";
1232 includePath.push_back(sOnePath);
1233 }
1234 ScpStream::setListOfIncludePaths(includePath);
1235 return NO_INTERRUPTION;
1236 //##protect##"setIncludePath"
1237 }
1238
setNow(const std::string & sConstantDateTime)1239 SEQUENCE_INTERRUPTION_LIST CGRuntime::setNow(const std::string& sConstantDateTime) {
1240 //##protect##"setNow"
1241 if (sConstantDateTime.empty()) {
1242 _sFrozenTime = "";
1243 } else {
1244 UtlDate theDate = UtlDate::getDateFromFormat(sConstantDateTime, "%d%b%Y%| %H:%M:%S%|.%L");
1245 _sFrozenTime = sConstantDateTime;
1246 }
1247 return NO_INTERRUPTION;
1248 //##protect##"setNow"
1249 }
1250
setProperty(const std::string & sDefine,const std::string & sValue)1251 SEQUENCE_INTERRUPTION_LIST CGRuntime::setProperty(const std::string& sDefine, const std::string& sValue) {
1252 //##protect##"setProperty"
1253 DtaProject::getInstance().setDefineTarget(sDefine, sValue);
1254 return NO_INTERRUPTION;
1255 //##protect##"setProperty"
1256 }
1257
setTextMode(const std::string & sTextMode)1258 SEQUENCE_INTERRUPTION_LIST CGRuntime::setTextMode(const std::string& sTextMode) {
1259 //##protect##"setTextMode"
1260 if (stricmp(sTextMode.c_str(), "dos") == 0) DtaProject::getInstance().setTextMode(DtaProject::DOS_MODE);
1261 else if (stricmp(sTextMode.c_str(), "unix") == 0) DtaProject::getInstance().setTextMode(DtaProject::UNIX_MODE);
1262 else if (stricmp(sTextMode.c_str(), "binary") == 0) DtaProject::getInstance().setTextMode(DtaProject::BINARY_MODE);
1263 else throw UtlException("setTextMode(<text-mode>) doesn't recognize \"" + sTextMode + "\" (\"DOS\" or \"UNIX\" or \"BINARY\" expected)");
1264 return NO_INTERRUPTION;
1265 //##protect##"setTextMode"
1266 }
1267
setVersion(const std::string & sVersion)1268 SEQUENCE_INTERRUPTION_LIST CGRuntime::setVersion(const std::string& sVersion) {
1269 //##protect##"setVersion"
1270 DtaProject::getInstance().setVersion(sVersion);
1271 return NO_INTERRUPTION;
1272 //##protect##"setVersion"
1273 }
1274
setWriteMode(const std::string & sMode)1275 SEQUENCE_INTERRUPTION_LIST CGRuntime::setWriteMode(const std::string& sMode) {
1276 //##protect##"setWriteMode"
1277 if (_pOutputStream == NULL) throw UtlException("no output stream on which to apply the function 'setWriteMode(\"" + sMode + "\")'!");
1278 if (stricmp(sMode.c_str(), "insert") == 0) _pOutputStream->insertMode(true);
1279 else if (stricmp(sMode.c_str(), "overwrite") == 0) _pOutputStream->insertMode(false);
1280 else throw UtlException("function 'setWriteMode()': \"insert\" or \"overwrite\" mode expected, instead of \"" + sMode + "\"");
1281 return NO_INTERRUPTION;
1282 //##protect##"setWriteMode"
1283 }
1284
setWorkingPath(const std::string & sPath)1285 SEQUENCE_INTERRUPTION_LIST CGRuntime::setWorkingPath(const std::string& sPath) {
1286 //##protect##"setWorkingPath"
1287 DtaProject::getInstance().setWorkingPath(sPath);
1288 return NO_INTERRUPTION;
1289 //##protect##"setWorkingPath"
1290 }
1291
sleep(int iMillis)1292 SEQUENCE_INTERRUPTION_LIST CGRuntime::sleep(int iMillis) {
1293 //##protect##"sleep"
1294 #ifdef WIN32
1295 Sleep(iMillis);
1296 #else
1297 usleep(iMillis*1000);
1298 #endif
1299 return NO_INTERRUPTION;
1300 //##protect##"sleep"
1301 }
1302
slideNodeContent(DtaScriptVariable * pOrgNode,ExprScriptVariable & xDestNode)1303 SEQUENCE_INTERRUPTION_LIST CGRuntime::slideNodeContent(DtaScriptVariable* pOrgNode, ExprScriptVariable& xDestNode) {
1304 //##protect##"slideNodeContent"
1305 if (pOrgNode != NULL) {
1306 pOrgNode->slideNodeContent(*pOrgNode, xDestNode);
1307 }
1308 return NO_INTERRUPTION;
1309 //##protect##"slideNodeContent"
1310 }
1311
slideNodeContent(CppParsingTree_var pOrgNode,CppParsingTree_varexpr & xDestNode)1312 SEQUENCE_INTERRUPTION_LIST CGRuntime::slideNodeContent(CppParsingTree_var pOrgNode, CppParsingTree_varexpr& xDestNode) {
1313 SEQUENCE_INTERRUPTION_LIST result = slideNodeContent(pOrgNode._pInternalNode, xDestNode.getVariableExpression());
1314 return result;
1315 }
1316
sortArray(DtaScriptVariable * pArray)1317 SEQUENCE_INTERRUPTION_LIST CGRuntime::sortArray(DtaScriptVariable* pArray) {
1318 //##protect##"sortArray"
1319 if (pArray != NULL) {
1320 pArray->sortArray();
1321 }
1322 return NO_INTERRUPTION;
1323 //##protect##"sortArray"
1324 }
1325
sortArray(CppParsingTree_var pArray)1326 SEQUENCE_INTERRUPTION_LIST CGRuntime::sortArray(CppParsingTree_var pArray) {
1327 SEQUENCE_INTERRUPTION_LIST result = sortArray(pArray._pInternalNode);
1328 return result;
1329 }
1330
traceEngine()1331 SEQUENCE_INTERRUPTION_LIST CGRuntime::traceEngine() {
1332 //##protect##"traceEngine"
1333 DtaProject::getInstance().traceEngine();
1334 return NO_INTERRUPTION;
1335 //##protect##"traceEngine"
1336 }
1337
traceLine(const std::string & sLine)1338 SEQUENCE_INTERRUPTION_LIST CGRuntime::traceLine(const std::string& sLine) {
1339 //##protect##"traceLine"
1340 if (getExternalHandling() == NULL) std::cout << sLine << std::endl;
1341 else getExternalHandling()->traceLine(sLine);
1342 if (!_sLogFile.empty()) {
1343 if (existVirtualFile(_sLogFile)) {
1344 ScpStream::appendVirtualFile(_sLogFile, sLine + CGRuntime::endl());
1345 } else {
1346 std::auto_ptr<std::ofstream> f(CodeWorker::openAppendFile(_sLogFile.c_str()));
1347 if (f.get() != NULL) {
1348 (*f) << sLine << CGRuntime::endl();
1349 f->close();
1350 }
1351 }
1352 }
1353 return NO_INTERRUPTION;
1354 //##protect##"traceLine"
1355 }
1356
traceObject(DtaScriptVariable * pObject,int iDepth)1357 SEQUENCE_INTERRUPTION_LIST CGRuntime::traceObject(DtaScriptVariable* pObject, int iDepth) {
1358 //##protect##"traceObject"
1359 if (pObject == NULL) {
1360 traceLine("null");
1361 } else {
1362 pObject->traceObject(iDepth);
1363 }
1364 return NO_INTERRUPTION;
1365 //##protect##"traceObject"
1366 }
1367
traceObject(CppParsingTree_var pObject,int iDepth)1368 SEQUENCE_INTERRUPTION_LIST CGRuntime::traceObject(CppParsingTree_var pObject, int iDepth) {
1369 SEQUENCE_INTERRUPTION_LIST result = traceObject(pObject._pInternalNode, iDepth);
1370 return result;
1371 }
1372
traceStack(DtaScriptVariable & visibility)1373 SEQUENCE_INTERRUPTION_LIST CGRuntime::traceStack(DtaScriptVariable& visibility) {
1374 //##protect##"traceStack"
1375 visibility.traceStack();
1376 return NO_INTERRUPTION;
1377 //##protect##"traceStack"
1378 }
1379
traceText(const std::string & sText)1380 SEQUENCE_INTERRUPTION_LIST CGRuntime::traceText(const std::string& sText) {
1381 //##protect##"traceText"
1382 if (getExternalHandling() == NULL) std::cout << sText << std::flush;
1383 else getExternalHandling()->traceText(sText);
1384 if (!_sLogFile.empty()) {
1385 if (existVirtualFile(_sLogFile)) {
1386 ScpStream::appendVirtualFile(_sLogFile, sText);
1387 } else {
1388 std::auto_ptr<std::ofstream> f(CodeWorker::openAppendFile(_sLogFile.c_str()));
1389 if (f.get() != NULL) {
1390 (*f) << sText << std::flush;
1391 f->close();
1392 }
1393 }
1394 }
1395 return NO_INTERRUPTION;
1396 //##protect##"traceText"
1397 }
1398
attachInputToSocket(int iSocket)1399 SEQUENCE_INTERRUPTION_LIST CGRuntime::attachInputToSocket(int iSocket) {
1400 //##protect##"attachInputToSocket"
1401 NetSocket::attachInputToSocket(iSocket);
1402 return NO_INTERRUPTION;
1403 //##protect##"attachInputToSocket"
1404 }
1405
detachInputFromSocket(int iSocket)1406 SEQUENCE_INTERRUPTION_LIST CGRuntime::detachInputFromSocket(int iSocket) {
1407 //##protect##"detachInputFromSocket"
1408 NetSocket::detachInputFromSocket(iSocket);
1409 return NO_INTERRUPTION;
1410 //##protect##"detachInputFromSocket"
1411 }
1412
goBack()1413 SEQUENCE_INTERRUPTION_LIST CGRuntime::goBack() {
1414 //##protect##"goBack"
1415 _pInputStream->goBack();
1416 return NO_INTERRUPTION;
1417 //##protect##"goBack"
1418 }
1419
setInputLocation(int iLocation)1420 SEQUENCE_INTERRUPTION_LIST CGRuntime::setInputLocation(int iLocation) {
1421 //##protect##"setInputLocation"
1422 _pInputStream->setInputLocation(iLocation);
1423 return NO_INTERRUPTION;
1424 //##protect##"setInputLocation"
1425 }
1426
allFloatingLocations(DtaScriptVariable * pList)1427 SEQUENCE_INTERRUPTION_LIST CGRuntime::allFloatingLocations(DtaScriptVariable* pList) {
1428 //##protect##"allFloatingLocations"
1429 const std::map<std::string, int>& flMap = _pInputStream->allFloatingLocations();
1430 for (std::map<std::string, int>::const_iterator i = flMap.begin(); i != flMap.end(); ++i) {
1431 pList->addElement(i->first)->setValue(i->second);
1432 }
1433 return NO_INTERRUPTION;
1434 //##protect##"allFloatingLocations"
1435 }
1436
allFloatingLocations(CppParsingTree_var pList)1437 SEQUENCE_INTERRUPTION_LIST CGRuntime::allFloatingLocations(CppParsingTree_var pList) {
1438 SEQUENCE_INTERRUPTION_LIST result = allFloatingLocations(pList._pInternalNode);
1439 return result;
1440 }
1441
attachOutputToSocket(int iSocket)1442 SEQUENCE_INTERRUPTION_LIST CGRuntime::attachOutputToSocket(int iSocket) {
1443 //##protect##"attachOutputToSocket"
1444 NetSocket::attachOutputToSocket(iSocket);
1445 return NO_INTERRUPTION;
1446 //##protect##"attachOutputToSocket"
1447 }
1448
detachOutputFromSocket(int iSocket)1449 SEQUENCE_INTERRUPTION_LIST CGRuntime::detachOutputFromSocket(int iSocket) {
1450 //##protect##"detachOutputFromSocket"
1451 NetSocket::detachOutputFromSocket(iSocket);
1452 return NO_INTERRUPTION;
1453 //##protect##"detachOutputFromSocket"
1454 }
1455
incrementIndentLevel(int iLevel)1456 SEQUENCE_INTERRUPTION_LIST CGRuntime::incrementIndentLevel(int iLevel) {
1457 //##protect##"incrementIndentLevel"
1458 _pOutputStream->incrementIndentation(iLevel);
1459 return NO_INTERRUPTION;
1460 //##protect##"incrementIndentLevel"
1461 }
1462
insertText(int iLocation,const std::string & sText)1463 SEQUENCE_INTERRUPTION_LIST CGRuntime::insertText(int iLocation, const std::string& sText) {
1464 //##protect##"insertText"
1465 if (!_pOutputStream->insertText(sText, iLocation, 0)) {
1466 std::string sMessage = "unable to insert \"" + composeCLikeString(sText) + "\" at position ";
1467 char tcNumber[32];
1468 sprintf(tcNumber, "%d/%ld", iLocation, _pOutputStream->size());
1469 sMessage += tcNumber;
1470 throw UtlException(sMessage);
1471 }
1472 return NO_INTERRUPTION;
1473 //##protect##"insertText"
1474 }
1475
insertTextOnce(int iLocation,const std::string & sText)1476 SEQUENCE_INTERRUPTION_LIST CGRuntime::insertTextOnce(int iLocation, const std::string& sText) {
1477 //##protect##"insertTextOnce"
1478 if (!_pOutputStream->insertTextOnce(sText, iLocation, 0)) {
1479 if ((iLocation < 0) || (iLocation > _pOutputStream->size())) {
1480 std::string sMessage = "unable to insert \"" + composeCLikeString(sText) + "\" at position ";
1481 char tcNumber[32];
1482 sprintf(tcNumber, "%d/%ld", iLocation, _pOutputStream->size());
1483 sMessage += tcNumber;
1484 throw UtlException(sMessage);
1485 }
1486 }
1487 return NO_INTERRUPTION;
1488 //##protect##"insertTextOnce"
1489 }
1490
insertTextToFloatingLocation(const std::string & sLocation,const std::string & sText)1491 SEQUENCE_INTERRUPTION_LIST CGRuntime::insertTextToFloatingLocation(const std::string& sLocation, const std::string& sText) {
1492 //##protect##"insertTextToFloatingLocation"
1493 ScpStream* pOwner;
1494 int iLocation = _pOutputStream->getFloatingLocation(sLocation, pOwner);
1495 if (pOwner == NULL) throw UtlException("the floating location '" + sLocation + "' doesn't exist");
1496 if (!pOwner->insertText(sText, iLocation, 0)) {
1497 std::string sMessage = "unable to insert \"" + composeCLikeString(sText) + "\" at position ";
1498 char tcNumber[32];
1499 sprintf(tcNumber, "%d/%ld", iLocation, pOwner->size());
1500 sMessage += tcNumber;
1501 throw UtlException(sMessage);
1502 }
1503 return NO_INTERRUPTION;
1504 //##protect##"insertTextToFloatingLocation"
1505 }
1506
insertTextOnceToFloatingLocation(const std::string & sLocation,const std::string & sText)1507 SEQUENCE_INTERRUPTION_LIST CGRuntime::insertTextOnceToFloatingLocation(const std::string& sLocation, const std::string& sText) {
1508 //##protect##"insertTextOnceToFloatingLocation"
1509 ScpStream* pOwner;
1510 int iLocation = _pOutputStream->getFloatingLocation(sLocation, pOwner);
1511 if (pOwner == NULL) throw UtlException("the floating location '" + sLocation + "' doesn't exist");
1512 if (!pOwner->insertTextOnce(sText, iLocation, 0)) {
1513 if ((iLocation < 0) || (iLocation > pOwner->size())) {
1514 std::string sMessage = "unable to insert \"" + composeCLikeString(sText) + "\" at position ";
1515 char tcNumber[32];
1516 sprintf(tcNumber, "%d/%ld", iLocation, pOwner->size());
1517 sMessage += tcNumber;
1518 throw UtlException(sMessage);
1519 }
1520 }
1521 return NO_INTERRUPTION;
1522 //##protect##"insertTextOnceToFloatingLocation"
1523 }
1524
overwritePortion(int iLocation,const std::string & sText,int iSize)1525 SEQUENCE_INTERRUPTION_LIST CGRuntime::overwritePortion(int iLocation, const std::string& sText, int iSize) {
1526 //##protect##"overwritePortion"
1527 if (!_pOutputStream->insertText(sText, iLocation, iSize)) {
1528 std::string sMessage = "unable to overwrite \"" + composeCLikeString(sText) + "\" at position ";
1529 char tcNumber[32];
1530 sprintf(tcNumber, "%d/%ld", iLocation, _pOutputStream->size());
1531 sMessage += tcNumber;
1532 throw UtlException(sMessage);
1533 }
1534 return NO_INTERRUPTION;
1535 //##protect##"overwritePortion"
1536 }
1537
populateProtectedArea(const std::string & sProtectedAreaName,const std::string & sContent)1538 SEQUENCE_INTERRUPTION_LIST CGRuntime::populateProtectedArea(const std::string& sProtectedAreaName, const std::string& sContent) {
1539 //##protect##"populateProtectedArea"
1540 _listOfPatternScripts.front()->populateProtectedArea(sProtectedAreaName, sContent);
1541 return NO_INTERRUPTION;
1542 //##protect##"populateProtectedArea"
1543 }
1544
resizeOutputStream(int iNewSize)1545 SEQUENCE_INTERRUPTION_LIST CGRuntime::resizeOutputStream(int iNewSize) {
1546 //##protect##"resizeOutputStream"
1547 _pOutputStream->resize(iNewSize);
1548 return NO_INTERRUPTION;
1549 //##protect##"resizeOutputStream"
1550 }
1551
setFloatingLocation(const std::string & sKey,int iLocation)1552 SEQUENCE_INTERRUPTION_LIST CGRuntime::setFloatingLocation(const std::string& sKey, int iLocation) {
1553 //##protect##"setFloatingLocation"
1554 _pOutputStream->setFloatingLocation(sKey, iLocation);
1555 return NO_INTERRUPTION;
1556 //##protect##"setFloatingLocation"
1557 }
1558
setOutputLocation(int iLocation)1559 SEQUENCE_INTERRUPTION_LIST CGRuntime::setOutputLocation(int iLocation) {
1560 //##protect##"setOutputLocation"
1561 if (iLocation == -1) _pOutputStream->setOutputLocation(_pOutputStream->size());
1562 else _pOutputStream->setOutputLocation(iLocation);
1563 return NO_INTERRUPTION;
1564 //##protect##"setOutputLocation"
1565 }
1566
setProtectedArea(const std::string & sProtectedAreaName)1567 SEQUENCE_INTERRUPTION_LIST CGRuntime::setProtectedArea(const std::string& sProtectedAreaName) {
1568 //##protect##"setProtectedArea"
1569 _listOfPatternScripts.front()->setProtectedArea(sProtectedAreaName);
1570 return NO_INTERRUPTION;
1571 //##protect##"setProtectedArea"
1572 }
1573
writeBytes(const std::string & sBytes)1574 SEQUENCE_INTERRUPTION_LIST CGRuntime::writeBytes(const std::string& sBytes) {
1575 //##protect##"writeBytes"
1576 int iLength = sBytes.size();
1577 if ((iLength % 2) != 0) throw UtlException("writeBytes(\"" + sBytes + "\"): a binary content cannot have an odd length");
1578 iLength >>= 1;
1579 unsigned char* tcBinary = new unsigned char[iLength];
1580 if (!convertBytesToChars(sBytes, tcBinary, iLength)) {
1581 delete [] tcBinary;
1582 throw UtlException("writeBytes(...): about the binary content, invalid hexadecimal digit encountered");
1583 }
1584 _pOutputStream->writeBinaryData((const char*) tcBinary, iLength);
1585 delete [] tcBinary;
1586 return NO_INTERRUPTION;
1587 //##protect##"writeBytes"
1588 }
1589
writeText(const std::string & sText)1590 SEQUENCE_INTERRUPTION_LIST CGRuntime::writeText(const std::string& sText) {
1591 //##protect##"writeText"
1592 _pOutputStream->writeBinaryData(sText.c_str(), sText.size());
1593 return NO_INTERRUPTION;
1594 //##protect##"writeText"
1595 }
1596
writeTextOnce(const std::string & sText)1597 SEQUENCE_INTERRUPTION_LIST CGRuntime::writeTextOnce(const std::string& sText) {
1598 //##protect##"writeTextOnce"
1599 _pOutputStream->writeTextOnce(sText.c_str());
1600 return NO_INTERRUPTION;
1601 //##protect##"writeTextOnce"
1602 }
1603
closeSocket(int iSocket)1604 SEQUENCE_INTERRUPTION_LIST CGRuntime::closeSocket(int iSocket) {
1605 //##protect##"closeSocket"
1606 NetSocket::closeSocket(iSocket);
1607 return NO_INTERRUPTION;
1608 //##protect##"closeSocket"
1609 }
1610
flushOutputToSocket(int iSocket)1611 bool CGRuntime::flushOutputToSocket(int iSocket) {
1612 //##protect##"flushOutputToSocket"
1613 return NetSocket::flushOutputToSocket(iSocket);
1614 //##protect##"flushOutputToSocket"
1615 }
1616
acceptSocket(int iServerSocket)1617 int CGRuntime::acceptSocket(int iServerSocket) {
1618 //##protect##"acceptSocket"
1619 return NetSocket::acceptSocket(iServerSocket);
1620 //##protect##"acceptSocket"
1621 }
1622
add(double dLeft,double dRight)1623 double CGRuntime::add(double dLeft, double dRight) {
1624 //##protect##"add"
1625 return dLeft + dRight;
1626 //##protect##"add"
1627 }
1628
addToDate(const std::string & sDate,const std::string & sFormat,const std::string & sShifting)1629 std::string CGRuntime::addToDate(const std::string& sDate, const std::string& sFormat, const std::string& sShifting) {
1630 //##protect##"addToDate"
1631 UtlDate theDate = UtlDate::getDateFromFormat(sDate, "%d%b%Y%| %H:%M:%S%|.%L");
1632 theDate.addDateFromFormat(sFormat, sShifting);
1633 if (theDate.getMillis() > 0) {
1634 return theDate.getFormattedDate("%d%b%Y %H:%M:%S.%L");
1635 }
1636 if ((theDate.getHour() == 0) && (theDate.getMin() == 0) && (theDate.getSec() == 0)) {
1637 return theDate.getFormattedDate("%d%b%Y");
1638 }
1639 return theDate.getFormattedDate("%d%b%Y %H:%M:%S");
1640 //##protect##"addToDate"
1641 }
1642
byteToChar(const std::string & sByte)1643 std::string CGRuntime::byteToChar(const std::string& sByte) {
1644 //##protect##"byteToChar"
1645 if (sByte.size() != 2) throw UtlException("'" + composeCLikeString(sByte) + "' isn't recognized as a byte");
1646 unsigned char c;
1647 char a = sByte[0];
1648 if (a <= '9') {
1649 if (a < '0') throw UtlException("byteToChar(\"" + sByte + "\"): invalid hexadecimal digit '" + composeCLikeString(std::string(1, a)) + "' encountered");
1650 c = a - '0';
1651 } else if (a <= 'F') {
1652 if (a < 'A') throw UtlException("byteToChar(\"" + sByte + "\"): invalid hexadecimal digit '" + std::string(1, a) + "' encountered");
1653 c = (a - 'A') + 10;
1654 } else if ((a >= 'a') && (a <= 'f')) {
1655 c = (a - 'a') + 10;
1656 } else {
1657 throw UtlException("byteToChar((\"" + sByte + "\"): invalid hexadecimal digit '" + std::string(1, a) + "' encountered");
1658 }
1659 c <<= 4;
1660 a = sByte[1];
1661 if (a <= '9') {
1662 if (a < '0') throw UtlException("byteToChar(\"" + sByte + "\"): invalid hexadecimal digit '" + composeCLikeString(std::string(1, a)) + "' encountered");
1663 c += a - '0';
1664 } else if (a <= 'F') {
1665 if (a < 'A') throw UtlException("byteToChar(\"" + sByte + "\"): invalid hexadecimal digit '" + std::string(1, a) + "' encountered");
1666 c += (a - 'A') + 10;
1667 } else if ((a >= 'a') && (a <= 'f')) {
1668 c += (a - 'a') + 10;
1669 } else {
1670 throw UtlException("byteToChar((\"" + sByte + "\"): invalid hexadecimal digit '" + std::string(1, a) + "' encountered");
1671 }
1672 if (c == '\0') return "";
1673 return std::string(1, (char) c);
1674 //##protect##"byteToChar"
1675 }
1676
bytesToLong(const std::string & sBytes)1677 unsigned long CGRuntime::bytesToLong(const std::string& sBytes) {
1678 //##protect##"bytesToLong"
1679 if (sBytes.size() != 8) throw UtlException("'" + composeCLikeString(sBytes) + "' isn't recognized as a 4-bytes sequence");
1680 unsigned long iLong;
1681 if (!convertBytesToChars(sBytes, (unsigned char*) &iLong, 4)) throw UtlException("invalid hexadecimal digit in the sequence of bytes '" + composeCLikeString(sBytes) + "'");
1682 return iLong;
1683 //##protect##"bytesToLong"
1684 }
1685
bytesToShort(const std::string & sBytes)1686 unsigned short CGRuntime::bytesToShort(const std::string& sBytes) {
1687 //##protect##"bytesToShort"
1688 if (sBytes.size() != 4) throw UtlException("'" + composeCLikeString(sBytes) + "' isn't recognized as a 4-bytes sequence");
1689 unsigned short iShort;
1690 if (!convertBytesToChars(sBytes, (unsigned char*) &iShort, 2)) throw UtlException("invalid hexadecimal digit in the sequence of bytes '" + composeCLikeString(sBytes) + "'");
1691 return iShort;
1692 //##protect##"bytesToShort"
1693 }
1694
canonizePath(const std::string & sPath)1695 std::string CGRuntime::canonizePath(const std::string& sPath) {
1696 //##protect##"canonizePath"
1697 char tcReference[MAX_PATH];
1698 std::string sDirectory = getCurrentDirectory();
1699 strcpy(tcReference, sDirectory.c_str());
1700 toSlashes_(tcReference);
1701 return canonize_(sPath.c_str(), tcReference);
1702 //##protect##"canonizePath"
1703 }
1704
changeDirectory(const std::string & sPath)1705 bool CGRuntime::changeDirectory(const std::string& sPath) {
1706 //##protect##"changeDirectory"
1707 #ifdef WIN32
1708 return (_chdir(sPath.c_str()) == 0);
1709 #else
1710 return (chdir(sPath.c_str()) == 0);
1711 #endif
1712 //##protect##"changeDirectory"
1713 }
1714
changeFileTime(const std::string & sFilename,const std::string & sAccessTime,const std::string & sModificationTime)1715 int CGRuntime::changeFileTime(const std::string& sFilename, const std::string& sAccessTime, const std::string& sModificationTime) {
1716 //##protect##"changeFileTime"
1717 UtlDate theAccessTime = UtlDate::getDateFromFormat(sAccessTime, "%d%b%Y%| %H:%M:%S%|.%L");
1718 UtlDate theModificationTime = UtlDate::getDateFromFormat(sModificationTime, "%d%b%Y%| %H:%M:%S%|.%L");
1719 struct utimbuf theTimes;
1720 struct tm theDate;
1721 theDate.tm_mday = theAccessTime.getDay();
1722 theDate.tm_mon = theAccessTime.getMonth() - 1;
1723 theDate.tm_year = theAccessTime.getYear() - 1900;
1724 theDate.tm_hour = theAccessTime.getHour();
1725 theDate.tm_min = theAccessTime.getMin();
1726 theDate.tm_sec = theAccessTime.getSec();
1727 theTimes.actime = mktime(&theDate);
1728 theDate.tm_mday = theModificationTime.getDay();
1729 theDate.tm_mon = theModificationTime.getMonth() - 1;
1730 theDate.tm_year = theModificationTime.getYear() - 1900;
1731 theDate.tm_hour = theModificationTime.getHour();
1732 theDate.tm_min = theModificationTime.getMin();
1733 theDate.tm_sec = theModificationTime.getSec();
1734 theTimes.modtime = mktime(&theDate);
1735 if (utime(sFilename.c_str(), &theTimes) == -1) {
1736 switch(errno) {
1737 case EACCES: return -2;
1738 case EMFILE: return -3;
1739 case ENOENT: return -4;
1740 case EINVAL: return -5;
1741 default: return -1;
1742 }
1743 }
1744 return 0;
1745 //##protect##"changeFileTime"
1746 }
1747
charAt(const std::string & sText,int iIndex)1748 std::string CGRuntime::charAt(const std::string& sText, int iIndex) {
1749 //##protect##"charAt"
1750 if ((iIndex < 0) || (iIndex >= (int) sText.size())) return "";
1751 std::string sResult(1, sText[iIndex]);
1752 return sResult;
1753 //##protect##"charAt"
1754 }
1755
charToByte(const std::string & sChar)1756 std::string CGRuntime::charToByte(const std::string& sChar) {
1757 //##protect##"charToByte"
1758 if (sChar.size() > 1) throw UtlException("charToByte('" + composeCLikeString(sChar) + "'): the parameter is bigger than a character");
1759 unsigned char c = sChar[0];
1760 char tcContent[] = {0, 0, 0};
1761 tcContent[0] = _tcHexa[c >> 4];
1762 tcContent[1] = _tcHexa[c & 0x0F];
1763 return tcContent;
1764 //##protect##"charToByte"
1765 }
1766
charToInt(const std::string & sChar)1767 int CGRuntime::charToInt(const std::string& sChar) {
1768 //##protect##"charToInt"
1769 if (sChar.size() != 1) return 0;
1770 return (int) ((unsigned char) (sChar[0]));
1771 //##protect##"charToInt"
1772 }
1773
chmod(const std::string & sFilename,const std::string & sMode)1774 bool CGRuntime::chmod(const std::string& sFilename, const std::string& sMode) {
1775 //##protect##"chmod"
1776 int iMode = 0;
1777 for (std::string::size_type i = 0; i < sMode.size(); i++) {
1778 char a = sMode[i];
1779 #ifdef WIN32
1780 if ((a == 'R') || (a == 'r')) iMode = iMode | _S_IREAD;
1781 else if ((a == 'W') || (a == 'w')) iMode = iMode | _S_IWRITE;
1782 else if ((a == 'X') || (a == 'x')) iMode = iMode | _S_IEXEC;
1783 #else
1784 if ((a == 'R') || (a == 'r')) iMode = iMode | S_IRUSR;
1785 else if ((a == 'W') || (a == 'w')) iMode = iMode | S_IWUSR;
1786 else if ((a == 'X') || (a == 'x')) iMode = iMode | S_IXUSR;
1787 #endif
1788 else throw UtlException("invalid access mode '" + sMode + "' encountered by function 'chmod'");
1789 }
1790 if (iMode != 0) return (::chmod(sFilename.c_str(), iMode) == 0);
1791 return true;
1792 //##protect##"chmod"
1793 }
1794
ceil(double dNumber)1795 int CGRuntime::ceil(double dNumber) {
1796 //##protect##"ceil"
1797 return (int) ::ceil(dNumber);
1798 //##protect##"ceil"
1799 }
1800
compareDate(const std::string & sDate1,const std::string & sDate2)1801 int CGRuntime::compareDate(const std::string& sDate1, const std::string& sDate2) {
1802 //##protect##"compareDate"
1803 UtlDate theDate1 = UtlDate::getDateFromFormat(sDate1, "%d%b%Y%| %H:%M:%S%|.%L");
1804 UtlDate theDate2 = UtlDate::getDateFromFormat(sDate2, "%d%b%Y%| %H:%M:%S%|.%L");
1805 if (theDate1 < theDate2) return -1;
1806 if (theDate1 > theDate2) return 1;
1807 return 0;
1808 //##protect##"compareDate"
1809 }
1810
completeDate(const std::string & sDate,const std::string & sFormat)1811 std::string CGRuntime::completeDate(const std::string& sDate, const std::string& sFormat) {
1812 //##protect##"completeDate"
1813 UtlDate theDate = UtlDate::getDateFromFormat(sDate, sFormat);
1814 if (theDate.getMillis() > 0) {
1815 return theDate.getFormattedDate("%d%b%Y %H:%M:%S.%L");
1816 }
1817 if ((theDate.getHour() == 0) && (theDate.getMin() == 0) && (theDate.getSec() == 0)) {
1818 return theDate.getFormattedDate("%d%b%Y");
1819 }
1820 return theDate.getFormattedDate("%d%b%Y %H:%M:%S");
1821 //##protect##"completeDate"
1822 }
1823
completeLeftSpaces(const std::string & sText,int iLength)1824 std::string CGRuntime::completeLeftSpaces(const std::string& sText, int iLength) {
1825 //##protect##"completeLeftSpaces"
1826 if ((int) sText.size() >= iLength) return sText;
1827 std::string sSpaces(iLength - sText.size(), ' ');
1828 return sSpaces + sText;
1829 //##protect##"completeLeftSpaces"
1830 }
1831
completeRightSpaces(const std::string & sText,int iLength)1832 std::string CGRuntime::completeRightSpaces(const std::string& sText, int iLength) {
1833 //##protect##"completeRightSpaces"
1834 if ((int) sText.size() >= iLength) return sText;
1835 std::string sSpaces(iLength - sText.size(), ' ');
1836 return sText + sSpaces;
1837 //##protect##"completeRightSpaces"
1838 }
1839
composeAdaLikeString(const std::string & sText)1840 std::string CGRuntime::composeAdaLikeString(const std::string& sText) {
1841 //##protect##"composeAdaLikeString"
1842 std::string sResult;
1843 char* u = (char*) sText.c_str();
1844 while (*u != '\0') {
1845 if (*u == '"') {
1846 sResult += "\"\"";
1847 } else {
1848 sResult += *u;
1849 }
1850 u++;
1851 }
1852 return sResult;
1853 //##protect##"composeAdaLikeString"
1854 }
1855
composeCLikeString(const std::string & sText)1856 std::string CGRuntime::composeCLikeString(const std::string& sText) {
1857 //##protect##"composeCLikeString"
1858 std::string sResult;
1859 char* u = (char*) sText.c_str();
1860 while (*u != '\0') {
1861 switch(*u) {
1862 case '\\': sResult += "\\\\";break;
1863 case '\"': sResult += "\\\"";break;
1864 case '\a': sResult += "\\a";break;
1865 case '\b': sResult += "\\b";break;
1866 case '\f': sResult += "\\f";break;
1867 case '\n': sResult += "\\n";break;
1868 case '\r': sResult += "\\r";break;
1869 case '\t': sResult += "\\t";break;
1870 case '\v': sResult += "\\v";break;
1871 default:
1872 sResult += *u;
1873 }
1874 u++;
1875 }
1876 return sResult;
1877 //##protect##"composeCLikeString"
1878 }
1879
composeHTMLLikeString(const std::string & sText)1880 std::string CGRuntime::composeHTMLLikeString(const std::string& sText) {
1881 //##protect##"composeHTMLLikeString"
1882 static std::map<char, std::string> mapOfCodes;
1883 if (mapOfCodes.empty()) {
1884 mapOfCodes['\''] = "'";
1885 mapOfCodes['�'] = "“";
1886 mapOfCodes['�'] = "”";
1887 // mapOfCodes['-'] = "–";
1888 mapOfCodes['�'] = "°";
1889
1890 mapOfCodes['�'] = "à";
1891 mapOfCodes['�'] = "â";
1892 mapOfCodes['�'] = "å";
1893 mapOfCodes['�'] = "ä";
1894 mapOfCodes['�'] = "ã";
1895
1896 mapOfCodes['�'] = "é";
1897 mapOfCodes['�'] = "è";
1898 mapOfCodes['�'] = "ê";
1899 mapOfCodes['�'] = "ë";
1900
1901 mapOfCodes['�'] = "ì";
1902 mapOfCodes['�'] = "í";
1903 mapOfCodes['�'] = "î";
1904 mapOfCodes['�'] = "ï";
1905
1906 mapOfCodes['�'] = "ô";
1907 mapOfCodes['�'] = "Ø";
1908 mapOfCodes['�'] = "ó";
1909 mapOfCodes['�'] = "ö";
1910
1911 mapOfCodes['�'] = "û";
1912 mapOfCodes['�'] = "ù";
1913 mapOfCodes['�'] = "ü";
1914
1915 mapOfCodes['�'] = "ÿ";
1916
1917 mapOfCodes['�'] = "ç";
1918 mapOfCodes['�'] = "ñ";
1919 mapOfCodes['�'] = "ß";
1920 mapOfCodes['�'] = "Þ";
1921
1922 mapOfCodes['&'] = "&";
1923 mapOfCodes['\"'] = """;
1924 mapOfCodes['<'] = "<";
1925 mapOfCodes['>'] = ">";
1926 mapOfCodes['�'] = "¨";
1927 mapOfCodes['�'] = "¢";
1928 mapOfCodes['�'] = "£";
1929 mapOfCodes['�'] = "©";
1930 }
1931 std::string sHTMLText;
1932 std::map<char, std::string>::iterator cursor;
1933 for (std::string::size_type i = 0; i < sText.size(); i++) {
1934 char a = sText[i];
1935 cursor = mapOfCodes.find(a);
1936 if (cursor != mapOfCodes.end()) sHTMLText += cursor->second;
1937 else sHTMLText += a;
1938 }
1939 return sHTMLText;
1940 //##protect##"composeHTMLLikeString"
1941 }
1942
composeSQLLikeString(const std::string & sText)1943 std::string CGRuntime::composeSQLLikeString(const std::string& sText) {
1944 //##protect##"composeSQLLikeString"
1945 std::string sResult = composeCLikeString(sText);
1946 std::string::size_type iLastPos = 0;
1947 std::string::size_type iPos = sResult.find('\'');
1948 std::string sReplace;
1949 while (iPos != std::string::npos) {
1950 iPos++;
1951 if (iPos == sResult.size()) sReplace += sResult.substr(iLastPos);
1952 else sReplace += sResult.substr(iLastPos, iPos - iLastPos);
1953 sReplace += "'";
1954 iLastPos = iPos;
1955 iPos = sResult.find('\'', iLastPos);
1956 }
1957 if (iLastPos != sResult.size()) sReplace += sResult.substr(iLastPos);
1958 return sReplace;
1959 //##protect##"composeSQLLikeString"
1960 }
1961
computeMD5(const std::string & sText)1962 std::string CGRuntime::computeMD5(const std::string& sText) {
1963 //##protect##"computeMD5"
1964 md5_context ctx;
1965 unsigned char tcMD5sum[16];
1966 md5_starts(&ctx);
1967 md5_update(&ctx, (unsigned char *) sText.c_str(), sText.size());
1968 md5_finish(&ctx, tcMD5sum);
1969
1970 char tcResult[33];
1971 for(int i = 0; i < 16; ++i)
1972 sprintf(tcResult + i * 2, "%02X", tcMD5sum[i]);
1973
1974 return tcResult;
1975 //##protect##"computeMD5"
1976 }
1977
copySmartFile(const std::string & sSourceFileName,const std::string & sDestinationFileName)1978 bool CGRuntime::copySmartFile(const std::string& sSourceFileName, const std::string& sDestinationFileName) {
1979 //##protect##"copySmartFile"
1980 std::auto_ptr<ScpStream> pInput(new ScpStream(sSourceFileName, ScpStream::IN | ScpStream::PATH));
1981 std::auto_ptr<ScpStream> pOutput(new ScpStream(sDestinationFileName, ScpStream::IN | ScpStream::OUT));
1982 int iPosition;
1983 bool bCopy = !DtaScript::equalsIgnoringGenerationHeader(*pInput, *pOutput, iPosition);
1984 if (bCopy) pInput->saveIntoFile(sDestinationFileName, true);
1985 return bCopy;
1986 //##protect##"copySmartFile"
1987 }
1988
coreString(const std::string & sText,int iPos,int iLastRemoved)1989 std::string CGRuntime::coreString(const std::string& sText, int iPos, int iLastRemoved) {
1990 //##protect##"coreString"
1991 register int iSum = iPos + iLastRemoved;
1992 if ((iPos < 0) || (iLastRemoved < 0) || (iSum >= (int) sText.size())) return "";
1993 if (iLastRemoved == 0) return sText.substr(iPos);
1994 return sText.substr(iPos, ((int) sText.size()) - iSum);
1995 //##protect##"coreString"
1996 }
1997
countStringOccurences(const std::string & sString,const std::string & sText)1998 int CGRuntime::countStringOccurences(const std::string& sString, const std::string& sText) {
1999 //##protect##"countStringOccurences"
2000 std::string::size_type iPos = sString.find(sText);
2001 int iOccurences = 0;
2002 while (iPos != std::string::npos) {
2003 iOccurences++;
2004 iPos = sString.find(sText, iPos + 1);
2005 }
2006 return iOccurences;
2007 //##protect##"countStringOccurences"
2008 }
2009
createDirectory(const std::string & sPath)2010 bool CGRuntime::createDirectory(const std::string& sPath) {
2011 //##protect##"createDirectory"
2012 if (sPath.empty()) return false;
2013 char a = sPath[sPath.size() - 1];
2014 std::string sTemp = sPath;
2015 if ((a != '\\') && (a != '/')) sTemp += "/empty.dir";
2016 else sTemp += "empty.dir";
2017 return createDirectoriesForFile(sTemp);
2018 //##protect##"createDirectory"
2019 }
2020
createINETClientSocket(const std::string & sRemoteAddress,int iPort)2021 int CGRuntime::createINETClientSocket(const std::string& sRemoteAddress, int iPort) {
2022 //##protect##"createINETClientSocket"
2023 return NetSocket::createINETClientSocket(sRemoteAddress.c_str(), iPort);
2024 //##protect##"createINETClientSocket"
2025 }
2026
createINETServerSocket(int iPort,int iBackLog)2027 int CGRuntime::createINETServerSocket(int iPort, int iBackLog) {
2028 //##protect##"createINETServerSocket"
2029 return NetSocket::createINETServerSocket(iPort, iBackLog);
2030 //##protect##"createINETServerSocket"
2031 }
2032
createIterator(DtaScriptVariable * pI,DtaScriptVariable * pList)2033 bool CGRuntime::createIterator(DtaScriptVariable* pI, DtaScriptVariable* pList) {
2034 //##protect##"createIterator"
2035 if (pList->getArray() == NULL) return false;
2036 pI->setValue(new DtaListIterator(*pList->getArray()));
2037 return true;
2038 //##protect##"createIterator"
2039 }
2040
createIterator(CppParsingTree_var pI,CppParsingTree_var pList)2041 bool CGRuntime::createIterator(CppParsingTree_var pI, CppParsingTree_var pList) {
2042 bool result = createIterator(pI._pInternalNode, pList._pInternalNode);
2043 return result;
2044 }
2045
createReverseIterator(DtaScriptVariable * pI,DtaScriptVariable * pList)2046 bool CGRuntime::createReverseIterator(DtaScriptVariable* pI, DtaScriptVariable* pList) {
2047 //##protect##"createReverseIterator"
2048 if (pList->getArray() == NULL) return false;
2049 pI->setValue(new DtaReverseListIterator(*pList->getArray()));
2050 return true;
2051 //##protect##"createReverseIterator"
2052 }
2053
createReverseIterator(CppParsingTree_var pI,CppParsingTree_var pList)2054 bool CGRuntime::createReverseIterator(CppParsingTree_var pI, CppParsingTree_var pList) {
2055 bool result = createReverseIterator(pI._pInternalNode, pList._pInternalNode);
2056 return result;
2057 }
2058
createVirtualFile(const std::string & sHandle,const std::string & sContent)2059 bool CGRuntime::createVirtualFile(const std::string& sHandle, const std::string& sContent) {
2060 //##protect##"createVirtualFile"
2061 return ScpStream::createVirtualFile(sHandle, sContent);
2062 //##protect##"createVirtualFile"
2063 }
2064
createVirtualTemporaryFile(const std::string & sContent)2065 std::string CGRuntime::createVirtualTemporaryFile(const std::string& sContent) {
2066 //##protect##"createVirtualTemporaryFile"
2067 return ScpStream::createVirtualTemporaryFile(sContent);
2068 //##protect##"createVirtualTemporaryFile"
2069 }
2070
decodeURL(const std::string & sURL)2071 std::string CGRuntime::decodeURL(const std::string& sURL) {
2072 //##protect##"decodeURL"
2073 std::string sResult;
2074 for (std::string::size_type i = 0; i < sURL.size(); i++) {
2075 char a = (unsigned char) sURL[i];
2076 if (a == '%') {
2077 unsigned char c;
2078 i++;
2079 a = (unsigned char) sURL[i];
2080 if (a <= '9') c = (a - '0') << 4;
2081 else if (a <= 'F') c = (a - ('A' - (char) 10)) << 4;
2082 else c = (a - ('a' - (char) 10)) << 4;
2083 i++;
2084 a = (unsigned char) sURL[i];
2085 if (a <= '9') c += (a - '0');
2086 else if (a <= 'F') c += (a - ('A' - (char) 10));
2087 else c += (a - ('a' - (char) 10));
2088 sResult += c;
2089 } else if (a == '+') {
2090 sResult += ' ';
2091 } else {
2092 sResult += a;
2093 }
2094 }
2095 return sResult;
2096 //##protect##"decodeURL"
2097 }
2098
decrement(double & dNumber)2099 double CGRuntime::decrement(double& dNumber) {
2100 //##protect##"decrement"
2101 dNumber = dNumber - 1.0;
2102 return dNumber;
2103 //##protect##"decrement"
2104 }
2105
decrement(CppParsingTree_var pNumber)2106 double CGRuntime::decrement(CppParsingTree_var pNumber) {
2107 double dNumber = pNumber.getDoubleValue();
2108 double result = decrement(dNumber);
2109 pNumber.setValue(dNumber);
2110 return result;
2111 }
2112
deleteFile(const std::string & sFilename)2113 bool CGRuntime::deleteFile(const std::string& sFilename) {
2114 //##protect##"deleteFile"
2115 return (unlink(sFilename.c_str()) == 0);
2116 //##protect##"deleteFile"
2117 }
2118
deleteVirtualFile(const std::string & sHandle)2119 bool CGRuntime::deleteVirtualFile(const std::string& sHandle) {
2120 //##protect##"deleteVirtualFile"
2121 return ScpStream::deleteVirtualFile(sHandle);
2122 //##protect##"deleteVirtualFile"
2123 }
2124
div(double dDividend,double dDivisor)2125 double CGRuntime::div(double dDividend, double dDivisor) {
2126 //##protect##"div"
2127 return dDividend / dDivisor;
2128 //##protect##"div"
2129 }
2130
duplicateIterator(DtaScriptVariable * pOldIt,DtaScriptVariable * pNewIt)2131 bool CGRuntime::duplicateIterator(DtaScriptVariable* pOldIt, DtaScriptVariable* pNewIt) {
2132 //##protect##"duplicateIterator"
2133 if (pOldIt->getIteratorData() == NULL) return false;
2134 pNewIt->setValue(pOldIt->getIteratorData()->clone());
2135 return true;
2136 //##protect##"duplicateIterator"
2137 }
2138
duplicateIterator(CppParsingTree_var pOldIt,CppParsingTree_var pNewIt)2139 bool CGRuntime::duplicateIterator(CppParsingTree_var pOldIt, CppParsingTree_var pNewIt) {
2140 bool result = duplicateIterator(pOldIt._pInternalNode, pNewIt._pInternalNode);
2141 return result;
2142 }
2143
encodeURL(const std::string & sURL)2144 std::string CGRuntime::encodeURL(const std::string& sURL) {
2145 //##protect##"encodeURL"
2146 std::string sResult;
2147 char percentChar[4];
2148 percentChar[0] = '%';
2149 percentChar[3] = '\0';
2150 for (std::string::size_type i = 0; i < sURL.size(); i++) {
2151 unsigned char a = (unsigned char) (sURL[i]);
2152 if (((a < 'a') || (a > 'z')) && ((a < 'A') || (a > 'Z')) && ((a < '0') || (a > '9'))) {
2153 percentChar[1] = _tcHexa[a >> 4];
2154 percentChar[2] = _tcHexa[a & 0x0F];
2155 sResult += percentChar;
2156 } else {
2157 sResult += (char) a;
2158 }
2159 }
2160 return sResult;
2161 //##protect##"encodeURL"
2162 }
2163
endl()2164 std::string CGRuntime::endl() {
2165 //##protect##"endl"
2166 return ScpStream::ENDL;
2167 //##protect##"endl"
2168 }
2169
endString(const std::string & sText,const std::string & sEnd)2170 bool CGRuntime::endString(const std::string& sText, const std::string& sEnd) {
2171 //##protect##"endString"
2172 int iPos = sText.size() - sEnd.size();
2173 if (iPos >= 0) {
2174 if (strncmp(sText.c_str() + iPos, sEnd.c_str(), sEnd.size()) == 0) return true;
2175 }
2176 return false;
2177 //##protect##"endString"
2178 }
2179
equal(double dLeft,double dRight)2180 bool CGRuntime::equal(double dLeft, double dRight) {
2181 //##protect##"equal"
2182 return dLeft == dRight;
2183 //##protect##"equal"
2184 }
2185
equalsIgnoreCase(const std::string & sLeft,const std::string & sRight)2186 bool CGRuntime::equalsIgnoreCase(const std::string& sLeft, const std::string& sRight) {
2187 //##protect##"equalsIgnoreCase"
2188 return (stricmp(sLeft.c_str(), sRight.c_str()) == 0);
2189 //##protect##"equalsIgnoreCase"
2190 }
2191
equalTrees(DtaScriptVariable * pFirstTree,DtaScriptVariable * pSecondTree)2192 bool CGRuntime::equalTrees(DtaScriptVariable* pFirstTree, DtaScriptVariable* pSecondTree) {
2193 //##protect##"equalTrees"
2194 if (pFirstTree == NULL) {
2195 throw UtlException("the first tree parameter passed to the procedure 'equalTrees' doesn't exist");
2196 }
2197 if (pSecondTree == NULL) {
2198 throw UtlException("the second tree parameter passed to the procedure 'equalTrees' doesn't exist");
2199 }
2200 return pFirstTree->equal(*pSecondTree);
2201 //##protect##"equalTrees"
2202 }
2203
equalTrees(CppParsingTree_var pFirstTree,CppParsingTree_var pSecondTree)2204 bool CGRuntime::equalTrees(CppParsingTree_var pFirstTree, CppParsingTree_var pSecondTree) {
2205 bool result = equalTrees(pFirstTree._pInternalNode, pSecondTree._pInternalNode);
2206 return result;
2207 }
2208
executeStringQuiet(DtaScriptVariable * pThis,const std::string & sCommand)2209 std::string CGRuntime::executeStringQuiet(DtaScriptVariable* pThis, const std::string& sCommand) {
2210 //##protect##"executeStringQuiet"
2211 CGQuietOutput quiet;
2212 ScpStream theCommand(sCommand);
2213 DtaScript script/*(pThis)*/;
2214 script.parseStream(theCommand);
2215 script.execute(*pThis);
2216 return quiet.getOutput();
2217 //##protect##"executeStringQuiet"
2218 }
2219
executeStringQuiet(CppParsingTree_var pThis,const std::string & sCommand)2220 std::string CGRuntime::executeStringQuiet(CppParsingTree_var pThis, const std::string& sCommand) {
2221 std::string result = executeStringQuiet(pThis._pInternalNode, sCommand);
2222 return result;
2223 }
2224
existDirectory(const std::string & sPath)2225 bool CGRuntime::existDirectory(const std::string& sPath) {
2226 //##protect##"existDirectory"
2227 if (access(sPath.c_str(), 0) == 0) {
2228 struct stat status;
2229 stat(sPath.c_str(), &status);
2230 return (status.st_mode & S_IFDIR) != 0;
2231 }
2232 return false;
2233 //##protect##"existDirectory"
2234 }
2235
existEnv(const std::string & sVariable)2236 bool CGRuntime::existEnv(const std::string& sVariable) {
2237 //##protect##"existEnv"
2238 const char* tcVariable = ::getenv(sVariable.c_str());
2239 return (tcVariable != NULL);
2240 //##protect##"existEnv"
2241 }
2242
existFile(const std::string & sFileName)2243 bool CGRuntime::existFile(const std::string& sFileName) {
2244 //##protect##"existFile"
2245 std::string sCompleteFileName;
2246 std::ifstream* pStream = openInputFileFromIncludePath(sFileName.c_str(), sCompleteFileName);
2247 if (pStream != NULL) {
2248 pStream->close();
2249 delete pStream;
2250 return true;
2251 }
2252 return false;
2253 //##protect##"existFile"
2254 }
2255
existVirtualFile(const std::string & sHandle)2256 bool CGRuntime::existVirtualFile(const std::string& sHandle) {
2257 //##protect##"existVirtualFile"
2258 return ScpStream::existVirtualFile(sHandle);
2259 //##protect##"existVirtualFile"
2260 }
2261
existVariable(DtaScriptVariable * pVariable)2262 bool CGRuntime::existVariable(DtaScriptVariable* pVariable) {
2263 //##protect##"existVariable"
2264 return (pVariable != NULL);
2265 //##protect##"existVariable"
2266 }
2267
existVariable(CppParsingTree_var pVariable)2268 bool CGRuntime::existVariable(CppParsingTree_var pVariable) {
2269 bool result = existVariable(pVariable._pInternalNode);
2270 return result;
2271 }
2272
exp(double dX)2273 double CGRuntime::exp(double dX) {
2274 //##protect##"exp"
2275 return ::exp(dX);
2276 //##protect##"exp"
2277 }
2278
exploreDirectory(DtaScriptVariable * pDirectory,const std::string & sPath,bool bSubfolders)2279 bool CGRuntime::exploreDirectory(DtaScriptVariable* pDirectory, const std::string& sPath, bool bSubfolders) {
2280 //##protect##"exploreDirectory"
2281 UtlDirectory theDirectory(sPath);
2282 bool bSuccess;
2283 if (bSubfolders) bSuccess = theDirectory.scanRecursively();
2284 else bSuccess = theDirectory.scan();
2285 if (bSuccess) {
2286 pDirectory->clearContent();
2287 populateDirectory(pDirectory, theDirectory, bSubfolders);
2288 }
2289 return bSuccess;
2290 //##protect##"exploreDirectory"
2291 }
2292
exploreDirectory(CppParsingTree_var pDirectory,const std::string & sPath,bool bSubfolders)2293 bool CGRuntime::exploreDirectory(CppParsingTree_var pDirectory, const std::string& sPath, bool bSubfolders) {
2294 bool result = exploreDirectory(pDirectory._pInternalNode, sPath, bSubfolders);
2295 return result;
2296 }
2297
extractGenerationHeader(const std::string & sFilename,std::string & sGenerator,std::string & sVersion,std::string & sDate)2298 std::string CGRuntime::extractGenerationHeader(const std::string& sFilename, std::string& sGenerator, std::string& sVersion, std::string& sDate) {
2299 //##protect##"extractGenerationHeader"
2300 std::string sComment;
2301 std::string sCompleteFileName;
2302 ScpStream* pStream = ScpStream::openInputFileFromIncludePath(sFilename.c_str(), sCompleteFileName);
2303 if (pStream != NULL) {
2304 extractGenerationHeader(*pStream, sGenerator, sVersion, sDate, sComment);
2305 delete pStream;
2306 }
2307 return sComment;
2308 //##protect##"extractGenerationHeader"
2309 }
2310
extractGenerationHeader(const std::string & sFilename,CppParsingTree_var pGenerator,CppParsingTree_var pVersion,CppParsingTree_var pDate)2311 std::string CGRuntime::extractGenerationHeader(const std::string& sFilename, CppParsingTree_var pGenerator, CppParsingTree_var pVersion, CppParsingTree_var pDate) {
2312 std::string sGenerator = pGenerator.getValue();
2313 std::string sVersion = pVersion.getValue();
2314 std::string sDate = pDate.getValue();
2315 std::string result = extractGenerationHeader(sFilename, sGenerator, sVersion, sDate);
2316 pGenerator.setValue(sGenerator);
2317 pVersion.setValue(sVersion);
2318 pDate.setValue(sDate);
2319 return result;
2320 }
2321
fileCreation(const std::string & sFilename)2322 std::string CGRuntime::fileCreation(const std::string& sFilename) {
2323 //##protect##"fileCreation"
2324 struct stat theStat;
2325 int iFileHandle = open(sFilename.c_str(), _O_RDONLY);
2326 if (iFileHandle == -1) {
2327 switch(errno) {
2328 case EACCES:
2329 return "-2";
2330 case EMFILE:
2331 return "-3";
2332 case ENOENT:
2333 return "-4";
2334 default: return "-1";
2335 }
2336 }
2337 fstat(iFileHandle, &theStat);
2338 close(iFileHandle);
2339 const char* tcTime = ctime(&theStat.st_ctime);
2340 std::string sTemp(tcTime);
2341 std::string sTime = sTemp.substr(8, 2) + sTemp.substr(4, 3) + sTemp.substr(20, 4) + " " + sTemp.substr(11, 8);
2342 if (sTime[2] <= 'Z') sTime[2] += ' ';
2343 return sTime;
2344 //##protect##"fileCreation"
2345 }
2346
fileLastAccess(const std::string & sFilename)2347 std::string CGRuntime::fileLastAccess(const std::string& sFilename) {
2348 //##protect##"fileLastAccess"
2349 struct stat theStat;
2350 int iFileHandle = open(sFilename.c_str(), _O_RDONLY);
2351 if (iFileHandle == -1) {
2352 switch(errno) {
2353 case EACCES:
2354 return "-2";
2355 case EMFILE:
2356 return "-3";
2357 case ENOENT:
2358 return "-4";
2359 default: return "-1";
2360 }
2361 }
2362 fstat(iFileHandle, &theStat);
2363 close(iFileHandle);
2364 const char* tcTime = ctime(&theStat.st_atime);
2365 std::string sTemp(tcTime);
2366 std::string sTime = sTemp.substr(8, 2) + sTemp.substr(4, 3) + sTemp.substr(20, 4) + " " + sTemp.substr(11, 8);
2367 if (sTime[2] <= 'Z') sTime[2] += ' ';
2368 return sTime;
2369 //##protect##"fileLastAccess"
2370 }
2371
fileLastModification(const std::string & sFilename)2372 std::string CGRuntime::fileLastModification(const std::string& sFilename) {
2373 //##protect##"fileLastModification"
2374 struct stat theStat;
2375 int iFileHandle = open(sFilename.c_str(), _O_RDONLY);
2376 if (iFileHandle == -1) {
2377 switch(errno) {
2378 case EACCES:
2379 return "-2";
2380 case EMFILE:
2381 return "-3";
2382 case ENOENT:
2383 return "-4";
2384 default: return "-1";
2385 }
2386 }
2387 fstat(iFileHandle, &theStat);
2388 close(iFileHandle);
2389 const char* tcTime = ctime(&theStat.st_mtime);
2390 std::string sTemp(tcTime);
2391 std::string sTime = sTemp.substr(8, 2) + sTemp.substr(4, 3) + sTemp.substr(20, 4) + " " + sTemp.substr(11, 8);
2392 if (sTime[2] <= 'Z') sTime[2] += ' ';
2393 return sTime;
2394 //##protect##"fileLastModification"
2395 }
2396
fileLines(const std::string & sFilename)2397 int CGRuntime::fileLines(const std::string& sFilename) {
2398 //##protect##"fileLines"
2399 std::string sCompleteFileName;
2400 std::auto_ptr<ScpStream> pStream(ScpStream::openInputFileFromIncludePath(sFilename.c_str(), sCompleteFileName));
2401 if (pStream.get() != NULL) {
2402 pStream->setInputLocation(pStream->size());
2403 return pStream->getLineCount();
2404 }
2405 return -1;
2406 //##protect##"fileLines"
2407 }
2408
fileMode(const std::string & sFilename)2409 std::string CGRuntime::fileMode(const std::string& sFilename) {
2410 //##protect##"fileMode"
2411 struct stat theStat;
2412 int iFileHandle = open(sFilename.c_str(), _O_RDONLY);
2413 if (iFileHandle == -1) {
2414 switch(errno) {
2415 case EACCES:
2416 return "-2";
2417 case EMFILE:
2418 return "-3";
2419 case ENOENT:
2420 return "-4";
2421 default: return "-1";
2422 }
2423 }
2424 fstat(iFileHandle, &theStat);
2425 close(iFileHandle);
2426 std::string sMode;
2427 #ifdef WIN32
2428 if (theStat.st_mode & _S_IREAD) sMode = "R";
2429 if (theStat.st_mode & _S_IWRITE) sMode += "W";
2430 if (theStat.st_mode & _S_IEXEC) sMode += "X";
2431 #else
2432 if (theStat.st_mode & S_IRUSR) sMode = "R";
2433 if (theStat.st_mode & S_IWUSR) sMode += "W";
2434 if (theStat.st_mode & S_IXUSR) sMode += "X";
2435 #endif
2436 return sMode;
2437 //##protect##"fileMode"
2438 }
2439
fileSize(const std::string & sFilename)2440 int CGRuntime::fileSize(const std::string& sFilename) {
2441 //##protect##"fileSize"
2442 struct stat theStat;
2443 int iFileHandle = open(sFilename.c_str(), _O_RDONLY);
2444 if (iFileHandle == -1) {
2445 switch(errno) {
2446 case EACCES:
2447 return -2;
2448 case EMFILE:
2449 return -3;
2450 case ENOENT:
2451 return -4;
2452 default: return -1;
2453 }
2454 }
2455 fstat(iFileHandle, &theStat);
2456 close(iFileHandle);
2457 return theStat.st_size;
2458 //##protect##"fileSize"
2459 }
2460
findElement(const std::string & sValue,DtaScriptVariable * pVariable)2461 bool CGRuntime::findElement(const std::string& sValue, DtaScriptVariable* pVariable) {
2462 //##protect##"findElement"
2463 return ((pVariable != NULL) && (pVariable->getArrayElement(sValue) != NULL));
2464 //##protect##"findElement"
2465 }
2466
findElement(const std::string & sValue,CppParsingTree_var pVariable)2467 bool CGRuntime::findElement(const std::string& sValue, CppParsingTree_var pVariable) {
2468 bool result = findElement(sValue, pVariable._pInternalNode);
2469 return result;
2470 }
2471
findFirstChar(const std::string & sText,const std::string & sSomeChars)2472 int CGRuntime::findFirstChar(const std::string& sText, const std::string& sSomeChars) {
2473 //##protect##"findFirstChar"
2474 std::string::size_type iFirstPos = std::string::npos;
2475 for (std::string::size_type i = 0; i < sSomeChars.size(); i++) {
2476 std::string::size_type iPos = sText.find(sSomeChars[i]);
2477 if ((iPos != std::string::npos) && ((iFirstPos == std::string::npos) || (iFirstPos > iPos))) iFirstPos = iPos;
2478 }
2479 if (iFirstPos == std::string::npos) return -1;
2480 return iFirstPos;
2481 //##protect##"findFirstChar"
2482 }
2483
findFirstSubstringIntoKeys(const std::string & sSubstring,DtaScriptVariable * pArray)2484 int CGRuntime::findFirstSubstringIntoKeys(const std::string& sSubstring, DtaScriptVariable* pArray) {
2485 //##protect##"findFirstSubstringIntoKeys"
2486 if (pArray != NULL) {
2487 const std::list<DtaScriptVariable*>* listOfElements = pArray->getArray();
2488 if (listOfElements != NULL) {
2489 int iIndex = 0;
2490 for (std::list<DtaScriptVariable*>::const_iterator i = listOfElements->begin(); i != listOfElements->end(); i++) {
2491 if (strstr((*i)->getName(), sSubstring.c_str()) != NULL) return iIndex;
2492 iIndex++;
2493 }
2494 }
2495 }
2496 return -1;
2497 //##protect##"findFirstSubstringIntoKeys"
2498 }
2499
findFirstSubstringIntoKeys(const std::string & sSubstring,CppParsingTree_var pArray)2500 int CGRuntime::findFirstSubstringIntoKeys(const std::string& sSubstring, CppParsingTree_var pArray) {
2501 int result = findFirstSubstringIntoKeys(sSubstring, pArray._pInternalNode);
2502 return result;
2503 }
2504
findLastString(const std::string & sText,const std::string & sFind)2505 int CGRuntime::findLastString(const std::string& sText, const std::string& sFind) {
2506 //##protect##"findLastString"
2507 std::string::size_type iPos = sText.rfind(sFind);
2508 if ((iPos == std::string::npos) || (iPos >= sText.size())) return -1;
2509 return iPos;
2510 //##protect##"findLastString"
2511 }
2512
findNextString(const std::string & sText,const std::string & sFind,int iPosition)2513 int CGRuntime::findNextString(const std::string& sText, const std::string& sFind, int iPosition) {
2514 //##protect##"findNextString"
2515 std::string::size_type iPos = sText.find(sFind, iPosition);
2516 if ((iPos == std::string::npos) || (iPos >= sText.size())) return -1;
2517 return iPos;
2518 //##protect##"findNextString"
2519 }
2520
findNextSubstringIntoKeys(const std::string & sSubstring,DtaScriptVariable * pArray,int iNext)2521 int CGRuntime::findNextSubstringIntoKeys(const std::string& sSubstring, DtaScriptVariable* pArray, int iNext) {
2522 //##protect##"findNextSubstringIntoKeys"
2523 if (pArray != NULL) {
2524 const std::list<DtaScriptVariable*>* listOfElements = pArray->getArray();
2525 if ((listOfElements != NULL) && (iNext < (int) listOfElements->size())) {
2526 int iIndex = 0;
2527 std::list<DtaScriptVariable*>::const_iterator i = listOfElements->begin();
2528 while (iNext >= 0) {
2529 i++;
2530 iIndex++;
2531 iNext--;
2532 }
2533 for (; i != listOfElements->end(); i++) {
2534 if (strstr((*i)->getName(), sSubstring.c_str()) != NULL) return iIndex;
2535 iIndex++;
2536 }
2537 }
2538 }
2539 return -1;
2540 //##protect##"findNextSubstringIntoKeys"
2541 }
2542
findNextSubstringIntoKeys(const std::string & sSubstring,CppParsingTree_var pArray,int iNext)2543 int CGRuntime::findNextSubstringIntoKeys(const std::string& sSubstring, CppParsingTree_var pArray, int iNext) {
2544 int result = findNextSubstringIntoKeys(sSubstring, pArray._pInternalNode, iNext);
2545 return result;
2546 }
2547
findString(const std::string & sText,const std::string & sFind)2548 int CGRuntime::findString(const std::string& sText, const std::string& sFind) {
2549 //##protect##"findString"
2550 std::string::size_type iPos = sText.find(sFind);
2551 if (iPos == std::string::npos) return -1;
2552 return iPos;
2553 //##protect##"findString"
2554 }
2555
floor(double dNumber)2556 int CGRuntime::floor(double dNumber) {
2557 //##protect##"floor"
2558 return (int) ::floor(dNumber);
2559 //##protect##"floor"
2560 }
2561
formatDate(const std::string & sDate,const std::string & sFormat)2562 std::string CGRuntime::formatDate(const std::string& sDate, const std::string& sFormat) {
2563 //##protect##"formatDate"
2564 UtlDate theDate = UtlDate::getDateFromFormat(sDate, "%d%b%Y%| %H:%M:%S%|.%L");
2565 return theDate.getFormattedDate(sFormat);
2566 //##protect##"formatDate"
2567 }
2568
getArraySize(DtaScriptVariable * pVariable)2569 int CGRuntime::getArraySize(DtaScriptVariable* pVariable) {
2570 //##protect##"getArraySize"
2571 if (pVariable == NULL) return 0;
2572 return pVariable->getArraySize();
2573 //##protect##"getArraySize"
2574 }
2575
getArraySize(CppParsingTree_var pVariable)2576 int CGRuntime::getArraySize(CppParsingTree_var pVariable) {
2577 int result = getArraySize(pVariable._pInternalNode);
2578 return result;
2579 }
2580
getCommentBegin()2581 std::string CGRuntime::getCommentBegin() {
2582 //##protect##"getCommentBegin"
2583 return DtaProject::getInstance().getCommentBegin();
2584 //##protect##"getCommentBegin"
2585 }
2586
getCommentEnd()2587 std::string CGRuntime::getCommentEnd() {
2588 //##protect##"getCommentEnd"
2589 return DtaProject::getInstance().getCommentEnd();
2590 //##protect##"getCommentEnd"
2591 }
2592
getCurrentDirectory()2593 std::string CGRuntime::getCurrentDirectory() {
2594 //##protect##"getCurrentDirectory"
2595 char tcPWD[MAX_PATH];
2596 if (getcwd(tcPWD, MAX_PATH - 1) == NULL) return "";
2597 toSlashes_(tcPWD);
2598 std::string sPWD = tcPWD;
2599 if (tcPWD[sPWD.size() - 1] != '/') sPWD += "/";
2600 return sPWD;
2601 //##protect##"getCurrentDirectory"
2602 }
2603
getEnv(const std::string & sVariable)2604 std::string CGRuntime::getEnv(const std::string& sVariable) {
2605 //##protect##"getEnv"
2606 const char* tcVariable = ::getenv(sVariable.c_str());
2607 if (tcVariable == NULL) throw UtlException("variable '" + sVariable + "' not found in the environment table");
2608 return tcVariable;
2609 //##protect##"getEnv"
2610 }
2611
getGenerationHeader()2612 std::string CGRuntime::getGenerationHeader() {
2613 //##protect##"getGenerationHeader"
2614 return DtaProject::getInstance().getGenerationHeader();
2615 //##protect##"getGenerationHeader"
2616 }
2617
getHTTPRequest(const std::string & sURL,DtaScriptVariable * pHTTPSession,DtaScriptVariable * pArguments)2618 std::string CGRuntime::getHTTPRequest(const std::string& sURL, DtaScriptVariable* pHTTPSession, DtaScriptVariable* pArguments) {
2619 //##protect##"getHTTPRequest"
2620 HTTPRequest request;
2621 return request.get(sURL, pHTTPSession, pArguments);
2622 //##protect##"getHTTPRequest"
2623 }
2624
getHTTPRequest(const std::string & sURL,CppParsingTree_var pHTTPSession,CppParsingTree_var pArguments)2625 std::string CGRuntime::getHTTPRequest(const std::string& sURL, CppParsingTree_var pHTTPSession, CppParsingTree_var pArguments) {
2626 std::string result = getHTTPRequest(sURL, pHTTPSession._pInternalNode, pArguments._pInternalNode);
2627 return result;
2628 }
2629
getIncludePath()2630 std::string CGRuntime::getIncludePath() {
2631 //##protect##"getIncludePath"
2632 std::string sPath;
2633 const std::list<std::string>& includePath = ScpStream::getListOfIncludePaths();
2634 for (std::list<std::string>::const_iterator i = includePath.begin(); i != includePath.end(); i++) {
2635 if (!sPath.empty()) sPath += ";";
2636 sPath += *i;
2637 }
2638 return sPath;
2639 //##protect##"getIncludePath"
2640 }
2641
getLastDelay()2642 double CGRuntime::getLastDelay() {
2643 //##protect##"getLastDelay"
2644 return DtaProject::getInstance().getLastDelay();
2645 //##protect##"getLastDelay"
2646 }
2647
getNow()2648 std::string CGRuntime::getNow() {
2649 //##protect##"getNow"
2650 if (_sFrozenTime.empty()) {
2651 UtlDate today;
2652 return today.getString();
2653 }
2654 return _sFrozenTime;
2655 //##protect##"getNow"
2656 }
2657
getProperty(const std::string & sDefine)2658 std::string CGRuntime::getProperty(const std::string& sDefine) {
2659 //##protect##"getProperty"
2660 return DtaProject::getInstance().getDefineTarget(sDefine);
2661 //##protect##"getProperty"
2662 }
2663
getShortFilename(const std::string & sPathFilename)2664 std::string CGRuntime::getShortFilename(const std::string& sPathFilename) {
2665 //##protect##"getShortFilename"
2666 std::string::size_type iIndex = sPathFilename.find_last_of("/\\");
2667 if (iIndex == std::string::npos) return sPathFilename;
2668 else if (iIndex == sPathFilename.size()) return "";
2669 return sPathFilename.substr(iIndex + 1);
2670 //##protect##"getShortFilename"
2671 }
2672
getTextMode()2673 std::string CGRuntime::getTextMode() {
2674 //##protect##"getTextMode"
2675 switch(DtaProject::getInstance().getTextMode()) {
2676 case DtaProject::DOS_MODE: return "DOS";
2677 case DtaProject::UNIX_MODE: return "UNIX";
2678 case DtaProject::BINARY_MODE: return "BINARY";
2679 }
2680 throw UtlException("internal error into CGRuntime::getTextMode(): unhandled text mode enum");
2681 //##protect##"getTextMode"
2682 }
2683
getVariableAttributes(DtaScriptVariable * pVariable,DtaScriptVariable * pList)2684 int CGRuntime::getVariableAttributes(DtaScriptVariable* pVariable, DtaScriptVariable* pList) {
2685 //##protect##"getVariableAttributes"
2686 if (pVariable == NULL) return -1;
2687 int iSize = 0;
2688 DtaScriptVariableList* pAttributes = pVariable->getAttributes();
2689 while (pAttributes != NULL) {
2690 DtaScriptVariable* pNode = pAttributes->getNode();
2691 DtaScriptVariable* pItem = pList->addElement(pNode->getName());
2692 if (pNode->getReferencedVariable() != NULL) {
2693 std::string sValue = pNode->getReferencedVariable()->getCompleteName();
2694 pItem->setValue(sValue.c_str());
2695 }
2696 pAttributes = pAttributes->getNext();
2697 iSize++;
2698 }
2699 return iSize;
2700 //##protect##"getVariableAttributes"
2701 }
2702
getVariableAttributes(CppParsingTree_var pVariable,CppParsingTree_var pList)2703 int CGRuntime::getVariableAttributes(CppParsingTree_var pVariable, CppParsingTree_var pList) {
2704 int result = getVariableAttributes(pVariable._pInternalNode, pList._pInternalNode);
2705 return result;
2706 }
2707
getVersion()2708 std::string CGRuntime::getVersion() {
2709 //##protect##"getVersion"
2710 std::string sVersion = DtaProject::getInstance().getVersion();
2711 if (sVersion.empty()) sVersion = EXECUTABLE_VERSION;
2712 return sVersion;
2713 //##protect##"getVersion"
2714 }
2715
getWorkingPath()2716 std::string CGRuntime::getWorkingPath() {
2717 //##protect##"getWorkingPath"
2718 return DtaProject::getInstance().getWorkingPath();
2719 //##protect##"getWorkingPath"
2720 }
2721
getWriteMode()2722 std::string CGRuntime::getWriteMode() {
2723 //##protect##"getWriteMode"
2724 if (_pOutputStream == NULL) return "";
2725 return ((_pOutputStream->insertMode()) ? "insert" : "overwrite");
2726 //##protect##"getWriteMode"
2727 }
2728
hexaToDecimal(const std::string & sHexaNumber)2729 int CGRuntime::hexaToDecimal(const std::string& sHexaNumber) {
2730 //##protect##"hexaToDecimal"
2731 int iResult = 0;
2732 for (std::string::size_type i = 0; i < sHexaNumber.size(); i++) {
2733 char a = sHexaNumber[i];
2734 iResult *= 16;
2735 if (a <= '9') {
2736 if (a < '0') throw UtlException("hexaToDecimal(\"" + composeCLikeString(sHexaNumber) + "\"): invalid hexadecimal digit '" + composeCLikeString(std::string(1, a)) + "' encountered");
2737 iResult += a - '0';
2738 } else if (a <= 'F') {
2739 if (a < 'A') throw UtlException("hexaToDecimal(\"" + composeCLikeString(sHexaNumber) + "\"): invalid hexadecimal digit '" + std::string(1, a) + "' encountered");
2740 iResult += 10 + (a - 'A');
2741 } else if ((a >= 'a') && (a <= 'f')) {
2742 iResult += 10 + (a - 'a');
2743 } else {
2744 throw UtlException("hexaToDecimal(\"" + composeCLikeString(sHexaNumber) + "\"): invalid hexadecimal digit '" + std::string(1, a) + "' encountered");;
2745 }
2746 }
2747 return iResult;
2748 //##protect##"hexaToDecimal"
2749 }
2750
hostToNetworkLong(const std::string & sBytes)2751 std::string CGRuntime::hostToNetworkLong(const std::string& sBytes) {
2752 //##protect##"hostToNetworkLong"
2753 if (sBytes.size() != 8) throw UtlException("'" + composeCLikeString(sBytes) + "' isn't recognized as a 4-bytes sequence");
2754 char tcLong[4];
2755 if (!convertBytesToChars(sBytes, (unsigned char*) tcLong, 4)) throw UtlException("invalid hexadecimal representation in '" + composeCLikeString(sBytes) + "'");
2756 unsigned long iLong = NetSocket::nToHl(*((unsigned long*) &tcLong));
2757 char tcBytes[9];
2758 convertCharsToBytes((const unsigned char*) &iLong, tcBytes, 4);
2759 return tcBytes;
2760 //##protect##"hostToNetworkLong"
2761 }
2762
hostToNetworkShort(const std::string & sBytes)2763 std::string CGRuntime::hostToNetworkShort(const std::string& sBytes) {
2764 //##protect##"hostToNetworkShort"
2765 if (sBytes.size() != 4) throw UtlException("'" + composeCLikeString(sBytes) + "' isn't recognized as a 2-bytes sequence");
2766 char tcShort[2];
2767 if (!convertBytesToChars(sBytes, (unsigned char*) tcShort, 2)) throw UtlException("invalid hexadecimal representation in '" + composeCLikeString(sBytes) + "'");
2768 unsigned short iShort = NetSocket::nToHs(*((unsigned short*) &tcShort));
2769 char tcBytes[5];
2770 convertCharsToBytes((const unsigned char*) &iShort, tcBytes, 2);
2771 return tcBytes;
2772 //##protect##"hostToNetworkShort"
2773 }
2774
increment(double & dNumber)2775 double CGRuntime::increment(double& dNumber) {
2776 //##protect##"increment"
2777 dNumber = dNumber + 1.0;
2778 return dNumber;
2779 //##protect##"increment"
2780 }
2781
increment(CppParsingTree_var pNumber)2782 double CGRuntime::increment(CppParsingTree_var pNumber) {
2783 double dNumber = pNumber.getDoubleValue();
2784 double result = increment(dNumber);
2785 pNumber.setValue(dNumber);
2786 return result;
2787 }
2788
indentFile(const std::string & sFile,const std::string & sMode)2789 bool CGRuntime::indentFile(const std::string& sFile, const std::string& sMode) {
2790 //##protect##"indentFile"
2791 std::auto_ptr<ScpStream> pFile(new ScpStream(sFile, ScpStream::IN | ScpStream::PATH));
2792 std::string::size_type iIndex = sFile.find_last_of('.');
2793 if ((iIndex == std::string::npos) || (iIndex == sFile.size())) throw UtlException("function 'indentFile(\"" + sFile + "\")' expects a file extension to determine its type for indentation");
2794 std::string sExtension = sFile.substr(iIndex + 1);
2795 bool bSuccess;
2796 if ((stricmp(sMode.c_str(), "c++") == 0) || (stricmp(sExtension.c_str(), "cpp") == 0) || (stricmp(sExtension.c_str(), "cxx") == 0) || (stricmp(sExtension.c_str(), "hxx") == 0) || (stricmp(sExtension.c_str(), "h") == 0)) bSuccess = pFile->indentAsCpp();
2797 else if ((stricmp(sMode.c_str(), "java") == 0) || stricmp(sExtension.c_str(), "java") == 0) bSuccess = pFile->indentAsCpp();
2798 else throw UtlException("function 'indentFile(\"" + sFile + "\")' works on C++ and JAVA only at the present time, so '" + sExtension + "' extension is refused");
2799 if (bSuccess) pFile->saveIntoFile(pFile->getFilename(), false);
2800 return bSuccess;
2801 //##protect##"indentFile"
2802 }
2803
inf(double dLeft,double dRight)2804 bool CGRuntime::inf(double dLeft, double dRight) {
2805 //##protect##"inf"
2806 return (dLeft < dRight);
2807 //##protect##"inf"
2808 }
2809
inputKey(bool bEcho)2810 std::string CGRuntime::inputKey(bool bEcho) {
2811 //##protect##"inputKey"
2812 if (getExternalHandling() != NULL) return getExternalHandling()->inputKey(bEcho);
2813 char tcText[] = {0, 0};
2814 int iKbHit = kbhit();
2815 if (iKbHit != 0) {
2816 #ifdef WIN32
2817 tcText[0] = (char) getch();
2818 #else
2819 tcText[0] = (char) readch();
2820 #endif
2821 }
2822 return tcText;
2823 //##protect##"inputKey"
2824 }
2825
inputLine(bool bEcho,const std::string & sPrompt)2826 std::string CGRuntime::inputLine(bool bEcho, const std::string& sPrompt) {
2827 //##protect##"inputLine"
2828 if (getExternalHandling() != NULL) return getExternalHandling()->inputLine(bEcho);
2829 #ifdef CODEWORKER_GNU_READLINE
2830 char *tcText = (char*)NULL;
2831 tcText = readline(sPrompt.c_str());
2832
2833 // Save history
2834 if (tcText && *tcText)
2835 add_history(tcText);
2836 #else
2837 char tcText[16384];
2838 # ifndef WIN32
2839 closeKeyboard();
2840 # endif
2841 if (!sPrompt.empty()) CGRuntime::traceText(sPrompt.c_str());
2842 std::cin.getline(tcText, 16383);
2843 # ifndef WIN32
2844 initKeyboard();
2845 # endif
2846 #endif
2847 return tcText;
2848 //##protect##"inputLine"
2849 }
2850
isEmpty(DtaScriptVariable * pArray)2851 bool CGRuntime::isEmpty(DtaScriptVariable* pArray) {
2852 //##protect##"isEmpty"
2853 return ((pArray == NULL) || (pArray->getArraySize() == 0));
2854 //##protect##"isEmpty"
2855 }
2856
isEmpty(CppParsingTree_var pArray)2857 bool CGRuntime::isEmpty(CppParsingTree_var pArray) {
2858 bool result = isEmpty(pArray._pInternalNode);
2859 return result;
2860 }
2861
isIdentifier(const std::string & sIdentifier)2862 bool CGRuntime::isIdentifier(const std::string& sIdentifier) {
2863 //##protect##"isIdentifier"
2864 char a = sIdentifier[0];
2865 if (((a >= 'a') && (a <= 'z')) || ((a >= 'A') && (a <= 'Z')) || (a == '_')) {
2866 std::string::size_type iIndex = 1;
2867 a = sIdentifier[1];
2868 while ((iIndex < sIdentifier.size()) && (((a >= 'a') && (a <= 'z')) || ((a >= 'A') && (a <= 'Z')) || ((a >= '0') && (a <= '9')) || (a == '_'))) {
2869 iIndex++;
2870 a = sIdentifier[iIndex];
2871 }
2872 return (iIndex == sIdentifier.size());
2873 }
2874 return false;
2875 //##protect##"isIdentifier"
2876 }
2877
isNegative(double dNumber)2878 bool CGRuntime::isNegative(double dNumber) {
2879 //##protect##"isNegative"
2880 return (dNumber < 0.0);
2881 //##protect##"isNegative"
2882 }
2883
isNumeric(const std::string & sNumber)2884 bool CGRuntime::isNumeric(const std::string& sNumber) {
2885 //##protect##"isNumeric"
2886 int iIndex = 0;
2887 char a = sNumber[iIndex];
2888 if (a == '-') {
2889 iIndex++;
2890 a = sNumber[iIndex];
2891 }
2892 bool bLeft = false;
2893 while (a >= '0' && a <= '9') {
2894 bLeft = true;
2895 iIndex++;
2896 a = sNumber[iIndex];
2897 }
2898 if (a == '.') {
2899 iIndex++;
2900 a = sNumber[iIndex];
2901 bool bRight = false;
2902 while (a >= '0' && a <= '9') {
2903 bRight = true;
2904 iIndex++;
2905 a = sNumber[iIndex];
2906 }
2907 if (!bLeft && !bRight) return false;
2908 } else if (!bLeft) {
2909 return false;
2910 }
2911 if (a == 'e' || a == 'E') {
2912 iIndex++;
2913 a = sNumber[iIndex];
2914 if (a == '+' || a == '-') {
2915 iIndex++;
2916 a = sNumber[iIndex];
2917 }
2918 bool bExponent = false;
2919 while (a >= '0' && a <= '9') {
2920 bExponent = true;
2921 iIndex++;
2922 a = sNumber[iIndex];
2923 }
2924 if (!bExponent) return false;
2925 }
2926 return (a == '\0');
2927 //##protect##"isNumeric"
2928 }
2929
isPositive(double dNumber)2930 bool CGRuntime::isPositive(double dNumber) {
2931 //##protect##"isPositive"
2932 return (dNumber > 0.0);
2933 //##protect##"isPositive"
2934 }
2935
joinStrings(DtaScriptVariable * pList,const std::string & sSeparator)2936 std::string CGRuntime::joinStrings(DtaScriptVariable* pList, const std::string& sSeparator) {
2937 //##protect##"joinStrings"
2938 std::string sResult;
2939 const std::list<DtaScriptVariable*>* slList = pList->getArray();
2940 if (slList != NULL) {
2941 for (std::list<DtaScriptVariable*>::const_iterator i = slList->begin(); i != slList->end(); ++i) {
2942 if (i != slList->begin()) {
2943 sResult += sSeparator;
2944 }
2945 const char* tcValue = (*i)->getValue();
2946 if (tcValue != NULL) sResult += tcValue;
2947 }
2948 }
2949 return sResult;
2950 //##protect##"joinStrings"
2951 }
2952
joinStrings(CppParsingTree_var pList,const std::string & sSeparator)2953 std::string CGRuntime::joinStrings(CppParsingTree_var pList, const std::string& sSeparator) {
2954 std::string result = joinStrings(pList._pInternalNode, sSeparator);
2955 return result;
2956 }
2957
leftString(const std::string & sText,int iLength)2958 std::string CGRuntime::leftString(const std::string& sText, int iLength) {
2959 //##protect##"leftString"
2960 if (iLength < 0) return "";
2961 if (iLength > (int) sText.size()) iLength = sText.size();
2962 return sText.substr(0, iLength);
2963 //##protect##"leftString"
2964 }
2965
lengthString(const std::string & sText)2966 int CGRuntime::lengthString(const std::string& sText) {
2967 //##protect##"lengthString"
2968 return sText.size();
2969 //##protect##"lengthString"
2970 }
2971
loadBinaryFile(const std::string & sFile,int iLength)2972 std::string CGRuntime::loadBinaryFile(const std::string& sFile, int iLength) {
2973 //##protect##"loadBinaryFile"
2974 std::auto_ptr<ScpStream> pFile;
2975 if (iLength < 0) {
2976 pFile = std::auto_ptr<ScpStream>(new ScpStream(sFile, ScpStream::IN | ScpStream::PATH));
2977 iLength = pFile->size();
2978 } else {
2979 pFile = std::auto_ptr<ScpStream>(new ScpStream(sFile, ScpStream::IN | ScpStream::PATH, iLength, iLength));
2980 }
2981 const char* tcBinary = pFile->readBuffer();
2982 char* tcContent = new char[1 + (iLength << 1)];
2983 convertCharsToBytes((const unsigned char*) tcBinary, tcContent, iLength);
2984 pFile->close();
2985 std::string sContent = tcContent;
2986 delete [] tcContent;
2987 return sContent;
2988 //##protect##"loadBinaryFile"
2989 }
2990
loadFile(const std::string & sFile,int iLength)2991 std::string CGRuntime::loadFile(const std::string& sFile, int iLength) {
2992 //##protect##"loadFile"
2993 std::auto_ptr<ScpStream> pFile;
2994 if (iLength < 0) {
2995 pFile = std::auto_ptr<ScpStream>(new ScpStream(sFile, ScpStream::IN | ScpStream::PATH));
2996 } else {
2997 pFile = std::auto_ptr<ScpStream>(new ScpStream(sFile, ScpStream::IN | ScpStream::PATH, iLength, iLength));
2998 }
2999 std::string sContent = pFile->readBuffer();
3000 pFile->close();
3001 return sContent;
3002 //##protect##"loadFile"
3003 }
3004
loadVirtualFile(const std::string & sHandle)3005 std::string CGRuntime::loadVirtualFile(const std::string& sHandle) {
3006 //##protect##"loadVirtualFile"
3007 std::string sContent;
3008 if (!ScpStream::loadVirtualFile(sHandle, sContent)) throw UtlException("unable to load the virtual file called '" + sHandle + "'");
3009 return sContent;
3010 //##protect##"loadVirtualFile"
3011 }
3012
log(double dX)3013 double CGRuntime::log(double dX) {
3014 //##protect##"log"
3015 if (dX < 0.0) throw UtlException("the logarithm of a negative floating-point doesn't exist");
3016 return ::log(dX);
3017 //##protect##"log"
3018 }
3019
longToBytes(unsigned long ulLong)3020 std::string CGRuntime::longToBytes(unsigned long ulLong) {
3021 //##protect##"longToBytes"
3022 char tcBytes[9];
3023 convertCharsToBytes((const unsigned char*) &ulLong, tcBytes, 4);
3024 return tcBytes;
3025 //##protect##"longToBytes"
3026 }
3027
midString(const std::string & sText,int iPos,int iLength)3028 std::string CGRuntime::midString(const std::string& sText, int iPos, int iLength) {
3029 //##protect##"midString"
3030 if ((iPos < 0) || (iPos >= (int) sText.size()) || (iLength <= 0)) return "";
3031 if (iPos + iLength > (int) sText.size()) iLength = sText.size() - iPos;
3032 return sText.substr(iPos, iLength);
3033 //##protect##"midString"
3034 }
3035
mod(int iDividend,int iDivisor)3036 int CGRuntime::mod(int iDividend, int iDivisor) {
3037 //##protect##"mod"
3038 return iDividend % iDivisor;
3039 //##protect##"mod"
3040 }
3041
mult(double dLeft,double dRight)3042 double CGRuntime::mult(double dLeft, double dRight) {
3043 //##protect##"mult"
3044 return dLeft * dRight;
3045 //##protect##"mult"
3046 }
3047
networkLongToHost(const std::string & sBytes)3048 std::string CGRuntime::networkLongToHost(const std::string& sBytes) {
3049 //##protect##"networkLongToHost"
3050 if (sBytes.size() != 8) throw UtlException("'" + composeCLikeString(sBytes) + "' isn't recognized as a 4-bytes sequence");
3051 char tcLong[4];
3052 if (!convertBytesToChars(sBytes, (unsigned char*) tcLong, 4)) throw UtlException("invalid hexadecimal representation in '" + composeCLikeString(sBytes) + "'");
3053 unsigned long iLong = NetSocket::hToNl(*((unsigned long*) &tcLong));
3054 char tcBytes[9];
3055 convertCharsToBytes((const unsigned char*) &iLong, tcBytes, 4);
3056 return tcBytes;
3057 //##protect##"networkLongToHost"
3058 }
3059
networkShortToHost(const std::string & sBytes)3060 std::string CGRuntime::networkShortToHost(const std::string& sBytes) {
3061 //##protect##"networkShortToHost"
3062 if (sBytes.size() != 4) throw UtlException("'" + composeCLikeString(sBytes) + "' isn't recognized as a 2-bytes sequence");
3063 char tcShort[2];
3064 if (!convertBytesToChars(sBytes, (unsigned char*) tcShort, 2)) throw UtlException("invalid hexadecimal representation in '" + composeCLikeString(sBytes) + "'");
3065 unsigned short iShort = NetSocket::hToNs(*((unsigned short*) &tcShort));
3066 char tcBytes[5];
3067 convertCharsToBytes((const unsigned char*) &iShort, tcBytes, 2);
3068 return tcBytes;
3069 //##protect##"networkShortToHost"
3070 }
3071
octalToDecimal(const std::string & sOctalNumber)3072 int CGRuntime::octalToDecimal(const std::string& sOctalNumber) {
3073 //##protect##"octalToDecimal"
3074 int iResult = 0;
3075 for (std::string::size_type i = 0; i < sOctalNumber.size(); i++) {
3076 char a = sOctalNumber[i];
3077 iResult *= 8;
3078 if ((a < '0') || (a > '7')) throw UtlException("octalToDecimal(\"" + composeCLikeString(sOctalNumber) + "\"): invalid hexadecimal digit '" + composeCLikeString(std::string(1, a)) + "' encountered");
3079 iResult += a - '0';
3080 }
3081 return iResult;
3082 //##protect##"octalToDecimal"
3083 }
3084
pathFromPackage(const std::string & sPackage)3085 std::string CGRuntime::pathFromPackage(const std::string& sPackage) {
3086 //##protect##"pathFromPackage"
3087 std::string sPath = sPackage;
3088 std::string::size_type iPos = sPath.find(".");
3089 while (iPos != std::string::npos) {
3090 sPath[iPos] = '/';
3091 iPos = sPath.find(".", iPos + 1);
3092 }
3093 if (sPath.empty() || ((sPath[sPath.size() - 1] != '\\') && (sPath[sPath.size() - 1] != '/'))) sPath += "/";
3094 return sPath;
3095 //##protect##"pathFromPackage"
3096 }
3097
postHTTPRequest(const std::string & sURL,DtaScriptVariable * pHTTPSession,DtaScriptVariable * pArguments)3098 std::string CGRuntime::postHTTPRequest(const std::string& sURL, DtaScriptVariable* pHTTPSession, DtaScriptVariable* pArguments) {
3099 //##protect##"postHTTPRequest"
3100 HTTPRequest request;
3101 return request.post(sURL, pHTTPSession, pArguments);
3102 //##protect##"postHTTPRequest"
3103 }
3104
postHTTPRequest(const std::string & sURL,CppParsingTree_var pHTTPSession,CppParsingTree_var pArguments)3105 std::string CGRuntime::postHTTPRequest(const std::string& sURL, CppParsingTree_var pHTTPSession, CppParsingTree_var pArguments) {
3106 std::string result = postHTTPRequest(sURL, pHTTPSession._pInternalNode, pArguments._pInternalNode);
3107 return result;
3108 }
3109
pow(double dX,double dY)3110 double CGRuntime::pow(double dX, double dY) {
3111 //##protect##"pow"
3112 return ::pow(dX, dY);
3113 //##protect##"pow"
3114 }
3115
randomInteger()3116 int CGRuntime::randomInteger() {
3117 //##protect##"randomInteger"
3118 return rand();
3119 //##protect##"randomInteger"
3120 }
3121
receiveBinaryFromSocket(int iSocket,int iLength)3122 std::string CGRuntime::receiveBinaryFromSocket(int iSocket, int iLength) {
3123 //##protect##"receiveBinaryFromSocket"
3124 char* tcBuffer = new char[iLength];
3125 int iNbChars = 0;
3126 int iOffset = 0;
3127 do {
3128 iOffset += iNbChars;
3129 iNbChars = NetSocket::receiveFromSocket(iSocket, tcBuffer + iOffset, iLength - iOffset);
3130 if (iNbChars < 0) {
3131 delete [] tcBuffer;
3132 return "";
3133 }
3134 } while (iOffset + iNbChars < iLength);
3135 char* tcContent = new char[iLength * 2 + 1];
3136 convertCharsToBytes((const unsigned char*) tcBuffer, tcContent, iLength);
3137 std::string sContent = tcContent;
3138 delete [] tcBuffer;
3139 delete [] tcContent;
3140 return sContent;
3141 //##protect##"receiveBinaryFromSocket"
3142 }
3143
receiveFromSocket(int iSocket,bool & bIsText)3144 std::string CGRuntime::receiveFromSocket(int iSocket, bool& bIsText) {
3145 //##protect##"receiveFromSocket"
3146 char tcBuffer[2048];
3147 int iLength = NetSocket::receiveFromSocket(iSocket, tcBuffer, 2047);
3148 unsigned char* u = (unsigned char*) tcBuffer;
3149 int i = iLength;
3150 while (i-- > 0) {
3151 if (*u < 2) {
3152 bIsText = false;
3153 char tcContent[4096];
3154 convertCharsToBytes((const unsigned char*) tcBuffer, tcContent, iLength);
3155 return tcContent;
3156 }
3157 u++;
3158 }
3159 bIsText = true;
3160 tcBuffer[iLength] = '\0';
3161 return tcBuffer;
3162 //##protect##"receiveFromSocket"
3163 }
3164
receiveFromSocket(int iSocket,CppParsingTree_var pIsText)3165 std::string CGRuntime::receiveFromSocket(int iSocket, CppParsingTree_var pIsText) {
3166 bool bIsText = pIsText.getBooleanValue();
3167 std::string result = receiveFromSocket(iSocket, bIsText);
3168 pIsText.setValue(bIsText);
3169 return result;
3170 }
3171
receiveTextFromSocket(int iSocket,int iLength)3172 std::string CGRuntime::receiveTextFromSocket(int iSocket, int iLength) {
3173 //##protect##"receiveTextFromSocket"
3174 char* tcBuffer = new char[iLength + 1];
3175 int iNbChars = 0;
3176 int iOffset = 0;
3177 do {
3178 iOffset += iNbChars;
3179 iNbChars = NetSocket::receiveFromSocket(iSocket, tcBuffer + iOffset, iLength - iOffset);
3180 if (iNbChars < 0) {
3181 delete [] tcBuffer;
3182 return "";
3183 }
3184 } while (iOffset + iNbChars < iLength);
3185 tcBuffer[iLength] = '\0';
3186 std::string sContent = tcBuffer;
3187 delete [] tcBuffer;
3188 return sContent;
3189 //##protect##"receiveTextFromSocket"
3190 }
3191
relativePath(const std::string & sPath,const std::string & sReference)3192 std::string CGRuntime::relativePath(const std::string& sPath, const std::string& sReference) {
3193 //##protect##"relativePath"
3194 std::string sPath1 = canonizePath(sPath);
3195 std::string sReference1 = canonizePath(sReference);
3196 #ifdef WIN32
3197 if ((sPath1.size() < 2) || (sReference1.size() < 2) ||
3198 (sPath1[1] != ':') || (sReference1[1] != ':') ||
3199 ((sPath1[0] & 0xDF) != (sReference1[0] & 0xDF))) return sPath1;
3200 #endif
3201 char a = sPath1[sPath1.size() - 1];
3202 if ((a == '/') || (a == '\\')) sPath1 = sPath1.substr(0, sPath1.size() - 1);
3203 a = sReference1[sReference1.size() - 1];
3204 if ((a == '/') || (a == '\\')) sReference1 = sReference1.substr(0, sReference1.size() - 1);
3205 std::string::size_type iIndex1 = sPath1.find_first_of("/\\");
3206 std::string::size_type iIndex2 = sReference1.find_first_of("/\\");
3207 while ((iIndex1 == iIndex2) && (iIndex1 != std::string::npos)) {
3208 if (strncmp(sPath1.c_str(), sReference1.c_str(), iIndex1) != 0) break;
3209 sPath1 = sPath1.substr(iIndex1 + 1);
3210 sReference1 = sReference1.substr(iIndex2 + 1);
3211 iIndex1 = sPath1.find_first_of("/\\");
3212 iIndex2 = sReference1.find_first_of("/\\");
3213 }
3214 if (iIndex1 == std::string::npos) {
3215 if (iIndex2 == std::string::npos) {
3216 if (sPath1 == sReference1) return ".";
3217 return "../" + sPath1;
3218 } else if ((iIndex2 == sPath1.size()) && (strncmp(sPath1.c_str(), sReference1.c_str(), iIndex2) == 0)) {
3219 sPath1 = "";
3220 sReference1 = sReference1.substr(iIndex2 + 1);
3221 iIndex2 = sReference1.find_first_of("/\\");
3222 }
3223 } else {
3224 if (iIndex2 == std::string::npos) {
3225 if ((iIndex1 == sReference1.size()) && (strncmp(sPath1.c_str(), sReference1.c_str(), iIndex1) == 0)) {
3226 return sPath1.substr(iIndex1 + 1);
3227 }
3228 return "../" + sPath1;
3229 }
3230 }
3231 std::string sRelativePath;
3232 sRelativePath = "../";
3233 while (iIndex2 != std::string::npos) {
3234 sRelativePath += "../";
3235 sReference1 = sReference1.substr(iIndex2 + 1);
3236 iIndex2 = sReference1.find_first_of("/\\");
3237 }
3238 sRelativePath += sPath1;
3239 return sRelativePath;
3240 //##protect##"relativePath"
3241 }
3242
removeDirectory(const std::string & sPath)3243 bool CGRuntime::removeDirectory(const std::string& sPath) {
3244 //##protect##"removeDirectory"
3245 if (sPath.empty()) return false;
3246 UtlDirectory theDirectory(sPath);
3247 return theDirectory.remove();
3248 //##protect##"removeDirectory"
3249 }
3250
removeGenerationTagsHandler(const std::string & sKey)3251 bool CGRuntime::removeGenerationTagsHandler(const std::string& sKey) {
3252 //##protect##"removeGenerationTagsHandler"
3253 return DtaProject::getInstance().removeGenerationTagsHandler(sKey);
3254 //##protect##"removeGenerationTagsHandler"
3255 }
3256
repeatString(const std::string & sText,int iOccurrences)3257 std::string CGRuntime::repeatString(const std::string& sText, int iOccurrences) {
3258 //##protect##"repeatString"
3259 std::string sResult;
3260 while (iOccurrences-- > 0) sResult += sText;
3261 return sResult;
3262 //##protect##"repeatString"
3263 }
3264
replaceString(const std::string & sOld,const std::string & sNew,const std::string & sText)3265 std::string CGRuntime::replaceString(const std::string& sOld, const std::string& sNew, const std::string& sText) {
3266 //##protect##"replaceString"
3267 if (sOld.empty()) return sText;
3268 std::string::size_type iLastPos = 0;
3269 std::string::size_type iPos = sText.find(sOld);
3270 std::string sReplace;
3271 while (iPos != std::string::npos) {
3272 sReplace += sText.substr(iLastPos, iPos - iLastPos);
3273 sReplace += sNew;
3274 iLastPos = iPos + sOld.size();
3275 iPos = sText.find(sOld, iLastPos);
3276 }
3277 if (iLastPos != sText.size()) sReplace += sText.substr(iLastPos);
3278 return sReplace;
3279 //##protect##"replaceString"
3280 }
3281
replaceTabulations(const std::string & sText,int iTab)3282 std::string CGRuntime::replaceTabulations(const std::string& sText, int iTab) {
3283 //##protect##"replaceTabulations"
3284 std::string::size_type iLastPos = 0;
3285 std::string::size_type iPos = sText.find_first_of("\t\n");
3286 std::string sReplace;
3287 while (iPos != std::string::npos) {
3288 if (sText[iPos] == '\n') iPos++;
3289 sReplace += sText.substr(iLastPos, iPos - iLastPos);
3290 if (sText[iPos] == '\t') {
3291 int iNbSpaces = iTab - ((iPos - iLastPos) % iTab);
3292 sReplace += std::string(iNbSpaces, ' ');
3293 iLastPos = iPos + 1;
3294 } else {
3295 iLastPos = iPos;
3296 }
3297 iPos = sText.find_first_of("\t\n", iLastPos);
3298 }
3299 sReplace += sText.substr(iLastPos);
3300 return sReplace;
3301 //##protect##"replaceTabulations"
3302 }
3303
resolveFilePath(const std::string & sFilename)3304 std::string CGRuntime::resolveFilePath(const std::string& sFilename) {
3305 //##protect##"resolveFilePath"
3306 if (ScpStream::existVirtualFile(sFilename)) return sFilename;
3307 std::string sCompleteFileName;
3308 if (openInputFileFromIncludePath(sFilename.c_str(), sCompleteFileName) == NULL) return "";
3309 return sCompleteFileName;
3310 //##protect##"resolveFilePath"
3311 }
3312
rightString(const std::string & sText,int iLength)3313 std::string CGRuntime::rightString(const std::string& sText, int iLength) {
3314 //##protect##"rightString"
3315 if (iLength < 0) return "";
3316 if (iLength > (int) sText.size()) iLength = sText.size();
3317 return sText.substr(sText.size() - iLength, iLength);
3318 //##protect##"rightString"
3319 }
3320
rsubString(const std::string & sText,int iPos)3321 std::string CGRuntime::rsubString(const std::string& sText, int iPos) {
3322 //##protect##"rsubString"
3323 int iLength = ((int) sText.size()) - iPos;
3324 if ((iLength <= 0) || (iLength >= (int) sText.size())) return "";
3325 return sText.substr(0, iLength);
3326 //##protect##"rsubString"
3327 }
3328
scanDirectories(DtaScriptVariable * pDirectory,const std::string & sPath,const std::string & sPattern)3329 bool CGRuntime::scanDirectories(DtaScriptVariable* pDirectory, const std::string& sPath, const std::string& sPattern) {
3330 //##protect##"scanDirectories"
3331 UtlDirectory theDirectory(sPath);
3332 bool bSuccess;
3333 bSuccess = theDirectory.scanRecursively(sPattern);
3334 if (bSuccess) {
3335 pDirectory->clearContent();
3336 populateDirectory(pDirectory, theDirectory, true);
3337 }
3338 return bSuccess;
3339 //##protect##"scanDirectories"
3340 }
3341
scanDirectories(CppParsingTree_var pDirectory,const std::string & sPath,const std::string & sPattern)3342 bool CGRuntime::scanDirectories(CppParsingTree_var pDirectory, const std::string& sPath, const std::string& sPattern) {
3343 bool result = scanDirectories(pDirectory._pInternalNode, sPath, sPattern);
3344 return result;
3345 }
3346
scanFiles(DtaScriptVariable * pFiles,const std::string & sPath,const std::string & sPattern,bool bSubfolders)3347 bool CGRuntime::scanFiles(DtaScriptVariable* pFiles, const std::string& sPath, const std::string& sPattern, bool bSubfolders) {
3348 //##protect##"scanFiles"
3349 bool bSuccess;
3350 std::string sNewPath = sPath;
3351 std::string sNewPattern = sPattern;
3352 if (!bSubfolders) {
3353 std::string::size_type iIndex = sPattern.find_last_of("/\\");
3354 if (iIndex != std::string::npos) {
3355 // a directory in the pattern, special case if non recursive
3356 std::string sNewPath = sPath;
3357 if (!sNewPath.empty() && (sNewPath.find_last_of("/\\") != sNewPath.size() - 1)) {
3358 sNewPath += "/";
3359 }
3360 iIndex++;
3361 sNewPath += sPattern.substr(0, iIndex);
3362 sNewPattern = sPattern.substr(iIndex);
3363 }
3364 }
3365 UtlDirectory theDirectory(sNewPath);
3366 if (bSubfolders) {
3367 bSuccess = theDirectory.scanRecursively(sNewPattern);
3368 } else {
3369 bSuccess = theDirectory.scan(sNewPattern);
3370 }
3371 if (bSuccess) {
3372 pFiles->clearContent();
3373 populateFileScan(pFiles, theDirectory, bSubfolders);
3374 }
3375 return bSuccess;
3376 //##protect##"scanFiles"
3377 }
3378
scanFiles(CppParsingTree_var pFiles,const std::string & sPath,const std::string & sPattern,bool bSubfolders)3379 bool CGRuntime::scanFiles(CppParsingTree_var pFiles, const std::string& sPath, const std::string& sPattern, bool bSubfolders) {
3380 bool result = scanFiles(pFiles._pInternalNode, sPath, sPattern, bSubfolders);
3381 return result;
3382 }
3383
sendBinaryToSocket(int iSocket,const std::string & sBytes)3384 bool CGRuntime::sendBinaryToSocket(int iSocket, const std::string& sBytes) {
3385 //##protect##"sendBinaryToSocket"
3386 int iLength = sBytes.size();
3387 if ((iLength & 1) != 0) throw UtlException("sequence of bytes expected for 'sendBinaryToSocket()'");
3388 iLength >>= 1;
3389 char* tcBuffer = new char[iLength];
3390 if (!convertBytesToChars(sBytes, (unsigned char*) tcBuffer, iLength)) {
3391 delete [] tcBuffer;
3392 throw UtlException("invalid hexadecimal digit encountered");
3393 }
3394 bool bSuccess = NetSocket::sendToSocket(iSocket, tcBuffer, iLength);
3395 delete [] tcBuffer;
3396 return bSuccess;
3397 //##protect##"sendBinaryToSocket"
3398 }
3399
sendHTTPRequest(const std::string & sURL,DtaScriptVariable * pHTTPSession)3400 std::string CGRuntime::sendHTTPRequest(const std::string& sURL, DtaScriptVariable* pHTTPSession) {
3401 //##protect##"sendHTTPRequest"
3402 HTTPRequest request;
3403 return request.send(sURL, pHTTPSession);
3404 //##protect##"sendHTTPRequest"
3405 }
3406
sendHTTPRequest(const std::string & sURL,CppParsingTree_var pHTTPSession)3407 std::string CGRuntime::sendHTTPRequest(const std::string& sURL, CppParsingTree_var pHTTPSession) {
3408 std::string result = sendHTTPRequest(sURL, pHTTPSession._pInternalNode);
3409 return result;
3410 }
3411
sendTextToSocket(int iSocket,const std::string & sText)3412 bool CGRuntime::sendTextToSocket(int iSocket, const std::string& sText) {
3413 //##protect##"sendTextToSocket"
3414 return NetSocket::sendToSocket(iSocket, sText.c_str(), sText.size());
3415 //##protect##"sendTextToSocket"
3416 }
3417
selectGenerationTagsHandler(const std::string & sKey)3418 bool CGRuntime::selectGenerationTagsHandler(const std::string& sKey) {
3419 //##protect##"selectGenerationTagsHandler"
3420 return DtaProject::getInstance().selectGenerationTagsHandler(sKey);
3421 //##protect##"selectGenerationTagsHandler"
3422 }
3423
shortToBytes(unsigned short ulShort)3424 std::string CGRuntime::shortToBytes(unsigned short ulShort) {
3425 //##protect##"shortToBytes"
3426 char tcBytes[5];
3427 convertCharsToBytes((const unsigned char*) &ulShort, tcBytes, 2);
3428 return tcBytes;
3429 //##protect##"shortToBytes"
3430 }
3431
sqrt(double dX)3432 double CGRuntime::sqrt(double dX) {
3433 //##protect##"sqrt"
3434 return ::sqrt(dX);
3435 //##protect##"sqrt"
3436 }
3437
startString(const std::string & sText,const std::string & sStart)3438 bool CGRuntime::startString(const std::string& sText, const std::string& sStart) {
3439 //##protect##"startString"
3440 return (strncmp(sText.c_str(), sStart.c_str(), sStart.size()) == 0);
3441 //##protect##"startString"
3442 }
3443
sub(double dLeft,double dRight)3444 double CGRuntime::sub(double dLeft, double dRight) {
3445 //##protect##"sub"
3446 return dLeft - dRight;
3447 //##protect##"sub"
3448 }
3449
subString(const std::string & sText,int iPos)3450 std::string CGRuntime::subString(const std::string& sText, int iPos) {
3451 //##protect##"subString"
3452 return ((iPos < (int) sText.size()) ? sText.substr(iPos) : "");
3453 //##protect##"subString"
3454 }
3455
sup(double dLeft,double dRight)3456 bool CGRuntime::sup(double dLeft, double dRight) {
3457 //##protect##"sup"
3458 return (dLeft > dRight);
3459 //##protect##"sup"
3460 }
3461
system(const std::string & sCommand)3462 std::string CGRuntime::system(const std::string& sCommand) {
3463 //##protect##"system"
3464 #ifdef WIN32
3465 std::string sAdjustedCommand = sCommand;
3466 #endif
3467 const char* tcCommand = NULL;
3468 if (!sCommand.empty()) {
3469 #ifdef WIN32
3470 char cFinal = ((sCommand[0] == '"') ? '"' : ' ');
3471 int i = ((cFinal == '"') ? 1 : 0);
3472 char a = sAdjustedCommand[i];
3473 while ((a != cFinal) && (a != '\0')) {
3474 if (a == '/') sAdjustedCommand[i] = '\\';
3475 a = sAdjustedCommand[++i];
3476 }
3477 tcCommand = sAdjustedCommand.c_str();
3478 #else
3479 tcCommand = sCommand.c_str();
3480 #endif
3481 }
3482 int iResult = ::system(tcCommand);
3483 if (iResult == -1) {
3484 switch(errno) {
3485 case E2BIG: return "Argument list is too big for command interpreter";
3486 case ENOENT: return "Command interpreter cannot be found";
3487 case ENOEXEC: return "Command interpreter file has invalid format and is not executable";
3488 case ENOMEM: return "Not enough memory is available to execute command; or available memory has been corrupted; or invalid block exists, indicating that process making call was not allocated properly";
3489 default: return "Unknown error encountered by command interpreter";
3490 }
3491 } else if (iResult != 0) {
3492 return "The name specified isn't recognized as an executable";
3493 }
3494 return "";
3495 //##protect##"system"
3496 }
3497
toLowerString(const std::string & sText)3498 std::string CGRuntime::toLowerString(const std::string& sText) {
3499 //##protect##"toLowerString"
3500 std::string sCopy(sText.c_str());
3501 for (std::string::size_type i = 0; i < sCopy.size(); i++) {
3502 char a = sCopy[i];
3503 if ((a >= 'A') && (a <= 'Z')) sCopy[i] = a + ' ';
3504 }
3505 return sCopy;
3506 //##protect##"toLowerString"
3507 }
3508
toUpperString(const std::string & sText)3509 std::string CGRuntime::toUpperString(const std::string& sText) {
3510 //##protect##"toUpperString"
3511 std::string sCopy(sText.c_str());
3512 for (std::string::size_type i = 0; i < sCopy.size(); i++) {
3513 char a = sCopy[i];
3514 if ((a >= 'a') && (a <= 'z')) sCopy[i] = a - ' ';
3515 }
3516 return sCopy;
3517 //##protect##"toUpperString"
3518 }
3519
trimLeft(std::string & sString)3520 int CGRuntime::trimLeft(std::string& sString) {
3521 //##protect##"trimLeft"
3522 int i = 0;
3523 while ((sString[i] > '\0') && (sString[i] <= ' ')) i++;
3524 if (i > 0) {
3525 if (i < (int) sString.size()) {
3526 sString = sString.substr(i);
3527 } else {
3528 sString = "";
3529 }
3530 }
3531 return i;
3532 //##protect##"trimLeft"
3533 }
3534
trimLeft(CppParsingTree_var pString)3535 int CGRuntime::trimLeft(CppParsingTree_var pString) {
3536 std::string sString = pString.getValue();
3537 int result = trimLeft(sString);
3538 pString.setValue(sString);
3539 return result;
3540 }
3541
trimRight(std::string & sString)3542 int CGRuntime::trimRight(std::string& sString) {
3543 //##protect##"trimRight"
3544 int i = sString.size() - 1;
3545 int iCounter = i;
3546 while ((i >= 0) && (sString[i] > '\0') && (sString[i] <= ' ')) i--;
3547 iCounter -= i;
3548 if (iCounter > 0) {
3549 if (i >= 0) {
3550 sString = sString.substr(0, i + 1);
3551 } else {
3552 sString = "";
3553 }
3554 }
3555 return iCounter;
3556 //##protect##"trimRight"
3557 }
3558
trimRight(CppParsingTree_var pString)3559 int CGRuntime::trimRight(CppParsingTree_var pString) {
3560 std::string sString = pString.getValue();
3561 int result = trimRight(sString);
3562 pString.setValue(sString);
3563 return result;
3564 }
3565
trim(std::string & sString)3566 int CGRuntime::trim(std::string& sString) {
3567 //##protect##"trim"
3568 return trimLeft(sString) + trimRight(sString);
3569 //##protect##"trim"
3570 }
3571
trim(CppParsingTree_var pString)3572 int CGRuntime::trim(CppParsingTree_var pString) {
3573 std::string sString = pString.getValue();
3574 int result = trim(sString);
3575 pString.setValue(sString);
3576 return result;
3577 }
3578
truncateAfterString(DtaScriptVariable * pVariable,const std::string & sText)3579 std::string CGRuntime::truncateAfterString(DtaScriptVariable* pVariable, const std::string& sText) {
3580 //##protect##"truncateAfterString"
3581 std::string sString = pVariable->getValue();
3582 std::string::size_type iPos = sString.find(sText);
3583 if (iPos == std::string::npos) return "";
3584 iPos += sText.size();
3585 if (iPos >= sString.size()) pVariable->setValue("");
3586 else {
3587 std::string sNewValue = sString.substr(iPos);
3588 pVariable->setValue(sNewValue.c_str());
3589 }
3590 return sString.substr(0, iPos);
3591 //##protect##"truncateAfterString"
3592 }
3593
truncateAfterString(CppParsingTree_var pVariable,const std::string & sText)3594 std::string CGRuntime::truncateAfterString(CppParsingTree_var pVariable, const std::string& sText) {
3595 std::string result = truncateAfterString(pVariable._pInternalNode, sText);
3596 return result;
3597 }
3598
truncateBeforeString(DtaScriptVariable * pVariable,const std::string & sText)3599 std::string CGRuntime::truncateBeforeString(DtaScriptVariable* pVariable, const std::string& sText) {
3600 //##protect##"truncateBeforeString"
3601 std::string sString = pVariable->getValue();
3602 std::string::size_type iPos = sString.find(sText);
3603 if (iPos == std::string::npos) return "";
3604 if (iPos == 0) pVariable->setValue("");
3605 else {
3606 std::string sNewValue = sString.substr(0, iPos);
3607 pVariable->setValue(sNewValue.c_str());
3608 }
3609 return sString.substr(iPos);
3610 //##protect##"truncateBeforeString"
3611 }
3612
truncateBeforeString(CppParsingTree_var pVariable,const std::string & sText)3613 std::string CGRuntime::truncateBeforeString(CppParsingTree_var pVariable, const std::string& sText) {
3614 std::string result = truncateBeforeString(pVariable._pInternalNode, sText);
3615 return result;
3616 }
3617
UUID()3618 std::string CGRuntime::UUID() {
3619 //##protect##"UUID"
3620 return HTTPRequest::UUID();
3621 //##protect##"UUID"
3622 }
3623
countInputCols()3624 int CGRuntime::countInputCols() {
3625 //##protect##"countInputCols"
3626 return _pInputStream->getColCount();
3627 //##protect##"countInputCols"
3628 }
3629
countInputLines()3630 int CGRuntime::countInputLines() {
3631 //##protect##"countInputLines"
3632 return _pInputStream->getLineCount();
3633 //##protect##"countInputLines"
3634 }
3635
getInputFilename()3636 std::string CGRuntime::getInputFilename() {
3637 //##protect##"getInputFilename"
3638 return _pInputStream->getFilename();
3639 //##protect##"getInputFilename"
3640 }
3641
getLastReadChars(int iLength)3642 std::string CGRuntime::getLastReadChars(int iLength) {
3643 //##protect##"getLastReadChars"
3644 std::string sLastChars;
3645 _pInputStream->readLastChars(iLength, sLastChars);
3646 return sLastChars;
3647 //##protect##"getLastReadChars"
3648 }
3649
getInputLocation()3650 int CGRuntime::getInputLocation() {
3651 //##protect##"getInputLocation"
3652 return _pInputStream->getInputLocation();
3653 //##protect##"getInputLocation"
3654 }
3655
lookAhead(const std::string & sText)3656 bool CGRuntime::lookAhead(const std::string& sText) {
3657 //##protect##"lookAhead"
3658 if (!_pInputStream->isEqualTo(sText)) return false;
3659 _pInputStream->setInputLocation(_pInputStream->getInputLocation() - sText.size());
3660 return true;
3661 //##protect##"lookAhead"
3662 }
3663
peekChar()3664 std::string CGRuntime::peekChar() {
3665 //##protect##"peekChar"
3666 static char tcResult[] = {'\0', '\0'};
3667 int iChar = _pInputStream->peekChar();
3668 if (iChar > 0) tcResult[0] = (char) iChar;
3669 else tcResult[0] = '\0';
3670 return tcResult;
3671 //##protect##"peekChar"
3672 }
3673
readAdaString(std::string & sText)3674 bool CGRuntime::readAdaString(std::string& sText) {
3675 //##protect##"readAdaString"
3676 return _pInputStream->readAdaString(sText);
3677 //##protect##"readAdaString"
3678 }
3679
readAdaString(CppParsingTree_var pText)3680 bool CGRuntime::readAdaString(CppParsingTree_var pText) {
3681 std::string sText = pText.getValue();
3682 bool result = readAdaString(sText);
3683 pText.setValue(sText);
3684 return result;
3685 }
3686
readByte()3687 std::string CGRuntime::readByte() {
3688 //##protect##"readByte"
3689 char tcText[] = {'\0', '\0', '\0'};
3690 int iChar = _pInputStream->readChar();
3691 if (iChar >= 0) {
3692 tcText[0] = _tcHexa[iChar >> 4];
3693 tcText[1] = _tcHexa[iChar & 0x0F];
3694 }
3695 return tcText;
3696 //##protect##"readByte"
3697 }
3698
readBytes(int iLength)3699 std::string CGRuntime::readBytes(int iLength) {
3700 //##protect##"readBytes"
3701 char* tcText = new char[iLength*2 + 1];
3702 int iLocation = _pInputStream->getInputLocation();
3703 int j = 0;
3704 int iChar;
3705 for (int i = 0; i < iLength; i++) {
3706 iChar = _pInputStream->readChar();
3707 if (iChar < 0) {
3708 delete [] tcText;
3709 _pInputStream->setInputLocation(iLocation);
3710 return "";
3711 }
3712 tcText[j++] = _tcHexa[iChar >> 4];
3713 tcText[j++] = _tcHexa[iChar & 0x0F];
3714 }
3715 tcText[j] = '\0';
3716 std::string sBytes = tcText;
3717 delete [] tcText;
3718 return sBytes;
3719 //##protect##"readBytes"
3720 }
3721
readCChar()3722 std::string CGRuntime::readCChar() {
3723 //##protect##"readCChar"
3724 static char tcResult[] = {'\0', '\0'};
3725 int iChar;
3726 if (_pInputStream->readCharLiteral(iChar)) tcResult[0] = (char) iChar;
3727 else tcResult[0] = '\0';
3728 return tcResult;
3729 //##protect##"readCChar"
3730 }
3731
readChar()3732 std::string CGRuntime::readChar() {
3733 //##protect##"readChar"
3734 static char tcResult[] = {'\0', '\0'};
3735 int iChar = _pInputStream->readChar();
3736 if (iChar > 0) tcResult[0] = (char) iChar;
3737 else tcResult[0] = '\0';
3738 return tcResult;
3739 //##protect##"readChar"
3740 }
3741
readCharAsInt()3742 int CGRuntime::readCharAsInt() {
3743 //##protect##"readCharAsInt"
3744 return _pInputStream->readChar();
3745 //##protect##"readCharAsInt"
3746 }
3747
readChars(int iLength)3748 std::string CGRuntime::readChars(int iLength) {
3749 //##protect##"readChars"
3750 std::string sText;
3751 _pInputStream->readChars(iLength, sText);
3752 return sText;
3753 //##protect##"readChars"
3754 }
3755
readIdentifier()3756 std::string CGRuntime::readIdentifier() {
3757 //##protect##"readIdentifier"
3758 std::string sIdentifier;
3759 if (!_pInputStream->readIdentifier(sIdentifier)) return "";
3760 return sIdentifier;
3761 //##protect##"readIdentifier"
3762 }
3763
readIfEqualTo(const std::string & sText)3764 bool CGRuntime::readIfEqualTo(const std::string& sText) {
3765 //##protect##"readIfEqualTo"
3766 return _pInputStream->isEqualTo(sText);
3767 //##protect##"readIfEqualTo"
3768 }
3769
readIfEqualToIgnoreCase(const std::string & sText)3770 bool CGRuntime::readIfEqualToIgnoreCase(const std::string& sText) {
3771 //##protect##"readIfEqualToIgnoreCase"
3772 return _pInputStream->isEqualToIgnoreCase(sText);
3773 //##protect##"readIfEqualToIgnoreCase"
3774 }
3775
readIfEqualToIdentifier(const std::string & sIdentifier)3776 bool CGRuntime::readIfEqualToIdentifier(const std::string& sIdentifier) {
3777 //##protect##"readIfEqualToIdentifier"
3778 return _pInputStream->isEqualToIdentifier(sIdentifier.c_str());
3779 //##protect##"readIfEqualToIdentifier"
3780 }
3781
readLine(std::string & sText)3782 bool CGRuntime::readLine(std::string& sText) {
3783 //##protect##"readLine"
3784 return _pInputStream->readLine(sText);
3785 //##protect##"readLine"
3786 }
3787
readLine(CppParsingTree_var pText)3788 bool CGRuntime::readLine(CppParsingTree_var pText) {
3789 std::string sText = pText.getValue();
3790 bool result = readLine(sText);
3791 pText.setValue(sText);
3792 return result;
3793 }
3794
readNextText(const std::string & sText)3795 bool CGRuntime::readNextText(const std::string& sText) {
3796 //##protect##"readNextText"
3797 return _pInputStream->findString(sText);
3798 //##protect##"readNextText"
3799 }
3800
readNumber(double & dNumber)3801 bool CGRuntime::readNumber(double& dNumber) {
3802 //##protect##"readNumber"
3803 return _pInputStream->readDouble(dNumber);
3804 //##protect##"readNumber"
3805 }
3806
readNumber(CppParsingTree_var pNumber)3807 bool CGRuntime::readNumber(CppParsingTree_var pNumber) {
3808 double dNumber = pNumber.getDoubleValue();
3809 bool result = readNumber(dNumber);
3810 pNumber.setValue(dNumber);
3811 return result;
3812 }
3813
readPythonString(std::string & sText)3814 bool CGRuntime::readPythonString(std::string& sText) {
3815 //##protect##"readPythonString"
3816 return _pInputStream->readPythonString(sText);
3817 //##protect##"readPythonString"
3818 }
3819
readPythonString(CppParsingTree_var pText)3820 bool CGRuntime::readPythonString(CppParsingTree_var pText) {
3821 std::string sText = pText.getValue();
3822 bool result = readPythonString(sText);
3823 pText.setValue(sText);
3824 return result;
3825 }
3826
readString(std::string & sText)3827 bool CGRuntime::readString(std::string& sText) {
3828 //##protect##"readString"
3829 return _pInputStream->readString(sText);
3830 //##protect##"readString"
3831 }
3832
readString(CppParsingTree_var pText)3833 bool CGRuntime::readString(CppParsingTree_var pText) {
3834 std::string sText = pText.getValue();
3835 bool result = readString(sText);
3836 pText.setValue(sText);
3837 return result;
3838 }
3839
readUptoJustOneChar(const std::string & sOneAmongChars)3840 std::string CGRuntime::readUptoJustOneChar(const std::string& sOneAmongChars) {
3841 //##protect##"readUptoJustOneChar"
3842 std::string sText;
3843 if (!_pInputStream->readUptoChar(sOneAmongChars, sText)) return "";
3844 return sText;
3845 //##protect##"readUptoJustOneChar"
3846 }
3847
readWord()3848 std::string CGRuntime::readWord() {
3849 //##protect##"readWord"
3850 std::string sWord;
3851 if (!_pInputStream->readWord(sWord)) return "";
3852 return sWord;
3853 //##protect##"readWord"
3854 }
3855
skipBlanks()3856 bool CGRuntime::skipBlanks() {
3857 //##protect##"skipBlanks"
3858 return _pInputStream->skipBlanks();
3859 //##protect##"skipBlanks"
3860 }
3861
skipSpaces()3862 bool CGRuntime::skipSpaces() {
3863 //##protect##"skipSpaces"
3864 return _pInputStream->skipSpaces();
3865 //##protect##"skipSpaces"
3866 }
3867
skipEmptyCpp()3868 bool CGRuntime::skipEmptyCpp() {
3869 //##protect##"skipEmptyCpp"
3870 return _pInputStream->skipEmpty();
3871 //##protect##"skipEmptyCpp"
3872 }
3873
skipEmptyCppExceptDoxygen()3874 bool CGRuntime::skipEmptyCppExceptDoxygen() {
3875 //##protect##"skipEmptyCppExceptDoxygen"
3876 return _pInputStream->skipEmptyCppExceptDoxygen();
3877 //##protect##"skipEmptyCppExceptDoxygen"
3878 }
3879
skipEmptyHTML()3880 bool CGRuntime::skipEmptyHTML() {
3881 //##protect##"skipEmptyHTML"
3882 return _pInputStream->skipEmptyHTML();
3883 //##protect##"skipEmptyHTML"
3884 }
3885
skipEmptyLaTeX()3886 bool CGRuntime::skipEmptyLaTeX() {
3887 //##protect##"skipEmptyLaTeX"
3888 return _pInputStream->skipEmptyLaTeX();
3889 //##protect##"skipEmptyLaTeX"
3890 }
3891
countOutputCols()3892 int CGRuntime::countOutputCols() {
3893 //##protect##"countOutputCols"
3894 return _pOutputStream->getOutputColCount();
3895 //##protect##"countOutputCols"
3896 }
3897
countOutputLines()3898 int CGRuntime::countOutputLines() {
3899 //##protect##"countOutputLines"
3900 return _pOutputStream->getOutputLineCount();
3901 //##protect##"countOutputLines"
3902 }
3903
decrementIndentLevel(int iLevel)3904 bool CGRuntime::decrementIndentLevel(int iLevel) {
3905 //##protect##"decrementIndentLevel"
3906 return _pOutputStream->decrementIndentation(iLevel);
3907 //##protect##"decrementIndentLevel"
3908 }
3909
equalLastWrittenChars(const std::string & sText)3910 bool CGRuntime::equalLastWrittenChars(const std::string& sText) {
3911 //##protect##"equalLastWrittenChars"
3912 std::string sLastChars = _pOutputStream->getLastWrittenChars(sText.length());
3913 return sLastChars == sText;
3914 //##protect##"equalLastWrittenChars"
3915 }
3916
existFloatingLocation(const std::string & sKey,bool bParent)3917 bool CGRuntime::existFloatingLocation(const std::string& sKey, bool bParent) {
3918 //##protect##"existFloatingLocation"
3919 ScpStream* pOwner;
3920 int iPosition = _pOutputStream->getFloatingLocation(sKey, pOwner);
3921 return ((bParent) ? (pOwner != NULL) : (pOwner == _pOutputStream));
3922 //##protect##"existFloatingLocation"
3923 }
3924
getFloatingLocation(const std::string & sKey)3925 int CGRuntime::getFloatingLocation(const std::string& sKey) {
3926 //##protect##"getFloatingLocation"
3927 ScpStream* pOwner;
3928 int iPosition = _pOutputStream->getFloatingLocation(sKey, pOwner);
3929 if (pOwner == NULL) throw UtlException("the floating area '" + sKey + "' doesn't exist.");
3930 if (pOwner != _pOutputStream) throw UtlException("the floating area '" + sKey + "' was put in a precedent markup area, but not in this one.");
3931 return iPosition;
3932 //##protect##"getFloatingLocation"
3933 }
3934
getLastWrittenChars(int iNbChars)3935 std::string CGRuntime::getLastWrittenChars(int iNbChars) {
3936 //##protect##"getLastWrittenChars"
3937 std::string sLastChars = _pOutputStream->getLastWrittenChars(iNbChars);
3938 return sLastChars;
3939 //##protect##"getLastWrittenChars"
3940 }
3941
getMarkupKey()3942 std::string CGRuntime::getMarkupKey() {
3943 //##protect##"getMarkupKey"
3944 return DtaProject::getInstance().getMarkupKey();
3945 //##protect##"getMarkupKey"
3946 }
3947
getMarkupValue()3948 std::string CGRuntime::getMarkupValue() {
3949 //##protect##"getMarkupValue"
3950 return DtaProject::getInstance().getMarkupValue();
3951 //##protect##"getMarkupValue"
3952 }
3953
getOutputFilename()3954 std::string CGRuntime::getOutputFilename() {
3955 //##protect##"getOutputFilename"
3956 return _pOutputStream->getFilename();
3957 //##protect##"getOutputFilename"
3958 }
3959
getOutputLocation()3960 int CGRuntime::getOutputLocation() {
3961 //##protect##"getOutputLocation"
3962 return _pOutputStream->getOutputLocation();
3963 //##protect##"getOutputLocation"
3964 }
3965
getProtectedArea(const std::string & sProtection)3966 std::string CGRuntime::getProtectedArea(const std::string& sProtection) {
3967 //##protect##"getProtectedArea"
3968 DtaPatternScript* pPatternScript = _listOfPatternScripts.front();
3969 return pPatternScript->getProtectedAreasBag().getProtection(sProtection.c_str());
3970 //##protect##"getProtectedArea"
3971 }
3972
getProtectedAreaKeys(DtaScriptVariable * pKeys)3973 int CGRuntime::getProtectedAreaKeys(DtaScriptVariable* pKeys) {
3974 //##protect##"getProtectedAreaKeys"
3975 if (pKeys == NULL) return -1;
3976 pKeys->clearContent();
3977 std::list<std::string> listOfKeys = _listOfPatternScripts.front()->getProtectionKeys();
3978 for (std::list<std::string>::const_iterator i = listOfKeys.begin(); i != listOfKeys.end(); ++i) {
3979 pKeys->addElement(*i)->setValue(i->c_str());
3980 }
3981 return listOfKeys.size();
3982 //##protect##"getProtectedAreaKeys"
3983 }
3984
getProtectedAreaKeys(CppParsingTree_var pKeys)3985 int CGRuntime::getProtectedAreaKeys(CppParsingTree_var pKeys) {
3986 int result = getProtectedAreaKeys(pKeys._pInternalNode);
3987 return result;
3988 }
3989
indentText(const std::string & sMode)3990 bool CGRuntime::indentText(const std::string& sMode) {
3991 //##protect##"indentText"
3992 if (stricmp(sMode.c_str(), "c++") == 0) return _pOutputStream->indentAsCpp();
3993 if (stricmp(sMode.c_str(), "java") == 0) return _pOutputStream->indentAsCpp();
3994 throw UtlException("function 'indentText(<mode>)' works on C++ and JAVA only at the present time, so '" + sMode + "' is refused");
3995 //##protect##"indentText"
3996 }
3997
newFloatingLocation(const std::string & sKey)3998 bool CGRuntime::newFloatingLocation(const std::string& sKey) {
3999 //##protect##"newFloatingLocation"
4000 return _pOutputStream->newFloatingLocation(sKey);
4001 //##protect##"newFloatingLocation"
4002 }
4003
remainingProtectedAreas(DtaScriptVariable * pKeys)4004 int CGRuntime::remainingProtectedAreas(DtaScriptVariable* pKeys) {
4005 //##protect##"remainingProtectedAreas"
4006 if (pKeys == NULL) return -1;
4007 pKeys->clearContent();
4008 std::list<std::string> listOfKeys = _listOfPatternScripts.front()->remainingProtectionKeys();
4009 for (std::list<std::string>::const_iterator i = listOfKeys.begin(); i != listOfKeys.end(); ++i) {
4010 pKeys->addElement(*i)->setValue(i->c_str());
4011 }
4012 return listOfKeys.size();
4013 //##protect##"remainingProtectedAreas"
4014 }
4015
remainingProtectedAreas(CppParsingTree_var pKeys)4016 int CGRuntime::remainingProtectedAreas(CppParsingTree_var pKeys) {
4017 int result = remainingProtectedAreas(pKeys._pInternalNode);
4018 return result;
4019 }
4020
removeFloatingLocation(const std::string & sKey)4021 int CGRuntime::removeFloatingLocation(const std::string& sKey) {
4022 //##protect##"removeFloatingLocation"
4023 ScpStream* pOwner;
4024 int iPosition = _pOutputStream->removeFloatingLocation(sKey, pOwner);
4025 return iPosition;
4026 //##protect##"removeFloatingLocation"
4027 }
4028
removeProtectedArea(const std::string & sProtectedAreaName)4029 bool CGRuntime::removeProtectedArea(const std::string& sProtectedAreaName) {
4030 //##protect##"removeProtectedArea"
4031 return _listOfPatternScripts.front()->removeProtectedArea(sProtectedAreaName);
4032 //##protect##"removeProtectedArea"
4033 }
4034
4035 //##end##"functions and procedures"
4036
extractGenerationHeader(ScpStream & theStream,std::string & sGenerator,std::string & sVersion,std::string & sDate,std::string & sComment)4037 bool CGRuntime::extractGenerationHeader(ScpStream& theStream, std::string& sGenerator, std::string& sVersion, std::string& sDate, std::string& sComment) {
4038 bool bSuccess = false;
4039 std::string sCommentBegin = DtaProject::getInstance().getCommentBegin();
4040 std::string sBeginningMarker = sCommentBegin + "##generation header##";
4041 theStream.setInputLocation(0);
4042 if (theStream.isEqualTo(sBeginningMarker)) {
4043 if (theStream.readUptoChar('#', sGenerator) && theStream.isEqualTo("##")) {
4044 if (theStream.readUptoChar('#', sVersion) && theStream.isEqualTo("##")) {
4045 if (theStream.readUptoChar('#', sDate) && theStream.isEqualTo("##")) {
4046 std::string sFile;
4047 bool bCommentExtracted = false;
4048 if (theStream.readString(sFile)) {
4049 if (!theStream.isEqualTo("##")) {
4050 sComment = sFile;
4051 sFile.clear();
4052 bCommentExtracted = true;
4053 }
4054 }
4055 if (bCommentExtracted || theStream.readString(sComment)) {
4056 bSuccess = true;
4057 } else {
4058 std::string sCommentEnd = DtaProject::getInstance().getCommentEnd();
4059 if (theStream.findString(sCommentBegin + "##header start##") && theStream.findString(sCommentEnd)) {
4060 if (sCommentEnd.find('\n') == std::string::npos) theStream.findString("\n");
4061 int iStart = theStream.getInputLocation();
4062 std::string sMarker = sCommentBegin + "##header end##";
4063 if (theStream.findString(sMarker)) {
4064 int iEnd = theStream.getInputLocation();
4065 theStream.readLastChars(iEnd - iStart, sComment);
4066 sComment = replaceString("\r", "", sComment.substr(0, iEnd - iStart - sMarker.size()));
4067 if (sCommentEnd.find('\n') == std::string::npos) sCommentEnd += "\n";
4068 std::string sSeparator = sCommentEnd + sCommentBegin;
4069 sComment = sComment.substr(sCommentBegin.size(), sComment.size() - sSeparator.size());
4070 sComment = replaceString(sSeparator, "\n", sComment);
4071 bSuccess = true;
4072 }
4073 }
4074 }
4075 }
4076 }
4077 }
4078 }
4079 if (bSuccess) {
4080 std::string sCommentEnd = DtaProject::getInstance().getCommentEnd();
4081 if (sCommentEnd.find('\n') != std::string::npos) {
4082 if (!theStream.findString("\n")) {
4083 theStream.setInputLocation(0);
4084 bSuccess = false;
4085 }
4086 } else if (!theStream.isEqualTo(sCommentEnd)) {
4087 theStream.setInputLocation(0);
4088 bSuccess = false;
4089 }
4090 } else theStream.setInputLocation(0);
4091 return bSuccess;
4092 }
4093
populateDirectory(DtaScriptVariable * pDirectory,UtlDirectory & theDirectory,bool bSubfolders)4094 void CGRuntime::populateDirectory(DtaScriptVariable* pDirectory, UtlDirectory& theDirectory, bool bSubfolders) {
4095 pDirectory->setValue(theDirectory.getRelativePath().c_str());
4096 if (!theDirectory.getFiles().empty()) {
4097 DtaScriptVariable* pFiles = pDirectory->insertNode("files");
4098 for (std::list<UtlFile*>::const_iterator i = theDirectory.getFiles().begin(); i != theDirectory.getFiles().end(); ++i) {
4099 const std::string& sName = (*i)->getFileName();
4100 DtaScriptVariable* pNode = pFiles->addElement(sName);
4101 pNode->setValue(sName.c_str());
4102 }
4103 }
4104 if (!theDirectory.getDirectories().empty()) {
4105 DtaScriptVariable* pDirectories = pDirectory->insertNode("directories");
4106 for (std::list<UtlDirectory*>::const_iterator i = theDirectory.getDirectories().begin(); i != theDirectory.getDirectories().end(); ++i) {
4107 DtaScriptVariable* pNode = pDirectories->addElement((*i)->getDirectoryName());
4108 if (bSubfolders) populateDirectory(pNode, *(*i), true);
4109 else pNode->setValue((*i)->getRelativePath().c_str());
4110 }
4111 }
4112 }
4113
populateFileScan(DtaScriptVariable * pFiles,UtlDirectory & theDirectory,bool bSubfolders)4114 void CGRuntime::populateFileScan(DtaScriptVariable* pFiles, UtlDirectory& theDirectory, bool bSubfolders) {
4115 if (!theDirectory.getFiles().empty()) {
4116 for (std::list<UtlFile*>::const_iterator i = theDirectory.getFiles().begin(); i != theDirectory.getFiles().end(); ++i) {
4117 std::string sRelativePath = (*i)->getDirectory()->getRelativePath() + (*i)->getFileName();
4118 DtaScriptVariable* pNode = pFiles->addElement(sRelativePath);
4119 pNode->setValue(sRelativePath.c_str());
4120 }
4121 }
4122 if (!theDirectory.getDirectories().empty() && bSubfolders) {
4123 for (std::list<UtlDirectory*>::const_iterator i = theDirectory.getDirectories().begin(); i != theDirectory.getDirectories().end(); ++i) {
4124 populateFileScan(pFiles, *(*i), true);
4125 }
4126 }
4127 }
4128
copySmartDirectory(UtlDirectory & theDirectory,const std::string & sDestinationPath)4129 void CGRuntime::copySmartDirectory(UtlDirectory& theDirectory, const std::string& sDestinationPath) {
4130 if (!theDirectory.getFiles().empty()) {
4131 for (std::list<UtlFile*>::const_iterator i = theDirectory.getFiles().begin(); i != theDirectory.getFiles().end(); ++i) {
4132 copySmartFile(theDirectory.getFullPath() + (*i)->getFileName(), sDestinationPath + (*i)->getFileName());
4133 }
4134 }
4135 if (!theDirectory.getDirectories().empty()) {
4136 for (std::list<UtlDirectory*>::const_iterator i = theDirectory.getDirectories().begin(); i != theDirectory.getDirectories().end(); ++i) {
4137 copySmartDirectory(*(*i), sDestinationPath + (*i)->getDirectoryName() + "/");
4138 }
4139 }
4140 }
4141
convertBytesToChars(const std::string & sBytes,unsigned char * tcBuffer,int iLength)4142 bool CGRuntime::convertBytesToChars(const std::string& sBytes, unsigned char* tcBuffer, int iLength) {
4143 int i = 0;
4144 for (int j = 0; j < iLength; j++) {
4145 unsigned char c;
4146 char a = sBytes[i++];
4147 if (a <= '9') {
4148 if (a < '0') return false;
4149 c = a - '0';
4150 } else if (a <= 'F') {
4151 if (a < 'A') return false;
4152 c = (a - 'A') + 10;
4153 } else if ((a >= 'a') && (a <= 'f')) {
4154 c = (a - 'a') + 10;
4155 } else return false;
4156 c <<= 4;
4157 a = sBytes[i++];
4158 if (a <= '9') {
4159 if (a < '0') return false;
4160 c += a - '0';
4161 } else if (a <= 'F') {
4162 if (a < 'A') return false;
4163 c += (a - 'A') + 10;
4164 } else if ((a >= 'a') && (a <= 'f')) {
4165 c += (a - 'a') + 10;
4166 } else return false;
4167 tcBuffer[j] = c;
4168 }
4169 return true;
4170 }
4171
convertCharsToBytes(const unsigned char * tcBuffer,char * tcContent,int iLength)4172 void CGRuntime::convertCharsToBytes(const unsigned char* tcBuffer, char* tcContent, int iLength) {
4173 int j = 0;
4174 for (int i = 0; i < iLength; i++) {
4175 unsigned char c = tcBuffer[i];
4176 tcContent[j++] = _tcHexa[c >> 4];
4177 tcContent[j++] = _tcHexa[c & 0x0F];
4178 }
4179 tcContent[j] = '\0';
4180 }
4181
4182
getExternalFunctionsRegister()4183 std::map<std::string, EXTERNAL_FUNCTION>& CGRuntime::getExternalFunctionsRegister() {
4184 static std::map<std::string, EXTERNAL_FUNCTION> theRegister;
4185 return theRegister;
4186 }
4187
getExternalTemplateDispatcherFunctionsRegister()4188 std::map<std::string, EXTERNAL_TEMPLATE_DISPATCHER_FUNCTION>& CGRuntime::getExternalTemplateDispatcherFunctionsRegister() {
4189 static std::map<std::string, EXTERNAL_TEMPLATE_DISPATCHER_FUNCTION> theRegister;
4190 return theRegister;
4191 }
4192
4193
4194
CGRuntimeInputStream(ScpStream * pNewStream)4195 CGRuntimeInputStream::CGRuntimeInputStream(ScpStream* pNewStream) {
4196 _pOldStream = CGRuntime::_pInputStream;
4197 CGRuntime::_pInputStream = pNewStream;
4198 }
4199
~CGRuntimeInputStream()4200 CGRuntimeInputStream::~CGRuntimeInputStream() {
4201 CGRuntime::_pInputStream = _pOldStream;
4202 }
4203
CGRuntimeOutputStream(ScpStream * pNewStream)4204 CGRuntimeOutputStream::CGRuntimeOutputStream(ScpStream* pNewStream) {
4205 _pOldStream = CGRuntime::_pOutputStream;
4206 CGRuntime::_pOutputStream = pNewStream;
4207 }
4208
~CGRuntimeOutputStream()4209 CGRuntimeOutputStream::~CGRuntimeOutputStream() {
4210 CGRuntime::_pOutputStream = _pOldStream;
4211 }
4212
4213
CGRuntimeInputFile(const std::string & sFile)4214 CGRuntimeInputFile::CGRuntimeInputFile(const std::string& sFile) : _sFile(sFile), _pOldInputStream(NULL), _pNewStream(NULL) {
4215 _pOldInputStream = CGRuntime::_pInputStream;
4216 _pNewStream = new ScpStream(sFile, ScpStream::IN | ScpStream::PATH);
4217 CGRuntime::_pInputStream = _pNewStream;
4218 }
4219
~CGRuntimeInputFile()4220 CGRuntimeInputFile::~CGRuntimeInputFile() {
4221 CGRuntime::_pInputStream = _pOldInputStream;
4222 if (_pNewStream != NULL) {
4223 _pNewStream->close();
4224 delete _pNewStream;
4225 }
4226 }
4227
onCatchedException(const UtlException & exception)4228 std::string CGRuntimeInputFile::onCatchedException(const UtlException& exception) {
4229 int iLine = CGRuntime::_pInputStream->getLineCount();
4230 std::string sException = exception.getMessage();
4231 std::string sMessage = _sFile;
4232 char tcNumber[32];
4233 sprintf(tcNumber, "(%d):", iLine);
4234 sMessage += tcNumber;
4235 sMessage += CGRuntime::endl() + sException;
4236 return sMessage;
4237 }
4238
4239
CGRuntimeInputString(const std::string & sText)4240 CGRuntimeInputString::CGRuntimeInputString(const std::string& sText) : _pOldInputStream(NULL), _pNewStream(NULL) {
4241 _pOldInputStream = CGRuntime::_pInputStream;
4242 _pNewStream = new ScpStream(sText);
4243 CGRuntime::_pInputStream = _pNewStream;
4244 }
4245
~CGRuntimeInputString()4246 CGRuntimeInputString::~CGRuntimeInputString() {
4247 CGRuntime::_pInputStream = _pOldInputStream;
4248 if (_pNewStream != NULL) {
4249 _pNewStream->close();
4250 delete _pNewStream;
4251 }
4252 }
4253
onCatchedException(const UtlException & exception)4254 std::string CGRuntimeInputString::onCatchedException(const UtlException& exception) {
4255 int iLine = CGRuntime::_pInputStream->getLineCount();
4256 std::string sException = exception.getMessage();
4257 std::string sMessage;
4258 if (!CGRuntime::_pInputStream->empty()) {
4259 sMessage += CGRuntime::endl() + "----------------- content -----------------" +
4260 CGRuntime::endl() + CGRuntime::_pInputStream->readBuffer() +
4261 CGRuntime::endl() + "-------------------------------------------" + CGRuntime::endl();
4262 }
4263 char tcNumber[40];
4264 sprintf(tcNumber, "line %d", iLine);
4265 sMessage += tcNumber;
4266 sMessage += ":" + CGRuntime::endl() + sException;
4267 return sMessage;
4268 }
4269
4270
CGRuntimeOutputString()4271 CGRuntimeOutputString::CGRuntimeOutputString() {
4272 _pGeneratedString = new DtaOutputFile(0);
4273 _pGeneratedString->openGenerate(true, NULL, _pOldOutputStream);
4274 }
4275
~CGRuntimeOutputString()4276 CGRuntimeOutputString::~CGRuntimeOutputString() {
4277 delete _pGeneratedString;
4278 }
4279
onCatchedException(UtlException & exception)4280 void CGRuntimeOutputString::onCatchedException(UtlException& exception) {
4281 _pGeneratedString->catchGenerateExecution(true, _pOldOutputStream, &exception);
4282 }
4283
getResult() const4284 std::string CGRuntimeOutputString::getResult() const {
4285 return _pGeneratedString->closeGenerate(true, NULL, _pOldOutputStream);
4286 }
4287
4288
CGRuntimeOutputFile(const std::string & sFile,bool bAppendMode)4289 CGRuntimeOutputFile::CGRuntimeOutputFile(const std::string& sFile, bool bAppendMode) : _bAppendMode(bAppendMode) {
4290 _pGeneratedString = new DtaOutputFile(0);
4291 if (_bAppendMode) {
4292 _pGeneratedString->openAppend(true, sFile.c_str(), _pOldOutputStream);
4293 } else {
4294 _pGeneratedString->openGenerate(true, sFile.c_str(), _pOldOutputStream);
4295 }
4296 }
4297
~CGRuntimeOutputFile()4298 CGRuntimeOutputFile::~CGRuntimeOutputFile() {
4299 delete _pGeneratedString;
4300 }
4301
onCatchedException(UtlException & exception)4302 void CGRuntimeOutputFile::onCatchedException(UtlException& exception) {
4303 _pGeneratedString->catchGenerateExecution(true, _pOldOutputStream, &exception);
4304 }
4305
closeGenerate()4306 void CGRuntimeOutputFile::closeGenerate() {
4307 _pGeneratedString->closeGenerate(true, CGRuntime::_pOutputStream->getFilename().c_str(), _pOldOutputStream);
4308 }
4309
CGRuntimeNewProject()4310 CGRuntimeNewProject::CGRuntimeNewProject() {
4311 _pNewProject = new DtaProject;
4312 }
4313
~CGRuntimeNewProject()4314 CGRuntimeNewProject::~CGRuntimeNewProject() {
4315 delete _pNewProject;
4316 }
4317
4318
4319
4320 struct CGRuntimeTemporaryMatchingStorage {
4321 bool bBegin;
4322 DtaScriptVariable* pClauseNode;
CGRuntimeTemporaryMatchingStorageCodeWorker::CGRuntimeTemporaryMatchingStorage4323 CGRuntimeTemporaryMatchingStorage(bool b, DtaScriptVariable* p) : bBegin(b), pClauseNode(p) {}
4324 };
4325
~CGMatchingAreas()4326 CGBNFRuntimeEnvironment::CGMatchingAreas::~CGMatchingAreas() {
4327 for (std::list<CGMatchingAreas*>::iterator i = childs.begin(); i != childs.end(); ++i) {
4328 delete *i;
4329 }
4330 }
4331
purgeChildsAfterPosition(int iPosition)4332 void CGBNFRuntimeEnvironment::CGMatchingAreas::purgeChildsAfterPosition(int iPosition) {
4333 while (!childs.empty() && (childs.back()->endPosition > iPosition)) {
4334 delete childs.back();
4335 childs.pop_back();
4336 }
4337 }
4338
~CGBNFRuntimeEnvironment()4339 CGBNFRuntimeEnvironment::~CGBNFRuntimeEnvironment() {
4340 delete _pMatchingAreas;
4341 }
4342
pushIgnoreMode(CGBNFRuntimeIgnore & ignoreMode,int iNewIgnoreMode,EXECUTE_CLAUSE * newExecuteClause)4343 void CGBNFRuntimeEnvironment::pushIgnoreMode(CGBNFRuntimeIgnore& ignoreMode, int iNewIgnoreMode, EXECUTE_CLAUSE* newExecuteClause) {
4344 ignoreMode._executeClause = _executeClause;
4345 ignoreMode._iIgnoreMode = _iIgnoreMode;
4346 _iIgnoreMode = iNewIgnoreMode;
4347 _executeClause = newExecuteClause;
4348 }
4349
popIgnoreMode(const CGBNFRuntimeIgnore & ignoreMode)4350 void CGBNFRuntimeEnvironment::popIgnoreMode(const CGBNFRuntimeIgnore& ignoreMode) {
4351 _executeClause = ignoreMode._executeClause;
4352 _iIgnoreMode = ignoreMode._iIgnoreMode;
4353 }
4354
pushImplicitCopy(CGBNFRuntimeTransformationMode & transformationMode,bool bNewImplicitCopy)4355 void CGBNFRuntimeEnvironment::pushImplicitCopy(CGBNFRuntimeTransformationMode& transformationMode, bool bNewImplicitCopy) {
4356 transformationMode._bImplicitCopy = _bImplicitCopy;
4357 _bImplicitCopy = bNewImplicitCopy;
4358 }
4359
popImplicitCopy(const CGBNFRuntimeTransformationMode & transformationMode)4360 void CGBNFRuntimeEnvironment::popImplicitCopy(const CGBNFRuntimeTransformationMode& transformationMode) {
4361 _bImplicitCopy = transformationMode._bImplicitCopy;
4362 }
4363
activateMatchingAreas()4364 void CGBNFRuntimeEnvironment::activateMatchingAreas() {
4365 _pMatchingAreas = new CGMatchingAreas(NULL, -1);
4366 }
4367
storeClauseMatching(DtaScriptVariable & ruleNames,std::map<int,std::map<int,std::list<CGRuntimeTemporaryMatchingStorage * >>> & mapOfAreas,CGMatchingAreas * pClauseMatching)4368 void CGBNFRuntimeEnvironment::storeClauseMatching(DtaScriptVariable& ruleNames, std::map<int, std::map<int, std::list<CGRuntimeTemporaryMatchingStorage*> > >& mapOfAreas, CGMatchingAreas* pClauseMatching) {
4369 if (pClauseMatching == NULL) return;
4370 int iBegin = pClauseMatching->beginPosition;
4371 int iEnd = pClauseMatching->endPosition;
4372 if (iBegin != iEnd) {
4373 DtaScriptVariable* pClauseNode = ruleNames.getArrayElement(pClauseMatching->clause);
4374 mapOfAreas[iBegin][iEnd].push_back(new CGRuntimeTemporaryMatchingStorage(true, pClauseNode));
4375 for (std::list<CGMatchingAreas*>::iterator i = pClauseMatching->childs.begin(); i != pClauseMatching->childs.end(); ++i) {
4376 storeClauseMatching(ruleNames, mapOfAreas, *i);
4377 }
4378 mapOfAreas[iEnd][iBegin].push_back(new CGRuntimeTemporaryMatchingStorage(false, pClauseNode));
4379 }
4380 }
4381
storeMatchingAreas(CppParsingTree_var & pStorage)4382 void CGBNFRuntimeEnvironment::storeMatchingAreas(CppParsingTree_var& pStorage) {
4383 DtaScriptVariable* pAreas = pStorage.insertNode("areas").getInternalNode();
4384 DtaScriptVariable* pRules = pStorage.insertNode("rules").getInternalNode();
4385 for (std::list<std::string>::iterator i = _clauseSignatures.begin(); i != _clauseSignatures.end(); ++i) {
4386 DtaScriptVariable* pClauseNode = pRules->addElement(*i);
4387 pClauseNode->setValue(i->c_str());
4388 }
4389 std::map<int, std::map<int, std::list<CGRuntimeTemporaryMatchingStorage*> > > mapOfAreas;
4390 if ((_pMatchingAreas != NULL) && !_pMatchingAreas->childs.empty()) storeClauseMatching(*pRules, mapOfAreas, _pMatchingAreas->childs.front());
4391 {
4392 for (std::map<int, std::map<int, std::list<CGRuntimeTemporaryMatchingStorage*> > >::iterator i = mapOfAreas.begin(); i != mapOfAreas.end(); ++i) {
4393 DtaScriptVariable* pPosition = pAreas->addElement(i->first);
4394 for (std::map<int, std::list<CGRuntimeTemporaryMatchingStorage*> >::reverse_iterator j = i->second.rbegin(); j != i->second.rend(); ++j) {
4395 {
4396 for (std::list<CGRuntimeTemporaryMatchingStorage*>::iterator k = j->second.begin(); k != j->second.end(); ++k) {
4397 if ((*k)->bBegin) {
4398 pPosition->insertNode("begin")->addElement(j->first)->pushItem("")->setValue((*k)->pClauseNode);
4399 }
4400 }
4401 }
4402 {
4403 for (std::list<CGRuntimeTemporaryMatchingStorage*>::iterator k = j->second.begin(); k != j->second.end(); ++k) {
4404 if (!(*k)->bBegin) {
4405 pPosition->insertNode("end")->addElement(j->first)->pushItem("")->setValue((*k)->pClauseNode);
4406 }
4407 }
4408 }
4409 {
4410 // delete the temporary storage
4411 for (std::list<CGRuntimeTemporaryMatchingStorage*>::iterator k = j->second.begin(); k != j->second.end(); ++k) {
4412 delete *k;
4413 }
4414 }
4415 }
4416 }
4417 }
4418 }
4419
skipEmptyChars()4420 int CGBNFRuntimeEnvironment::skipEmptyChars() {
4421 int iImplicitCopyPosition;
4422 int iLocation;
4423 if (_bImplicitCopy) {
4424 iImplicitCopyPosition = CGRuntime::getOutputLocation();
4425 iLocation = CGRuntime::getInputLocation();
4426 } else {
4427 iImplicitCopyPosition = -1;
4428 }
4429 if ((_iIgnoreMode != (int) NOT_IGNORE) && (_iIgnoreMode != (int) UNDEFINED_IGNORE)) {
4430 bool bCopyImplicitly = _bImplicitCopy;
4431 switch(_iIgnoreMode) {
4432 case IGNORE_CPP:
4433 case IGNORE_JAVA:
4434 CGRuntime::_pInputStream->skipEmpty();
4435 break;
4436 case IGNORE_HTML:
4437 CGRuntime::_pInputStream->skipEmptyHTML();
4438 break;
4439 case IGNORE_BLANKS:
4440 CGRuntime::_pInputStream->skipBlanks();
4441 break;
4442 case IGNORE_SPACES:
4443 CGRuntime::_pInputStream->skipSpaces();
4444 break;
4445 case IGNORE_ADA:
4446 CGRuntime::_pInputStream->skipEmptyAda();
4447 break;
4448 case IGNORE_LATEX:
4449 CGRuntime::_pInputStream->skipEmptyLaTeX();
4450 break;
4451 case IGNORE_CPP_EXCEPT_DOXYGEN:
4452 CGRuntime::_pInputStream->skipEmptyCppExceptDoxygen();
4453 break;
4454 case IGNORE_CLAUSE:
4455 bCopyImplicitly = false;
4456 if (_executeClause != NULL) {
4457 CGBNFRuntimeEnvironment theEnvironment(NULL, NOT_IGNORE, _bImplicitCopy);
4458 _executeClause->run(theEnvironment);
4459 }
4460 break;
4461 default:
4462 throw UtlException("internal error in CGBNFRuntimeEnvironment::skipEmptyChars(): unrecognized ignore mode encountered");
4463 }
4464 if (bCopyImplicitly) {
4465 int iLastLocation = CGRuntime::getInputLocation();
4466 if (iLastLocation > iLocation) {
4467 std::string sText = CGRuntime::getLastReadChars(iLastLocation - iLocation);
4468 CGRuntime::writeBinaryData(sText.c_str(), sText.size());
4469 }
4470 }
4471 }
4472 return iImplicitCopyPosition;
4473 }
4474
writeBinaryData(const char * tcText,int iLength)4475 void CGBNFRuntimeEnvironment::writeBinaryData(const char* tcText, int iLength) {
4476 CGRuntime::writeBinaryData(tcText, iLength);
4477 }
4478
4479
CGBNFRuntimeClauseMatchingAreaValidator(const char * tcClause,CGBNFRuntimeEnvironment * pBNFScript)4480 CGBNFRuntimeClauseMatchingAreaValidator::CGBNFRuntimeClauseMatchingAreaValidator(const char* tcClause, CGBNFRuntimeEnvironment* pBNFScript) {
4481 if (pBNFScript->_pMatchingAreas == NULL) {
4482 pBNFScript_ = NULL;
4483 } else {
4484 pBNFScript_ = pBNFScript;
4485 pOld_ = pBNFScript->_pMatchingAreas;
4486 pBNFScript->_pMatchingAreas = new CGBNFRuntimeEnvironment::CGMatchingAreas(tcClause, CGRuntime::getInputLocation());
4487 }
4488 }
4489
~CGBNFRuntimeClauseMatchingAreaValidator()4490 CGBNFRuntimeClauseMatchingAreaValidator::~CGBNFRuntimeClauseMatchingAreaValidator() {
4491 if (pBNFScript_ != NULL) {
4492 if (pBNFScript_->_pMatchingAreas->endPosition < 0) {
4493 // the clause has failed!
4494 delete pBNFScript_->_pMatchingAreas;
4495 }
4496 pBNFScript_->_pMatchingAreas = pOld_;
4497 }
4498 }
4499
validate()4500 void CGBNFRuntimeClauseMatchingAreaValidator::validate() {
4501 if (pBNFScript_ != NULL) {
4502 CGBNFRuntimeEnvironment::CGMatchingAreas* pNew = pBNFScript_->_pMatchingAreas;
4503 if (pNew->endPosition < 0) {
4504 // prevents aginst multiple call to 'validate()' (shouldn't)
4505 pNew->endPosition = CGRuntime::getInputLocation();
4506 pOld_->pushChild(pNew);
4507 }
4508 }
4509 }
4510
purgeChildsAfterPosition(int iLocation)4511 void CGBNFRuntimeClauseMatchingAreaValidator::purgeChildsAfterPosition(int iLocation) {
4512 if (pBNFScript_ != NULL) {
4513 pBNFScript_->_pMatchingAreas->purgeChildsAfterPosition(iLocation);
4514 }
4515 }
4516
4517
CGBNFRuntimeResizeInput(int iFinalLocation)4518 CGBNFRuntimeResizeInput::CGBNFRuntimeResizeInput(int iFinalLocation) {
4519 _pSizeAttributes = new ScpStream::SizeAttributes(CGRuntime::_pInputStream->resize(iFinalLocation));
4520 }
4521
~CGBNFRuntimeResizeInput()4522 CGBNFRuntimeResizeInput::~CGBNFRuntimeResizeInput() {
4523 ScpStream::SizeAttributes* pSizeAttributes = (ScpStream::SizeAttributes*) _pSizeAttributes;
4524 CGRuntime::_pInputStream->restoreSize(*pSizeAttributes);
4525 delete pSizeAttributes;
4526 }
4527
4528
~CGJointPointStack()4529 CGJointPointStack::~CGJointPointStack() {
4530 CGRuntime::_pJointPoint = _pOldJointPoint;
4531 }
4532
4533
~CGBNFClauseScope()4534 CGBNFClauseScope::~CGBNFClauseScope() {
4535 if (_pLocalVariables != NULL) delete _pLocalVariables;
4536 }
4537
getNode(const std::string & sName) const4538 CppParsingTree_var CGBNFClauseScope::getNode(const std::string& sName) const {
4539 if (_pLocalVariables != NULL) {
4540 CppParsingTree_var theNode = _pLocalVariables->getNode(sName.c_str());
4541 if (!theNode.isNull()) return theNode;
4542 }
4543 return CGRuntime::getThisTree().getNode(sName);
4544 }
4545
getEvaluatedNode(const std::string & sDynamicVariable) const4546 CppParsingTree_var CGBNFClauseScope::getEvaluatedNode(const std::string& sDynamicVariable) const {
4547 if (_pLocalVariables != NULL) {
4548 CppParsingTree_var theNode = _pLocalVariables->getEvaluatedNode(sDynamicVariable);
4549 if (!theNode.isNull()) return theNode;
4550 }
4551 return CGRuntime::getThisTree().getEvaluatedNode(sDynamicVariable);
4552 }
4553
insertNode(const std::string & sName)4554 CppParsingTree_var CGBNFClauseScope::insertNode(const std::string& sName) {
4555 if (_pLocalVariables != NULL) {
4556 DtaScriptVariable* pNode = _pLocalVariables->getNode(sName.c_str());
4557 if (pNode != NULL) return pNode;
4558 } else {
4559 _pLocalVariables = new DtaScriptVariable;
4560 }
4561 return _pLocalVariables->insertNode(sName.c_str());
4562 }
4563
insertClassicalNode(const std::string & sName)4564 CppParsingTree_var CGBNFClauseScope::insertClassicalNode(const std::string& sName) {
4565 if (_pLocalVariables != NULL) {
4566 DtaScriptVariable* pNode = _pLocalVariables->getNode(sName.c_str());
4567 if (pNode != NULL) return pNode;
4568 }
4569 return CGRuntime::getThisTree().insertNode(sName);
4570 }
4571
insertEvaluatedNode(const std::string & sDynamicVariable)4572 CppParsingTree_var CGBNFClauseScope::insertEvaluatedNode(const std::string& sDynamicVariable) {
4573 if (_pLocalVariables == NULL) _pLocalVariables = new DtaScriptVariable;
4574 return _pLocalVariables->insertEvaluatedNode(sDynamicVariable);
4575 }
4576
insertClassicalEvaluatedNode(const std::string & sDynamicVariable)4577 CppParsingTree_var CGBNFClauseScope::insertClassicalEvaluatedNode(const std::string& sDynamicVariable) {
4578 if (_pLocalVariables == NULL) _pLocalVariables = new DtaScriptVariable;
4579 return _pLocalVariables->insertClassicalEvaluatedNode(sDynamicVariable);
4580 }
4581
getOrCreateLocalNode(const std::string & sName)4582 CppParsingTree_var CGBNFClauseScope::getOrCreateLocalNode(const std::string& sName) {
4583 if (_pLocalVariables != NULL) {
4584 DtaScriptVariable* pNode = _pLocalVariables->getNode(sName.c_str());
4585 if (pNode != NULL) return pNode;
4586 }
4587 CppParsingTree_var theNode = CGRuntime::getThisTree().getNode(sName);
4588 if (theNode.isNull()) {
4589 if (_pLocalVariables == NULL) _pLocalVariables = new DtaScriptVariable(NULL, "##stack## clause");
4590 theNode = _pLocalVariables->insertNode(sName.c_str());
4591 }
4592 return theNode;
4593 }
4594 }
4595