hqlparse.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "hqlgram.hpp"
  14. #include "hqlfold.hpp"
  15. #include "jiter.ipp"
  16. #include "jptree.hpp"
  17. #include "hqlerrors.hpp"
  18. #include "hqlthql.hpp"
  19. #include "hqlexpr.hpp"
  20. #include "jdebug.hpp"
  21. #include "hqlexpr.ipp"
  22. #include "hqlgram.h"
  23. #define YY_NO_UNISTD_H
  24. #include "hqllex.hpp"
  25. //#define TIMING_DEBUG
  26. #define MAX_LOOP_TIMES 250000
  27. // =========================== local helper functions ===================================
  28. static bool isInModule(HqlLookupContext & ctx, const char* module_name, const char* attr_name);
  29. static StringBuffer& mangle(IErrorReceiver* errReceiver,const char* src, StringBuffer& mangled,bool demangle);
  30. // =========================== CDummyScopeIterator ======================================
  31. class CDummyScopeIterator : public IIterator, public CInterface
  32. {
  33. IXmlScope *parent;
  34. public:
  35. IMPLEMENT_IINTERFACE;
  36. CDummyScopeIterator(IXmlScope *_parent)
  37. {
  38. parent = _parent;
  39. }
  40. ~CDummyScopeIterator ()
  41. {
  42. }
  43. virtual bool first()
  44. {
  45. return true;
  46. };
  47. virtual bool next()
  48. {
  49. return true;
  50. }
  51. virtual bool isValid()
  52. {
  53. return true;
  54. }
  55. virtual IInterface & query()
  56. {
  57. return *parent;
  58. }
  59. virtual IInterface & get()
  60. {
  61. IInterface &ret = query(); ret.Link(); return ret;
  62. }
  63. };
  64. // =========================== CTemplateContext =========================================
  65. class CTemplateContext : implements ITemplateContext, public CInterface
  66. {
  67. HqlLex * lexer;
  68. IXmlScope* m_xmlScope;
  69. int m_startLine,m_startCol;
  70. HqlLookupContext & m_lookupContext;
  71. public:
  72. IMPLEMENT_IINTERFACE;
  73. CTemplateContext(HqlLex * _lexer, HqlLookupContext & lookupContext, IXmlScope* xmlScope, int startLine,int startCol)
  74. : lexer(_lexer), m_xmlScope(xmlScope), m_lookupContext(lookupContext),
  75. m_startLine(startLine), m_startCol(startCol) {}
  76. virtual IXmlScope* queryXmlScope() { return m_xmlScope; }
  77. virtual IEclRepository* queryDataServer() { return m_lookupContext.queryRepository(); }
  78. // convenient functions
  79. virtual bool isInModule(const char* moduleName, const char* attrName) { return ::isInModule(m_lookupContext, moduleName,attrName); }
  80. virtual StringBuffer& getDataType(const char* field, StringBuffer& tgt) { return lexer->doGetDataType(tgt, field, m_startLine, m_startCol); }
  81. virtual StringBuffer& mangle(const char* src, StringBuffer& mangled) { return ::mangle(m_lookupContext.errs,src,mangled,false); }
  82. virtual StringBuffer& demangle(const char* mangled, StringBuffer& demangled) { return ::mangle(m_lookupContext.errs,mangled,demangled,true); }
  83. virtual void reportError(int errNo,const char* format,...);
  84. virtual void reportWarning(int warnNo,const char* format,...);
  85. };
  86. void CTemplateContext::reportError(int errNo,const char* format,...)
  87. {
  88. if (m_lookupContext.errs)
  89. {
  90. va_list args;
  91. va_start(args, format);
  92. StringBuffer msg;
  93. msg.valist_appendf(format,args);
  94. m_lookupContext.errs->reportError(errNo,msg.str(),NULL,m_startLine,m_startCol,0);
  95. va_end(args);
  96. }
  97. }
  98. void CTemplateContext::reportWarning(int warnNo,const char* format,...)
  99. {
  100. if (m_lookupContext.errs)
  101. {
  102. va_list args;
  103. va_start(args, format);
  104. StringBuffer msg;
  105. msg.valist_appendf(format,args);
  106. WarnErrorCategory category = CategoryUnusual; // a reasonable default
  107. m_lookupContext.errs->reportWarning(category, warnNo,msg.str(),NULL,m_startLine,m_startCol,0);
  108. va_end(args);
  109. }
  110. }
  111. // ===================================== HqlLex ============================================
  112. class CHqlParserPseduoScope : public CHqlScope
  113. {
  114. protected:
  115. HqlGram * parser;
  116. public:
  117. CHqlParserPseduoScope(HqlGram * _parser) : CHqlScope(no_privatescope) { parser = _parser; }
  118. virtual IHqlExpression *lookupSymbol(IIdAtom * name, unsigned lookupFlags, HqlLookupContext & ctx)
  119. {
  120. attribute errpos;
  121. errpos.clearPosition();
  122. return parser->lookupSymbol(name, errpos);
  123. }
  124. virtual IHqlScope * queryConcreteScope() { return this; }
  125. virtual bool allBasesFullyBound() const { return true; }
  126. };
  127. // ===================================== HqlLex ============================================
  128. HqlLex::HqlLex(HqlGram *parser, IFileContents * contents, IXmlScope *_xmlScope, IHqlExpression *_macroExpr)
  129. : yyParser(parser), xmlScope(LINK(_xmlScope)), macroExpr(_macroExpr), sourcePath(contents->querySourcePath())
  130. {
  131. assertex(parser);
  132. init(contents);
  133. }
  134. void HqlLex::init(IFileContents * _text)
  135. {
  136. text.set(_text);
  137. inmacro = NULL;
  138. parentLex = NULL;
  139. inComment = false;
  140. inCpp = false;
  141. hasHashbreak = false;
  142. encrypted = false;
  143. loopTimes = 0;
  144. skipNesting = 0;
  145. macroGathering = 0;
  146. forLoop = NULL;
  147. size32_t len = _text->length();
  148. yyBuffer = new char[len+2]; // Include room for \0 and another \0 that we write beyond the end null while parsing
  149. memcpy(yyBuffer, text->getText(), len);
  150. yyBuffer[len] = '\0';
  151. yyBuffer[len+1] = '\0';
  152. yyLineNo = 1;
  153. yyPosition = 0;
  154. yyColumn = 1;
  155. yyStartPos = 0;
  156. lastToken = 0;
  157. eclyylex_init(&scanner);
  158. eclyy_scan_buffer(yyBuffer, len+2, scanner);
  159. }
  160. ///////////////////////////////////////////////////
  161. // public destructor
  162. //
  163. HqlLex::~HqlLex()
  164. {
  165. eclyylex_destroy(scanner);
  166. scanner = NULL;
  167. delete[] yyBuffer;
  168. ::Release(xmlScope);
  169. ::Release(macroExpr);
  170. if (inmacro) delete inmacro;
  171. ::Release(forLoop);
  172. }
  173. char* HqlLex::get_yyText(void)
  174. {
  175. if (inmacro)
  176. return inmacro->get_yyText();
  177. return eclyyget_text(scanner);
  178. }
  179. IFileContents* HqlLex::query_FileContents(void)
  180. {
  181. if (inmacro)
  182. return inmacro->query_FileContents();
  183. return text;
  184. }
  185. bool HqlLex::isMacroActive(IHqlExpression *expr)
  186. {
  187. if (expr==macroExpr)
  188. return true;
  189. else if (parentLex)
  190. return parentLex->isMacroActive(expr);
  191. else
  192. return false;
  193. }
  194. bool HqlLex::assertNext(YYSTYPE & returnToken, int expected, unsigned code, const char * msg)
  195. {
  196. if (yyLex(returnToken, false,0) != expected)
  197. {
  198. reportError(returnToken, code, "%s", msg);
  199. returnToken.release();
  200. return false;
  201. }
  202. return true;
  203. }
  204. bool HqlLex::assertNextOpenBra()
  205. {
  206. YYSTYPE tempToken;
  207. return assertNext(tempToken, '(', ERR_EXPECTED_LEFTCURLY, "( expected");
  208. }
  209. bool HqlLex::assertNextComma()
  210. {
  211. YYSTYPE tempToken;
  212. return assertNext(tempToken, ',', ERR_EXPECTED_COMMA, ", expected");
  213. }
  214. StringBuffer &HqlLex::getTokenText(StringBuffer &ret)
  215. {
  216. if (inmacro)
  217. return inmacro->getTokenText(ret);
  218. return ret.append(yyPosition - yyStartPos, yyBuffer+yyStartPos);
  219. }
  220. IHqlExpression *HqlLex::lookupSymbol(IIdAtom * name, const attribute& errpos)
  221. {
  222. return yyParser->lookupSymbol(name, errpos);
  223. }
  224. unsigned HqlLex::hex2digit(char c)
  225. {
  226. if (c >= 'a')
  227. return (c - 'a' + 10);
  228. else if (c >= 'A')
  229. return (c - 'A' + 10);
  230. return (c - '0');
  231. }
  232. __int64 HqlLex::str2int64(unsigned len, const char * digits, unsigned base)
  233. {
  234. __int64 value = 0;
  235. while (len--)
  236. {
  237. char c = *digits++;
  238. value = value * base + hex2digit(c);
  239. }
  240. return value;
  241. }
  242. void HqlLex::hex2str(char * target, const char * digits, unsigned len)
  243. {
  244. while (len)
  245. {
  246. *target++ = (hex2digit(digits[0]) << 4) | hex2digit(digits[1]);
  247. len -= 2;
  248. digits += 2;
  249. }
  250. }
  251. IHqlExpression * HqlLex::createIntegerConstant(__int64 value, bool isSigned)
  252. {
  253. return createConstant(createIntValue(value, makeIntType(8, isSigned)));
  254. }
  255. void HqlLex::pushText(IFileContents * text, int startLineNo, int startColumn)
  256. {
  257. #ifdef TIMING_DEBUG
  258. MTIME_SECTION(timer, "HqlLex::pushText");
  259. #endif
  260. inmacro = new HqlLex(yyParser, text, NULL, NULL);
  261. inmacro->set_yyLineNo(startLineNo);
  262. inmacro->set_yyColumn(startColumn);
  263. }
  264. void HqlLex::pushText(const char *s, int startLineNo, int startColumn)
  265. {
  266. Owned<IFileContents> macroContents = createFileContentsFromText(s, sourcePath);
  267. pushText(macroContents, startLineNo, startColumn);
  268. }
  269. void HqlLex::pushText(const char *s)
  270. {
  271. #ifdef TIMING_DEBUG
  272. MTIME_SECTION(timer, "HqlLex::pushText");
  273. #endif
  274. Owned<IFileContents> macroContents = createFileContentsFromText(s, sourcePath);
  275. inmacro = new HqlLex(yyParser, macroContents, NULL, NULL);
  276. inmacro->set_yyLineNo(yyLineNo);
  277. inmacro->set_yyColumn(yyColumn);
  278. #if defined (TRACE_MACRO)
  279. PrintLog("MACRO>> inmacro %p created for \"%s\" for macro parameters.\n",inmacro,s);
  280. #endif
  281. }
  282. void HqlLex::setMacroParam(const YYSTYPE & errpos, IHqlExpression* funcdef, StringBuffer& curParam, IIdAtom * argumentId, unsigned& parmno,IProperties *macroParms)
  283. {
  284. IHqlExpression * formals = queryFunctionParameters(funcdef);
  285. IHqlExpression * defaults = queryFunctionDefaults(funcdef);
  286. unsigned numFormals = formals->numChildren();
  287. unsigned thisParam = (unsigned)-1;
  288. if (argumentId)
  289. {
  290. IAtom * argumentName = argumentId->lower();
  291. unsigned argNum = 0;
  292. for (unsigned i=0; i < numFormals; i++)
  293. {
  294. if (formals->queryChild(i)->queryName() == argumentName)
  295. {
  296. argNum = i+1;
  297. break;
  298. }
  299. }
  300. if (argNum == 0)
  301. reportError(errpos, ERR_NAMED_PARAM_NOT_FOUND, "Named parameter '%s' not found in macro", argumentId->str());
  302. else
  303. thisParam = argNum;
  304. }
  305. else
  306. thisParam = ++parmno;
  307. if (thisParam <= numFormals)
  308. {
  309. IHqlExpression* formal = formals->queryChild(thisParam-1);
  310. if (curParam.length()==0)
  311. {
  312. IHqlExpression* def = queryDefaultValue(defaults, thisParam-1);
  313. if (!def)
  314. {
  315. StringBuffer msg("Omitted parameter ");
  316. msg.append(parmno).append(" has no default value");
  317. reportError(errpos, ERR_PARAM_NODEFVALUE, "%s", msg.str());
  318. }
  319. else
  320. {
  321. if (!getFoldedConstantText(curParam, def))
  322. {
  323. StringBuffer msg("Default value for parameter ");
  324. msg.append(parmno).append(" should be a constant");
  325. reportError(errpos, ERR_PARAM_NODEFVALUE, "%s", msg.str());
  326. }
  327. }
  328. }
  329. //PrintLog("Set macro parm: %s", curParam.str());
  330. // if (macroParms->queryProp(formal->queryName()))
  331. // reportError(errpos, ERR_NAMED_ALREADY_HAS_VALUE, "Parameter %s already has a value supplied", argumentName->str());
  332. // else
  333. macroParms->setProp(formal->queryName()->str(), curParam.str());
  334. }
  335. curParam.clear();
  336. }
  337. /* This is pushing a macro definition. */
  338. void HqlLex::pushMacro(IHqlExpression *expr)
  339. {
  340. /* expr points to namedSymbol(no_funcdef):
  341. child(0)-> no_macro = macro body
  342. child(1) = parameters
  343. child(2) = defaults for parameters
  344. */
  345. YYSTYPE nextToken;
  346. int tok = yyLex(nextToken, false, 0);
  347. if (tok != '(')
  348. {
  349. //throw MakeStringException(2, "( expected");
  350. reportError(nextToken, ERR_EXPECTED_LEFTCURLY, "( expected");
  351. if (tok==EOF)
  352. return;
  353. // assume we've got an '(', we can continue parsing.
  354. }
  355. unsigned parenDepth = 1;
  356. StringBuffer curParam;
  357. Owned<IProperties> macroParms = createProperties();
  358. IHqlExpression * formals = expr->queryChild(1);
  359. IHqlExpression * defaults = expr->queryChild(2);
  360. unsigned formalParmCt = formals->numChildren();
  361. unsigned parmno = 0;
  362. IIdAtom * possibleName = NULL;
  363. IIdAtom * argumentName = NULL;
  364. while (parenDepth)
  365. {
  366. tok = yyLex(nextToken, false, 0);
  367. switch(tok)
  368. {
  369. case '[':
  370. case '(':
  371. parenDepth++;
  372. curParam.append((char)tok);
  373. break;
  374. case ']':
  375. if (parenDepth > 1)
  376. parenDepth--;
  377. curParam.append((char)tok);
  378. break;
  379. case ')':
  380. parenDepth--;
  381. if (parenDepth)
  382. curParam.append(')');
  383. else if (formalParmCt>0 || curParam.length()>0) // handle last parameter
  384. setMacroParam(nextToken, expr, curParam, argumentName, parmno, macroParms);
  385. break;
  386. case ',':
  387. if (parenDepth==1)
  388. setMacroParam(nextToken, expr, curParam, argumentName, parmno, macroParms);
  389. else
  390. curParam.append(',');
  391. possibleName = NULL;
  392. argumentName = NULL;
  393. break;
  394. case ASSIGN:
  395. {
  396. bool done = false;
  397. if (parenDepth == 1 && possibleName)
  398. {
  399. //Horrible. Allow NAMED <id> := or <id> :=
  400. const char * text = curParam.str();
  401. while (isspace((byte)*text)) text++;
  402. if (memicmp(text, "NAMED", 5) == 0)
  403. text += 5;
  404. while (isspace((byte)*text)) text++;
  405. if (strlen(possibleName->str()) == strlen(text))
  406. {
  407. argumentName = possibleName;
  408. possibleName = NULL;
  409. curParam.clear();
  410. done = true;
  411. }
  412. }
  413. if (!done)
  414. getTokenText(curParam.append(' '));
  415. break;
  416. }
  417. case EOF:
  418. reportError(nextToken, ERR_MACRO_EOFINPARAM,"EOF encountered while gathering macro parameters");
  419. // no attempt to recover at the end of the file, but cleanup is needed.
  420. return;
  421. case UNKNOWN_ID:
  422. possibleName = nextToken.getId();
  423. //fall through
  424. default:
  425. curParam.append(' ');
  426. getTokenText(curParam);
  427. break;
  428. }
  429. nextToken.release();
  430. }
  431. if (parmno > formalParmCt)
  432. {
  433. StringBuffer msg("Too many actual parameters supplied to macro");
  434. if (expr->queryName())
  435. msg.append(' ').append(expr->queryName());
  436. msg.appendf(": expected %d, given %d", formalParmCt, parmno);
  437. reportError(nextToken, ERR_PARAM_TOOMANY, "%s", msg.str());
  438. }
  439. else if (parmno < formalParmCt)
  440. {
  441. for (unsigned idx = parmno; idx < formalParmCt; idx++)
  442. {
  443. IHqlExpression* formal = formals->queryChild(idx);
  444. if (!macroParms->queryProp(formal->queryName()->str()))
  445. {
  446. IHqlExpression* def = queryDefaultValue(defaults, idx);
  447. if (def)
  448. {
  449. if (!getFoldedConstantText(curParam, def))
  450. {
  451. StringBuffer msg("Omitted parameter ");
  452. msg.append(idx+1);
  453. if (expr->queryName())
  454. msg.append(" to macro ").append(expr->queryName());
  455. msg.append(" should be a constant value");
  456. reportError(nextToken, ERR_PARAM_NODEFVALUE, "%s", msg.str());
  457. }
  458. macroParms->setProp(formal->queryName()->str(), curParam.str());
  459. //PrintLog("Set macro parm: %s", curParam.str());
  460. curParam.clear();
  461. }
  462. else
  463. {
  464. StringBuffer msg("Omitted parameter ");
  465. msg.append(idx+1);
  466. if (expr->queryName())
  467. msg.append(" to macro ").append(expr->queryName());
  468. msg.append(" has no default value");
  469. reportError(nextToken, ERR_PARAM_NODEFVALUE, "%s", msg.str());
  470. }
  471. }
  472. }
  473. }
  474. IHqlExpression *macroBodyExpr = expr->queryChild(0);
  475. IFileContents * macroContents = static_cast<IFileContents *>(macroBodyExpr->queryUnknownExtra());
  476. if (isMacroActive(expr))
  477. {
  478. StringBuffer msg;
  479. msg.append("recursive macro call: ").append(getMacroName());
  480. reportError(nextToken, ERR_MACRO_RECURSIVE, "%s", msg.str());
  481. // error recovery
  482. if (expr->isAction())
  483. pushText("0;");
  484. else if (expr->isDataset())
  485. pushText("{}");
  486. else
  487. pushText("0 ENDMACRO");
  488. }
  489. else
  490. {
  491. inmacro = new HqlLex(yyParser, macroContents, NULL, LINK(expr));
  492. #if defined(TRACE_MACRO)
  493. PrintLog("MACRO>> inmacro %p created for \"%s\" at %d:%d\n",inmacro, s.str(),macroBodyExpr->getStartLine(),macroBodyExpr->getStartColumn());
  494. // PrintLog("MACRO>> macro called at %d:%d\n", expr->getStartLine(),expr->getStartColumn());
  495. #endif
  496. /* set the lineno and column in the original source as the starting point */
  497. inmacro->yyLineNo = macroBodyExpr->getStartLine();
  498. inmacro->yyColumn = macroBodyExpr->getStartColumn();
  499. inmacro->setParentLex(this);
  500. inmacro->macroParms.setown(macroParms.getClear());
  501. }
  502. }
  503. /* Read encrypted syntax, and push the decrypted text as a macro. */
  504. void HqlLex::processEncrypted()
  505. {
  506. YYSTYPE nextToken;
  507. if (yyLex(nextToken, false,0) != '(')
  508. {
  509. reportError(nextToken, ERR_EXPECTED_LEFTCURLY, "( expected");
  510. nextToken.release();
  511. return;
  512. }
  513. StringBuffer encoded64;
  514. loop
  515. {
  516. if (yyLex(nextToken, false,0) != STRING_CONST)
  517. {
  518. reportError(nextToken, ERR_EXPECTED, "String expected");
  519. nextToken.release();
  520. return;
  521. }
  522. OwnedHqlExpr str = nextToken.getExpr();
  523. getStringValue(encoded64, str);
  524. int next = yyLex(nextToken, false,0);
  525. if (next == ')')
  526. break;
  527. if (next != ',')
  528. {
  529. reportError(nextToken, ERR_EXPECTED_COMMA, ", expected");
  530. nextToken.release();
  531. return;
  532. }
  533. }
  534. if (yyLex(nextToken, false,0) != ';')
  535. {
  536. reportError(nextToken, ERR_EXPECTED, "; expected");
  537. nextToken.release();
  538. return;
  539. }
  540. MemoryBuffer decrypted;
  541. decryptEclAttribute(decrypted, encoded64.str());
  542. decrypted.append(0); // add a null terminator to the string...
  543. Owned<ISourcePath> sourcePath = createSourcePath("<encrypted>");
  544. Owned<IFileContents> decryptedContents = createFileContentsFromText((const char *)decrypted.toByteArray(), sourcePath);
  545. inmacro = new HqlLex(yyParser, decryptedContents, NULL, NULL);
  546. inmacro->setParentLex(this);
  547. inmacro->encrypted = true;
  548. }
  549. /* Return: true if more parameter(s) left. */
  550. bool HqlLex::getParameter(StringBuffer &curParam, const char* for_what, int* startLine, int* startCol)
  551. {
  552. unsigned parenDepth = 1;
  553. if (startLine) *startLine = -1;
  554. YYSTYPE nextToken;
  555. for (;;)
  556. {
  557. int tok = yyLex(nextToken, false, 0);
  558. if (startLine && *startLine == -1)
  559. {
  560. *startLine = nextToken.pos.lineno;
  561. *startCol = nextToken.pos.column;
  562. }
  563. switch(tok)
  564. {
  565. case '(':
  566. case '[':
  567. parenDepth++;
  568. curParam.append((char) tok);
  569. break;
  570. case ')':
  571. if (parenDepth==1)
  572. return false;
  573. // fall into
  574. case ']':
  575. parenDepth--;
  576. curParam.append((char) tok);
  577. break;
  578. case ',':
  579. if (parenDepth==1)
  580. return true;
  581. curParam.append(',');
  582. break;
  583. case EOF:
  584. {
  585. StringBuffer msg("EOF encountered while gathering parameters for ");
  586. msg.append(for_what);
  587. reportError(nextToken, ERR_TMPLT_EOFINPARAM, "%s", msg.str());
  588. }
  589. return false;
  590. default:
  591. curParam.append(' ');
  592. getTokenText(curParam);
  593. break;
  594. }
  595. nextToken.release();
  596. }
  597. }
  598. void HqlLex::doSkipUntilEnd(YYSTYPE & returnToken, const char * forwhat)
  599. {
  600. while (skipNesting)
  601. {
  602. int tok = yyLex(returnToken, false,0);
  603. returnToken.release();
  604. if (tok == EOF)
  605. {
  606. StringBuffer msg;
  607. msg.appendf("Unexpected EOF in %s: #END expected",forwhat);
  608. reportError(returnToken, ERR_TMPLT_HASHENDEXPECTED, "%s", msg.str());
  609. clearNestedHash(); // prevent unnecessary more error messages
  610. break;
  611. }
  612. }
  613. }
  614. void HqlLex::doIf(YYSTYPE & returnToken, bool isElseIf)
  615. {
  616. StringBuffer forwhat;
  617. int line = returnToken.pos.lineno, col = returnToken.pos.column;
  618. forwhat.appendf("#IF(%d,%d)",returnToken.pos.lineno,returnToken.pos.column);
  619. int tok = yyLex(returnToken, false, 0);
  620. if (tok != '(')
  621. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected"); // MORE - make it fatal!
  622. StringBuffer curParam("(");
  623. if (getParameter(curParam, forwhat.str()))
  624. {
  625. reportError(returnToken, ERR_OPERANDS_TOOMANY, "too many operands");
  626. StringBuffer dummy;
  627. while (getParameter(dummy,forwhat.str()))
  628. ;
  629. }
  630. curParam.append(')');
  631. Owned<IValue> value = parseConstExpression(returnToken, curParam, queryTopXmlScope(),line,col);
  632. if (value && !value->getBoolValue())
  633. {
  634. setHashEndFlags(0);
  635. skipNesting = 1;
  636. if (!isElseIf)
  637. doSkipUntilEnd(returnToken, forwhat);
  638. }
  639. else
  640. setHashEndFlags(HEFhadtrue);
  641. }
  642. int HqlLex::doElse(YYSTYPE & returnToken, bool lookup, const short * activeState, bool isElseIf)
  643. {
  644. StringBuffer forwhat;
  645. forwhat.appendf("#%s(%d,%d)",isElseIf ? "ELSEIF" : "ELSE", returnToken.pos.lineno,returnToken.pos.column);
  646. if ((hashendKinds.ordinality() == 0) || (hashendKinds.tos() != HashStmtIf))
  647. {
  648. reportError(returnToken, ERR_TMPLT_EXTRAELSE,"#ELSE does not match a #IF");
  649. return SKIPPED;
  650. }
  651. unsigned flags = hashendFlags.tos();
  652. if (!isElseIf)
  653. {
  654. if (flags & HEFhadelse)
  655. reportError(returnToken, ERR_TMPLT_EXTRAELSE,"Multiple #ELSE for the same #IF");
  656. setHashEndFlags(flags|HEFhadelse);
  657. }
  658. switch (skipNesting)
  659. {
  660. case 0:
  661. skipNesting = 1;
  662. doSkipUntilEnd(returnToken, forwhat);
  663. return yyLex(returnToken, lookup, activeState);
  664. case 1:
  665. if (flags & HEFhadtrue)
  666. {
  667. //Don't need to do anything
  668. }
  669. else
  670. {
  671. skipNesting = 0;
  672. if (isElseIf)
  673. doIf(returnToken, true);
  674. else
  675. setHashEndFlags(HEFhadtrue|HEFhadelse);
  676. }
  677. return SKIPPED; // looks wrong, but called within a doIf() loop, and first return is ignored
  678. default:
  679. return SKIPPED;
  680. }
  681. }
  682. int HqlLex::doEnd(YYSTYPE & returnToken, bool lookup, const short * activeState)
  683. {
  684. if (hashendKinds.ordinality() != 0)
  685. {
  686. endNestedHash();
  687. if (skipNesting)
  688. {
  689. skipNesting -= 1;
  690. return(HASHEND);
  691. }
  692. }
  693. else
  694. reportError(returnToken, ERR_TMPLT_EXTRAEND,"#END doesn't match a # command");
  695. return yyLex(returnToken, lookup, activeState);
  696. }
  697. void HqlLex::doDeclare(YYSTYPE & returnToken)
  698. {
  699. StringBuffer forwhat;
  700. forwhat.appendf("#DECLARE(%d,%d)",returnToken.pos.lineno,returnToken.pos.column);
  701. IIdAtom * name = NULL;
  702. if (yyLex(returnToken, false,0) != '(')
  703. {
  704. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected");
  705. returnToken.release();
  706. return;
  707. }
  708. for (;;)
  709. {
  710. int tok = yyLex(returnToken, false,0);
  711. if (tok == EOF)
  712. {
  713. StringBuffer msg;
  714. msg.append("Unexpected EOF in ").append(forwhat.str()).append(": ')' expected");
  715. reportError(returnToken, ERR_TMPLT_HASHENDEXPECTED, "%s", msg.str());
  716. clearNestedHash(); // prevent unnecessary more error messages
  717. return;
  718. }
  719. if (tok != UNKNOWN_ID)
  720. {
  721. reportError(returnToken, ERR_EXPECTED_IDENTIFIER, "Identifier expected");
  722. returnToken.release();
  723. continue;
  724. }
  725. name = returnToken.getId();
  726. declareXmlSymbol(returnToken, name->getAtomNamePtr());
  727. tok = yyLex(returnToken, false,0);
  728. if (tok == ')')
  729. break;
  730. else if (tok == ',')
  731. continue;
  732. else if (tok == EOF)
  733. {
  734. StringBuffer msg;
  735. msg.append("Unexpected EOF in ").append(forwhat.str()).append(": ) expected");
  736. reportError(returnToken, ERR_TMPLT_HASHENDEXPECTED, "%s", msg.str());
  737. clearNestedHash(); // prevent unnecessary more error messages
  738. }
  739. else
  740. {
  741. reportError(returnToken, ERR_EXPECTED, "',' or ')' expected");
  742. returnToken.release();
  743. }
  744. }
  745. }
  746. void HqlLex::doExpand(YYSTYPE & returnToken)
  747. {
  748. StringBuffer forwhat;
  749. forwhat.appendf("#DECLARE(%d,%d)",returnToken.pos.lineno,returnToken.pos.column);
  750. if (yyLex(returnToken, false,0) != '(')
  751. {
  752. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected");
  753. returnToken.release();
  754. return;
  755. }
  756. StringBuffer curParam("(");
  757. int startLine, startCol;
  758. if (getParameter(curParam,forwhat.str(),&startLine,&startCol))
  759. {
  760. reportError(returnToken, ERR_OPERANDS_TOOMANY, "Too many operands");
  761. StringBuffer dummy;
  762. while (getParameter(dummy,forwhat.str()))
  763. ;
  764. }
  765. curParam.append(')');
  766. Owned<IValue> value = parseConstExpression(returnToken, curParam, queryTopXmlScope(),startLine-1,startCol);
  767. if (value)
  768. {
  769. StringBuffer buf;
  770. value->getStringValue(buf);
  771. if (buf.length())
  772. pushText(buf.str());
  773. }
  774. }
  775. void HqlLex::doSet(YYSTYPE & returnToken, bool append)
  776. {
  777. StringBuffer forwhat;
  778. forwhat.appendf("%s(%d,%d)",append?"#APPEND":"#SET",returnToken.pos.lineno,returnToken.pos.column);
  779. IIdAtom * name = NULL;
  780. if (yyLex(returnToken, false,0) != '(')
  781. {
  782. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected");
  783. returnToken.release();
  784. return;
  785. }
  786. if (yyLex(returnToken, false,0) != UNKNOWN_ID)
  787. {
  788. reportError(returnToken, ERR_EXPECTED_IDENTIFIER, "Identifier expected");
  789. returnToken.release();
  790. return;
  791. }
  792. name = returnToken.getId();
  793. if (yyLex(returnToken, false,0) != ',')
  794. {
  795. reportError(returnToken, ERR_EXPECTED_COMMA, ", expected");
  796. return;
  797. }
  798. StringBuffer curParam("(");
  799. int startLine, startCol;
  800. if (getParameter(curParam,forwhat.str(),&startLine,&startCol))
  801. {
  802. reportError(returnToken, ERR_OPERANDS_TOOMANY, "Too many operands");
  803. StringBuffer dummy;
  804. while (getParameter(dummy,forwhat.str()))
  805. ;
  806. }
  807. curParam.append(')');
  808. IValue *value = parseConstExpression(returnToken, curParam, queryTopXmlScope(),startLine-1,startCol);
  809. if (value)
  810. {
  811. StringBuffer buf;
  812. value->getStringValue(buf);
  813. setXmlSymbol(returnToken, name->getAtomNamePtr(), buf.str(), append);
  814. value->Release();
  815. }
  816. }
  817. void HqlLex::doLine(YYSTYPE & returnToken)
  818. {
  819. StringBuffer forwhat;
  820. int line = returnToken.pos.lineno, col = returnToken.pos.column;
  821. forwhat.appendf("LINE(%d,%d)",returnToken.pos.lineno,returnToken.pos.column);
  822. IIdAtom * name = NULL;
  823. if (yyLex(returnToken, false,0) != '(')
  824. {
  825. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected");
  826. returnToken.release();
  827. return;
  828. }
  829. StringBuffer curParam("(");
  830. bool moreParams = getParameter(curParam, forwhat.str(), &line, &col);
  831. curParam.append(')');
  832. IValue *value = parseConstExpression(returnToken, curParam, queryTopXmlScope(),line,col);
  833. if (value && value->getTypeCode()==type_int)
  834. {
  835. returnToken.pos.lineno = yyLineNo = (int)value->getIntValue();
  836. }
  837. else
  838. reportError(returnToken, ERR_EXPECTED_CONST, "Constant integer expression expected");
  839. ::Release(value);
  840. if (moreParams)
  841. {
  842. int startLine, startCol;
  843. if (getParameter(curParam,forwhat.str(),&startLine,&startCol))
  844. {
  845. reportError(returnToken, ERR_OPERANDS_TOOMANY, "Too many operands");
  846. StringBuffer dummy;
  847. while (getParameter(dummy,forwhat.str()))
  848. ;
  849. }
  850. curParam.append(')');
  851. IValue *value = parseConstExpression(returnToken, curParam, queryTopXmlScope(),startLine-1,startCol);
  852. if (value && value->getTypeCode()==type_string)
  853. {
  854. StringBuffer buf;
  855. value->getStringValue(buf);
  856. // MORE - set filename here
  857. value->Release();
  858. }
  859. else
  860. reportError(returnToken, ERR_EXPECTED_CONST, "Constant string expression expected");
  861. }
  862. }
  863. void HqlLex::doError(YYSTYPE & returnToken, bool isError)
  864. {
  865. StringBuffer forwhat;
  866. forwhat.appendf("%s(%d,%d)",isError?"#ERROR":"#WARNING",returnToken.pos.lineno,returnToken.pos.column);
  867. IIdAtom * name = NULL;
  868. if (yyLex(returnToken, false,0) != '(')
  869. {
  870. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected");
  871. returnToken.release();
  872. return;
  873. }
  874. StringBuffer curParam("(");
  875. int startLine, startCol;
  876. if (getParameter(curParam,forwhat.str(),&startLine,&startCol))
  877. {
  878. reportError(returnToken, ERR_OPERANDS_TOOMANY, "Too many operands");
  879. StringBuffer dummy;
  880. while (getParameter(dummy,forwhat.str()))
  881. ;
  882. }
  883. curParam.append(')');
  884. StringBuffer buf;
  885. OwnedIValue value = parseConstExpression(returnToken, curParam, queryTopXmlScope(),startLine-1,startCol);
  886. if (value)
  887. {
  888. value->getStringValue(buf);
  889. }
  890. else
  891. buf.append(curParam.length()-2, curParam.str()+1);
  892. if (isError)
  893. reportError(returnToken, ERR_HASHERROR, "#ERROR: %s", buf.str());
  894. else
  895. reportWarning(CategoryUnusual, returnToken, WRN_HASHWARNING, "#WARNING: %s", buf.str());
  896. }
  897. void HqlLex::doExport(YYSTYPE & returnToken, bool toXml)
  898. {
  899. StringBuffer forwhat;
  900. forwhat.appendf("#EXPORT(%d,%d)",returnToken.pos.lineno,returnToken.pos.column);
  901. IIdAtom * exportname = NULL;
  902. if (yyLex(returnToken, false,0) != '(')
  903. {
  904. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected");
  905. returnToken.release();
  906. return;
  907. }
  908. if (yyLex(returnToken, false,0) != UNKNOWN_ID)
  909. {
  910. reportError(returnToken, ERR_EXPECTED_IDENTIFIER, "Identifier expected");
  911. returnToken.release();
  912. return;
  913. }
  914. exportname = returnToken.getId();
  915. if (yyLex(returnToken, false,0) != ',')
  916. {
  917. reportError(returnToken, ERR_EXPECTED_COMMA, ", expected");
  918. return;
  919. }
  920. IPropertyTree *data = createPTree("Data", ipt_caseInsensitive);
  921. for (;;)
  922. {
  923. StringBuffer curParam("SIZEOF(");
  924. bool more = getParameter(curParam,"#EXPORT");
  925. curParam.append(",MAX)");
  926. OwnedHqlExpr expr;
  927. Owned<IHqlScope> scope = new CHqlParserPseduoScope(yyParser);
  928. try
  929. {
  930. HqlLookupContext ctx(yyParser->lookupCtx);
  931. Owned<IFileContents> exportContents = createFileContentsFromText(curParam.str(), sourcePath);
  932. expr.setown(parseQuery(scope, exportContents, ctx, xmlScope, NULL, true));
  933. if (expr && (expr->getOperator() == no_sizeof))
  934. {
  935. IHqlExpression * child = expr->queryChild(0);
  936. node_operator op = child->getOperator();
  937. if(op==no_table || op==no_usertable || op==no_newusertable || op == no_record || op == no_select || op == no_field)
  938. exportData(data, child, true);
  939. else if (child->queryRecord())
  940. exportData(data, child->queryRecord(), true);
  941. else
  942. reportError(returnToken, ERR_EXPECTED_COMMA, "DATASET or TABLE expression expected");
  943. }
  944. else
  945. reportError(returnToken, ERR_EXPECTED_COMMA, "Could not parse the argument passed to #EXPORT");
  946. }
  947. catch (...)
  948. {
  949. setXmlSymbol(returnToken, exportname->getAtomNamePtr(), "", false);
  950. PrintLog("Unexpected exception in doExport()");
  951. }
  952. if (!more)
  953. break;
  954. }
  955. StringBuffer buf;
  956. toXML(data, buf, 0);
  957. if (toXml)
  958. ensureTopXmlScope(returnToken)->loadXML(buf.str(), exportname->getAtomNamePtr());
  959. else
  960. setXmlSymbol(returnToken, exportname->getAtomNamePtr(), buf.str(), false);
  961. data->Release();
  962. }
  963. void HqlLex::doTrace(YYSTYPE & returnToken)
  964. {
  965. StringBuffer forwhat;
  966. forwhat.appendf("#TRACE(%d,%d)",returnToken.pos.lineno,returnToken.pos.column);
  967. IIdAtom * name = NULL;
  968. if (yyLex(returnToken, false,0) != '(')
  969. {
  970. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected");
  971. returnToken.release();
  972. return;
  973. }
  974. StringBuffer curParam("(");
  975. int startLine, startCol;
  976. if (getParameter(curParam,forwhat.str(),&startLine,&startCol))
  977. {
  978. reportError(returnToken, ERR_OPERANDS_TOOMANY, "Too many operands");
  979. StringBuffer dummy;
  980. while (getParameter(dummy,forwhat.str()))
  981. ;
  982. }
  983. curParam.append(')');
  984. Owned<IValue> value = parseConstExpression(returnToken, curParam, queryTopXmlScope(),startLine-1,startCol);
  985. if (value)
  986. {
  987. StringBuffer buf;
  988. value->getStringValue(buf);
  989. FILE *trace = fopen("hql.log", "at");
  990. if (trace)
  991. {
  992. fwrite(buf.str(),buf.length(),1,trace);
  993. fclose(trace);
  994. }
  995. }
  996. }
  997. void HqlLex::doFor(YYSTYPE & returnToken, bool doAll)
  998. {
  999. //MTIME_SECTION(timer, "HqlLex::doFor")
  1000. int startLine = -1, startCol = 0;
  1001. StringBuffer forwhat;
  1002. forwhat.appendf("#FOR(%d,%d)",returnToken.pos.lineno,returnToken.pos.column);
  1003. IIdAtom * name = NULL;
  1004. if (yyLex(returnToken, false,0) != '(')
  1005. {
  1006. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected");
  1007. returnToken.release();
  1008. return;
  1009. }
  1010. if (yyLex(returnToken, false,0) != UNKNOWN_ID)
  1011. {
  1012. reportError(returnToken, ERR_EXPECTED_IDENTIFIER, "Identifier expected");
  1013. returnToken.release();
  1014. return;
  1015. }
  1016. name = returnToken.getId();
  1017. StringBuffer forFilterText;
  1018. // Note - we gather the for filter and body in skip mode (deferring evaluation of #if etc) since the context will be different each time...
  1019. skipNesting = 1;
  1020. int tok = yyLex(returnToken, false,0);
  1021. if (tok == '(')
  1022. {
  1023. forFilterText.append('(');
  1024. while (getParameter(forFilterText, forwhat.str()))
  1025. forFilterText.append(") AND (");
  1026. forFilterText.append(')');
  1027. tok = yyLex(returnToken, false,0);
  1028. }
  1029. if (tok != ')')
  1030. {
  1031. reportError(returnToken, ERR_EXPECTED_RIGHTCURLY, ") expected");
  1032. // recovery: assume a ')' is here. And push back the token.
  1033. pushText(get_yyText());
  1034. returnToken.release();
  1035. }
  1036. // Now gather the tokens we are going to repeat...
  1037. StringBuffer forBodyText;
  1038. for (;;)
  1039. {
  1040. int tok = yyLex(returnToken, false,0);
  1041. if (startLine == -1)
  1042. {
  1043. startLine = returnToken.pos.lineno - 1;
  1044. startCol = returnToken.pos.column;
  1045. }
  1046. if (tok == EOF)
  1047. {
  1048. reportError(returnToken, ERR_TMPLT_HASHENDEXPECTED, "EOF encountered inside %s: #END expected", forwhat.str());
  1049. clearNestedHash(); // prevent unnecessary more error messages
  1050. return;
  1051. }
  1052. if (tok == HASHEND && !skipNesting)
  1053. break;
  1054. forBodyText.append(' ');
  1055. getTokenText(forBodyText);
  1056. returnToken.release();
  1057. }
  1058. ::Release(forLoop);
  1059. forLoop = getSubScopes(returnToken, name->getAtomNamePtr(), doAll);
  1060. if (forFilterText.length())
  1061. forFilter.setown(createFileContentsFromText(forFilterText, sourcePath));
  1062. forBody.setown(createFileContentsFromText(forBodyText, sourcePath));
  1063. loopTimes = 0;
  1064. if (forLoop && forLoop->first()) // more - check filter
  1065. checkNextLoop(returnToken, true, startLine, startCol);
  1066. }
  1067. void HqlLex::doLoop(YYSTYPE & returnToken)
  1068. {
  1069. int startLine = -1, startCol = 0;
  1070. StringBuffer forwhat;
  1071. forwhat.appendf("#LOOP(%d,%d)",returnToken.pos.lineno,returnToken.pos.column);
  1072. // Now gather the tokens we are going to repeat...
  1073. StringBuffer forBodyText;
  1074. // Note - we gather the for filter and body in skip mode (deferring evaluation of #if etc) since the context will be different each time...
  1075. skipNesting = 1;
  1076. hasHashbreak = false;
  1077. for (;;)
  1078. {
  1079. int tok = yyLex(returnToken, false,0);
  1080. if (startLine == -1)
  1081. {
  1082. startLine = returnToken.pos.lineno-1;
  1083. startCol = returnToken.pos.column;
  1084. }
  1085. if (tok == EOF)
  1086. {
  1087. reportError(returnToken, ERR_TMPLT_HASHENDEXPECTED, "EOF encountered inside %s: #END expected",forwhat.str());
  1088. clearNestedHash(); // prevent unnecessary more error messages
  1089. return;
  1090. }
  1091. if (tok == HASHEND && !skipNesting)
  1092. break;
  1093. forBodyText.append(' ');
  1094. getTokenText(forBodyText);
  1095. returnToken.release();
  1096. }
  1097. if (!hasHashbreak)
  1098. {
  1099. reportError(returnToken, ERR_TMPLT_NOBREAKINLOOP,"No #BREAK inside %s: infinite loop will occur", forwhat.str());
  1100. return;
  1101. }
  1102. ::Release(forLoop);
  1103. forLoop = new CDummyScopeIterator(ensureTopXmlScope(returnToken));
  1104. forFilter.clear();
  1105. forBody.setown(createFileContentsFromText(forBodyText, sourcePath));
  1106. loopTimes = 0;
  1107. if (forLoop->first()) // more - check filter
  1108. checkNextLoop(returnToken, true,startLine,startCol);
  1109. }
  1110. void HqlLex::doGetDataType(YYSTYPE & returnToken)
  1111. {
  1112. int tok = yyLex(returnToken, false,0);
  1113. if (tok != '(')
  1114. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected"); // MORE - make it fatal!
  1115. StringBuffer curParam("(");
  1116. if (getParameter(curParam, "#GETDATATYPE"))
  1117. {
  1118. reportError(returnToken, ERR_OPERANDS_TOOMANY, "too many operands");
  1119. StringBuffer dummy;
  1120. while (getParameter(dummy,"#GETDATATYPE"))
  1121. ;
  1122. }
  1123. curParam.append(')');
  1124. StringBuffer type;
  1125. doGetDataType(type, curParam.str(), returnToken.pos.lineno, returnToken.pos.column);
  1126. pushText(type.str());
  1127. }
  1128. StringBuffer& HqlLex::doGetDataType(StringBuffer & type, const char * text, int lineno, int column)
  1129. {
  1130. OwnedHqlExpr expr = parseECL(text, queryTopXmlScope(), lineno, column);
  1131. if(expr)
  1132. {
  1133. type.append('\'');
  1134. if (expr->queryType())
  1135. expr->queryType()->getECLType(type);
  1136. type.append('\'');
  1137. }
  1138. else
  1139. type.append("'unknown_type'");
  1140. return type;
  1141. }
  1142. int HqlLex::doHashText(YYSTYPE & returnToken)
  1143. {
  1144. StringBuffer forwhat;
  1145. forwhat.appendf("#TEXT(%d,%d)",returnToken.pos.lineno,returnToken.pos.column);
  1146. if (yyLex(returnToken, false,0) != '(')
  1147. {
  1148. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected");
  1149. returnToken.release();
  1150. returnToken.setExpr(createConstant(""));
  1151. return STRING_CONST;
  1152. }
  1153. StringBuffer parameterText;
  1154. bool moreParams = getParameter(parameterText, forwhat.str());
  1155. if (!moreParams)
  1156. {
  1157. while (parameterText.length() && parameterText.charAt(0)==' ')
  1158. parameterText.remove(0, 1);
  1159. }
  1160. else
  1161. {
  1162. reportError(returnToken, ERR_OPERANDS_TOOMANY, "Too many operands");
  1163. StringBuffer dummy;
  1164. while (getParameter(dummy,forwhat.str()))
  1165. ;
  1166. }
  1167. returnToken.setExpr(createConstant(parameterText));
  1168. return (STRING_CONST);
  1169. }
  1170. void HqlLex::doInModule(YYSTYPE & returnToken)
  1171. {
  1172. #ifdef TIMING_DEBUG
  1173. MTIME_SECTION(timer, "HqlLex::doInModule");
  1174. #endif
  1175. int tok = yyLex(returnToken, false,0);
  1176. if (tok != '(')
  1177. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected");
  1178. StringBuffer moduleName, attrName;
  1179. if (getParameter(moduleName,"#INMODULE"))
  1180. {
  1181. if (getParameter(attrName,"#INMODULE"))
  1182. {
  1183. reportError(returnToken, ERR_OPERANDS_TOOMANY, "too many operands");
  1184. /* skip the rest */
  1185. StringBuffer dummy;
  1186. while (getParameter(dummy,"#INMODULE"))
  1187. ;
  1188. }
  1189. }
  1190. else
  1191. {
  1192. reportError(returnToken, ERR_PARAM_TOOFEW,"Too few parameters: #INMODULE needs 2");
  1193. /* recovery */
  1194. pushText("true");
  1195. return;
  1196. }
  1197. if (isInModule(yyParser->lookupCtx, moduleName.str(),attrName.str()))
  1198. pushText("true");
  1199. else
  1200. pushText("false");
  1201. }
  1202. static bool isInModule(HqlLookupContext & ctx, const char* moduleName, const char* attrName)
  1203. {
  1204. if (!ctx.queryRepository())
  1205. return false;
  1206. try
  1207. {
  1208. //hack: get rid of the extra leading spaces
  1209. const char* pModule = moduleName;
  1210. while(*pModule==' ') pModule++;
  1211. const char* pAttr = attrName;
  1212. while(*pAttr==' ') pAttr++;
  1213. OwnedHqlExpr match = ctx.queryRepository()->queryRootScope()->lookupSymbol(createIdAtom(pModule), LSFpublic, ctx);
  1214. IHqlScope * scope = match ? match->queryScope() : NULL;
  1215. if (scope)
  1216. {
  1217. OwnedHqlExpr expr = scope->lookupSymbol(createIdAtom(pAttr), LSFpublic, ctx);
  1218. if (expr)
  1219. return true;
  1220. }
  1221. }
  1222. catch (...)
  1223. {
  1224. PrintLog("Unexpected exception in doInModule()");
  1225. }
  1226. return false;
  1227. }
  1228. void HqlLex::doUniqueName(YYSTYPE & returnToken)
  1229. {
  1230. int tok = yyLex(returnToken, false,0);
  1231. if (tok != '(')
  1232. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected");
  1233. else
  1234. tok = yyLex(returnToken, false,0);
  1235. if (tok != UNKNOWN_ID)
  1236. {
  1237. reportError(returnToken, ERR_EXPECTED_IDENTIFIER, "Identifier expected");
  1238. returnToken.release();
  1239. }
  1240. else
  1241. {
  1242. IIdAtom * name = returnToken.getId();
  1243. StringAttr pattern("__#__$__");
  1244. tok = yyLex(returnToken, false,0);
  1245. if (tok == ',')
  1246. {
  1247. tok = yyLex(returnToken, false,0);
  1248. if (tok == STRING_CONST)
  1249. {
  1250. StringBuffer text;
  1251. OwnedHqlExpr str = returnToken.getExpr();
  1252. getStringValue(text, str);
  1253. pattern.set(text.str());
  1254. tok = yyLex(returnToken, false,0);
  1255. }
  1256. else
  1257. reportError(returnToken, ERR_EXPECTED, "string expected");
  1258. }
  1259. declareUniqueName(name->getAtomNamePtr(), pattern);
  1260. }
  1261. if (tok != ')')
  1262. reportError(returnToken, ERR_EXPECTED_RIGHTCURLY, ") expected");
  1263. }
  1264. static int gUniqueId = 0;
  1265. void resetLexerUniqueNames() { gUniqueId = 0; }
  1266. void HqlLex::declareUniqueName(const char *name, const char * pattern)
  1267. {
  1268. IXmlScope *top = queryTopXmlScope();
  1269. if (!top)
  1270. top = xmlScope = createXMLScope();
  1271. StringBuffer value;
  1272. if (!top->getValue(name,value))
  1273. top->declareValue(name);
  1274. StringBuffer uniqueName;
  1275. bool added = false;
  1276. for (const char * cur = pattern; *cur; cur++)
  1277. {
  1278. char next = *cur;
  1279. switch (next)
  1280. {
  1281. case '#':
  1282. uniqueName.append(name);
  1283. break;
  1284. case '$':
  1285. uniqueName.append(++gUniqueId);
  1286. added = true;
  1287. break;
  1288. default:
  1289. uniqueName.append(next);
  1290. break;
  1291. }
  1292. }
  1293. if (!added)
  1294. uniqueName.append(++gUniqueId);
  1295. //PrintLog("Declaring unique name: %s",uniqueName.str());
  1296. top->setValue(name,uniqueName.str());
  1297. }
  1298. void HqlLex::doIsValid(YYSTYPE & returnToken)
  1299. {
  1300. int tok = yyLex(returnToken, false,0);
  1301. if (tok != '(')
  1302. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected");
  1303. StringBuffer curParam("(");
  1304. if (getParameter(curParam,"#ISVALID"))
  1305. {
  1306. reportError(returnToken, ERR_OPERANDS_TOOMANY, "too many operands");
  1307. StringBuffer dummy;
  1308. while (getParameter(dummy,"#ISVALID"))
  1309. ;
  1310. }
  1311. curParam.append(')');
  1312. IHqlExpression * expr = NULL;
  1313. IHqlScope *scope = createScope();
  1314. try
  1315. {
  1316. HqlLookupContext ctx(yyParser->lookupCtx);
  1317. ctx.errs.clear(); //Deliberately ignore any errors
  1318. Owned<IFileContents> contents = createFileContentsFromText(curParam.str(), sourcePath);
  1319. expr = parseQuery(scope, contents, ctx, xmlScope, NULL, true);
  1320. if(expr)
  1321. {
  1322. pushText("true");
  1323. }
  1324. else
  1325. {
  1326. pushText("false");
  1327. }
  1328. }
  1329. catch (...)
  1330. {
  1331. pushText("false");
  1332. PrintLog("Unexpected exception in doIsValid()");
  1333. }
  1334. ::Release(expr);
  1335. ::Release(closeScope(scope));
  1336. }
  1337. void HqlLex::checkNextLoop(const YYSTYPE & errpos, bool first, int startLine, int startCol)
  1338. {
  1339. if (yyParser->aborting)
  1340. return;
  1341. if (loopTimes++ > MAX_LOOP_TIMES)
  1342. {
  1343. reportError(errpos, ERR_TMPLT_LOOPEXCESSMAX,"The loop exceeded the limit: infinite loop is suspected");
  1344. return;
  1345. }
  1346. //printf("%d\r",loopTimes);
  1347. //assertex(forLoop);
  1348. while (first || forLoop->next())
  1349. {
  1350. bool filtered;
  1351. IXmlScope *subscope = (IXmlScope *) &forLoop->query();
  1352. if (forFilter)
  1353. {
  1354. #ifdef TIMING_DEBUG
  1355. MTIME_SECTION(timer, "HqlLex::checkNextLoopcond");
  1356. #endif
  1357. IValue *value = parseConstExpression(errpos, forFilter, subscope,startLine,startCol);
  1358. filtered = !value || !value->getBoolValue();
  1359. ::Release(value);
  1360. }
  1361. else
  1362. filtered = false;
  1363. if (!filtered)
  1364. {
  1365. pushText(forBody,startLine,startCol);
  1366. inmacro->xmlScope = LINK(subscope);
  1367. return;
  1368. }
  1369. first = false;
  1370. }
  1371. forLoop->Release();
  1372. forLoop = NULL;
  1373. }
  1374. void HqlLex::doPreprocessorLookup(const YYSTYPE & errpos, bool stringify, int extra)
  1375. {
  1376. StringBuffer out;
  1377. char *text = get_yyText() + 1;
  1378. unsigned len = (size32_t)strlen(text) - 1;
  1379. text += extra;
  1380. len -= (extra+extra);
  1381. StringBuffer in;
  1382. in.append(len, text);
  1383. lookupXmlSymbol(errpos, in.str(), out);
  1384. if (stringify)
  1385. {
  1386. char *expanded = (char *) malloc(out.length()*2 + 3); // maximum it could be (might be a bit big for alloca)
  1387. char *s = expanded;
  1388. *s++='\'';
  1389. const char *finger = out.str();
  1390. for (;;)
  1391. {
  1392. char c = *finger++;
  1393. if (!c)
  1394. break;
  1395. switch(c)
  1396. {
  1397. case '\r':
  1398. *s++='\\'; *s++ ='r';
  1399. break;
  1400. case '\n':
  1401. *s++='\\'; *s++ ='n';
  1402. break;
  1403. case '\\':
  1404. case '\'':
  1405. *s++='\\';
  1406. // fall into
  1407. default:
  1408. *s++=c;
  1409. }
  1410. }
  1411. *s++ = '\'';
  1412. *s = '\0';
  1413. pushText(expanded);
  1414. free(expanded);
  1415. }
  1416. else
  1417. {
  1418. // a space is needed sometimes, e.g, #IF(true or %x%=2)
  1419. out.trim();
  1420. if (out.length())
  1421. {
  1422. out.insert(0," ");
  1423. pushText(out.str());
  1424. }
  1425. else
  1426. pushText(" 0");
  1427. }
  1428. }
  1429. //Read the text of a parameter, but also have a good guess at whether it is defined.
  1430. bool HqlLex::getDefinedParameter(StringBuffer &curParam, YYSTYPE & returnToken, const char* for_what, SharedHqlExpr & resolved)
  1431. {
  1432. enum { StateStart, StateDot, StateSelectId, StateFailed } state = StateStart;
  1433. unsigned parenDepth = 1;
  1434. OwnedHqlExpr expr;
  1435. for (;;)
  1436. {
  1437. int tok = yyLex(returnToken, false, 0);
  1438. switch(tok)
  1439. {
  1440. case '(':
  1441. case '[':
  1442. parenDepth++;
  1443. break;
  1444. case ')':
  1445. if (parenDepth-- == 1)
  1446. {
  1447. if (state == StateDot)
  1448. resolved.setown(expr.getClear());
  1449. return false;
  1450. }
  1451. break;
  1452. case ']':
  1453. parenDepth--;
  1454. break;
  1455. case ',':
  1456. if (parenDepth==1)
  1457. {
  1458. if (state == StateDot)
  1459. resolved.setown(expr.getClear());
  1460. return true;
  1461. }
  1462. break;
  1463. case EOF:
  1464. {
  1465. StringBuffer msg("EOF encountered while gathering parameters for ");
  1466. msg.append(for_what);
  1467. reportError(returnToken, ERR_TMPLT_EOFINPARAM, "%s", msg.str());
  1468. }
  1469. return false;
  1470. case UNKNOWN_ID:
  1471. if (parenDepth == 1)
  1472. {
  1473. switch (state)
  1474. {
  1475. case StateStart:
  1476. {
  1477. expr.setown(lookupSymbol(returnToken.getId(), returnToken));
  1478. state = expr ? StateDot : StateFailed;
  1479. break;
  1480. }
  1481. case StateDot:
  1482. {
  1483. state = StateFailed;
  1484. break;
  1485. }
  1486. case StateSelectId:
  1487. {
  1488. state = StateFailed;
  1489. if (expr->getOperator() == no_funcdef)
  1490. expr.set(expr->queryChild(0));
  1491. IHqlScope * scope = expr->queryScope();
  1492. if (scope)
  1493. {
  1494. expr.setown(yyParser->lookupSymbol(scope, returnToken.getId()));
  1495. if (expr)
  1496. state = StateDot;
  1497. }
  1498. break;
  1499. }
  1500. }
  1501. }
  1502. curParam.append(' ');
  1503. break;
  1504. case '.':
  1505. if (parenDepth == 1)
  1506. {
  1507. if (state == StateDot)
  1508. state = StateSelectId;
  1509. else
  1510. state = StateFailed;
  1511. }
  1512. break;
  1513. default:
  1514. curParam.append(' ');
  1515. break;
  1516. }
  1517. getTokenText(curParam);
  1518. returnToken.release();
  1519. }
  1520. }
  1521. bool HqlLex::doIsDefined(YYSTYPE & returnToken)
  1522. {
  1523. StringBuffer forwhat;
  1524. forwhat.appendf("#ISDEFINED(%d,%d)",returnToken.pos.lineno,returnToken.pos.column);
  1525. if (!assertNextOpenBra())
  1526. return false;
  1527. OwnedHqlExpr resolved;
  1528. StringBuffer paramText;
  1529. bool hasMore = getDefinedParameter(paramText, returnToken, forwhat.str(), resolved);
  1530. if (hasMore)
  1531. reportError(returnToken, ERR_EXPECTED, "Expected ')'");
  1532. return resolved != NULL;
  1533. }
  1534. void HqlLex::doDefined(YYSTYPE & returnToken)
  1535. {
  1536. StringBuffer forwhat;
  1537. forwhat.appendf("#DEFINED(%d,%d)",returnToken.pos.lineno,returnToken.pos.column);
  1538. if (!assertNextOpenBra())
  1539. return;
  1540. OwnedHqlExpr resolved;
  1541. StringBuffer param1Text;
  1542. StringBuffer param2Text;
  1543. bool hasMore = getDefinedParameter(param1Text, returnToken, forwhat.str(), resolved);
  1544. if (hasMore)
  1545. hasMore = getParameter(param2Text, forwhat.str());
  1546. if (hasMore)
  1547. reportError(returnToken, ERR_EXPECTED, "Expected ')'");
  1548. if (resolved)
  1549. pushText(param1Text);
  1550. else if (param2Text.length())
  1551. pushText(param2Text);
  1552. }
  1553. IHqlExpression *HqlLex::parseECL(IFileContents * contents, IXmlScope *xmlScope, int startLine, int startCol)
  1554. {
  1555. #ifdef TIMING_DEBUG
  1556. MTIME_SECTION(timer, "HqlLex::parseConstExpression");
  1557. #endif
  1558. // Use an ECL reserved word as the scope name to avoid name conflicts with these defined localscope.
  1559. Owned<IHqlScope> scope = new CHqlMultiParentScope(sharedId,yyParser->queryPrimaryScope(false),yyParser->queryPrimaryScope(true),yyParser->parseScope.get(),NULL);
  1560. HqlGramCtx parentContext(yyParser->lookupCtx);
  1561. yyParser->saveContext(parentContext, false);
  1562. HqlGram parser(parentContext, scope, contents, xmlScope, true);
  1563. parser.getLexer()->set_yyLineNo(startLine);
  1564. parser.getLexer()->set_yyColumn(startCol);
  1565. return parser.yyParse(false, false);
  1566. }
  1567. IHqlExpression *HqlLex::parseECL(const char * text, IXmlScope *xmlScope, int startLine, int startCol)
  1568. {
  1569. Owned<IFileContents> contents = createFileContentsFromText(text, querySourcePath());
  1570. return parseECL(contents, xmlScope, startLine, startCol);
  1571. }
  1572. IValue *HqlLex::foldConstExpression(const YYSTYPE & errpos, IHqlExpression * expr, IXmlScope *xmlScope, int startLine, int startCol)
  1573. {
  1574. OwnedIValue value;
  1575. if (expr)
  1576. {
  1577. try
  1578. {
  1579. CTemplateContext context(this, yyParser->lookupCtx, xmlScope, startLine, startCol);
  1580. OwnedHqlExpr folded = foldHqlExpression(*yyParser, expr, &context, HFOthrowerror|HFOfoldimpure|HFOforcefold);
  1581. if (folded)
  1582. {
  1583. if (folded->queryValue())
  1584. value.set(folded->queryValue());
  1585. }
  1586. }
  1587. catch (IException* except)
  1588. {
  1589. StringBuffer s;
  1590. reportError(errpos, except->errorCode(), "%s", except->errorMessage(s).str());
  1591. except->Release();
  1592. }
  1593. }
  1594. if (!value.get())
  1595. reportError(errpos, ERR_EXPECTED_CONST, "Constant expression expected"); // errpos could be better
  1596. return value.getClear();
  1597. }
  1598. IValue *HqlLex::parseConstExpression(const YYSTYPE & errpos, StringBuffer &curParam, IXmlScope *xmlScope, int startLine, int startCol)
  1599. {
  1600. #ifdef TIMING_DEBUG
  1601. MTIME_SECTION(timer, "HqlLex::parseConstExpression");
  1602. #endif
  1603. OwnedHqlExpr expr = parseECL(curParam, xmlScope, startLine, startCol);
  1604. return foldConstExpression(errpos, expr, xmlScope, startLine, startCol);
  1605. }
  1606. IValue *HqlLex::parseConstExpression(const YYSTYPE & errpos, IFileContents * text, IXmlScope *xmlScope, int startLine, int startCol)
  1607. {
  1608. #ifdef TIMING_DEBUG
  1609. MTIME_SECTION(timer, "HqlLex::parseConstExpression");
  1610. #endif
  1611. OwnedHqlExpr expr = parseECL(text, xmlScope, startLine, startCol);
  1612. return foldConstExpression(errpos, expr, xmlScope, startLine, startCol);
  1613. }
  1614. int hexchar(char c)
  1615. {
  1616. if (c >= 'A' && c <= 'F')
  1617. return c - 'A' + 10;
  1618. else if (c >= 'a' && c <= 'f')
  1619. return c - 'a' + 10;
  1620. else
  1621. return c - '0';
  1622. }
  1623. void HqlLex::doApply(YYSTYPE & returnToken)
  1624. {
  1625. int tok = yyLex(returnToken, false,0);
  1626. int line = returnToken.pos.lineno, col = returnToken.pos.column;
  1627. if (tok != '(')
  1628. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected"); // MORE - make it fatal!
  1629. StringBuffer curParam("(");
  1630. if (getParameter(curParam, "#APPLY"))
  1631. {
  1632. reportError(returnToken, ERR_OPERANDS_TOOMANY, "too many operands");
  1633. StringBuffer dummy;
  1634. while (getParameter(dummy, "#APPLY"))
  1635. ;
  1636. }
  1637. curParam.append(')');
  1638. OwnedHqlExpr actions = parseECL(curParam, queryTopXmlScope(), line, col);
  1639. if (actions)
  1640. {
  1641. CTemplateContext context(this, yyParser->lookupCtx, xmlScope,line,col);
  1642. OwnedHqlExpr folded = foldHqlExpression(*yyParser, actions, &context, HFOthrowerror|HFOfoldimpure|HFOforcefold);
  1643. }
  1644. else
  1645. reportError(returnToken, ERR_EXPECTED_CONST, "Constant expression expected");
  1646. }
  1647. void HqlLex::doMangle(YYSTYPE & returnToken, bool de)
  1648. {
  1649. int tok = yyLex(returnToken, false,0);
  1650. int line = returnToken.pos.lineno, col = returnToken.pos.column;
  1651. if (tok != '(')
  1652. reportError(returnToken, ERR_EXPECTED_LEFTCURLY, "( expected"); // MORE - make it fatal!
  1653. StringBuffer curParam("(");
  1654. if (getParameter(curParam, de?"#DEMANGLE":"#MANGLE"))
  1655. {
  1656. reportError(returnToken, ERR_OPERANDS_TOOMANY, "too many operands");
  1657. StringBuffer dummy;
  1658. while (getParameter(dummy, de?"#DEMANGLE":"MANGLE"))
  1659. ;
  1660. }
  1661. curParam.append(')');
  1662. IValue *value = parseConstExpression(returnToken, curParam, queryTopXmlScope(), line, col);
  1663. if (value)
  1664. {
  1665. const char *str = value->getStringValue(curParam.clear());
  1666. value->Release();
  1667. StringBuffer mangled;
  1668. mangle(yyParser->errorHandler,str,mangled,de);
  1669. pushText(mangled.str());
  1670. }
  1671. else
  1672. reportError(returnToken, ERR_EXPECTED_CONST, "Constant expression expected");
  1673. }
  1674. static StringBuffer& mangle(IErrorReceiver* errReceiver,const char* src, StringBuffer& mangled,bool de)
  1675. {
  1676. mangled.append("'");
  1677. for (const char *finger = src; *finger!=0; finger++)
  1678. {
  1679. unsigned char c = *finger;
  1680. if (isalnum(c))
  1681. {
  1682. if (finger == src && isdigit(c)) // a leading digit
  1683. {
  1684. if (de)
  1685. {
  1686. //errReceiver->reportError(returnToken, ERR_EXPECTED_CONST, "Bad parameter to #DEMANGLE", "CppTemplate");
  1687. PrintLog("Bad parameter to #DEMANGLE");
  1688. break;
  1689. }
  1690. else
  1691. mangled.appendf("_%02x",(int)c);
  1692. }
  1693. else
  1694. mangled.append(c);
  1695. }
  1696. else if (de)
  1697. {
  1698. if (c != '_')
  1699. {
  1700. //errReceiver->reportError(returnToken, ERR_EXPECTED_CONST, "Bad parameter to #DEMANGLE");
  1701. PrintLog("Bad parameter to #DEMANGLE");
  1702. break;
  1703. }
  1704. c = hexchar(finger[1])*16 + hexchar(finger[2]);
  1705. finger += 2;
  1706. if (c=='\'')
  1707. mangled.append('\\');
  1708. mangled.append(c);
  1709. }
  1710. else
  1711. mangled.appendf("_%02x", (int) c);
  1712. }
  1713. mangled.append('\'');
  1714. return mangled;
  1715. }
  1716. bool HqlLex::checkUnicodeLiteral(char const * str, unsigned length, unsigned & ep, StringBuffer & msg)
  1717. {
  1718. unsigned i;
  1719. for(i = 0; i < length; i++)
  1720. {
  1721. if (str[i] == '\\')
  1722. {
  1723. unsigned char next = str[++i];
  1724. if (next == '\'' || next == '\\' || next == 'n' || next == 'r' || next == 't' || next == 'a' || next == 'b' || next == 'f' || next == 'v' || next == '?' || next == '"')
  1725. {
  1726. continue;
  1727. }
  1728. else if (isdigit(next) && next < '8')
  1729. {
  1730. unsigned count;
  1731. for(count = 1; count < 3; count++)
  1732. {
  1733. next = str[++i];
  1734. if(!isdigit(next) || next >= '8')
  1735. {
  1736. msg.append("3-digit numeric escape sequence contained non-octal digit: ").append(next);
  1737. ep = i;
  1738. return false;
  1739. }
  1740. }
  1741. }
  1742. else if (next == 'u' || next == 'U')
  1743. {
  1744. unsigned count;
  1745. unsigned max = (next == 'u') ? 4 : 8;
  1746. for(count = 0; count < max; count++)
  1747. {
  1748. next = str[++i];
  1749. if(!isdigit(next) && (!isalpha(next) || tolower(next) > 'f'))
  1750. {
  1751. msg.append((max == 4) ? '4' : '8').append("-digit unicode escape sequence contained non-hex digit: ").append(next);
  1752. ep = i;
  1753. return false;
  1754. }
  1755. }
  1756. }
  1757. else
  1758. {
  1759. msg.append("Unrecognized escape sequence: ").append("\\").append(next);
  1760. ep = i;
  1761. return false;
  1762. }
  1763. }
  1764. }
  1765. return true;
  1766. }
  1767. //====================================== Error Reporting ======================================
  1768. bool HqlLex::isAborting()
  1769. {
  1770. return yyParser->isAborting();
  1771. }
  1772. void HqlLex::reportError(const YYSTYPE & returnToken, int errNo, const char *format, ...)
  1773. {
  1774. if (yyParser)
  1775. {
  1776. va_list args;
  1777. va_start(args, format);
  1778. yyParser->reportErrorVa(errNo, returnToken.pos, format, args);
  1779. va_end(args);
  1780. }
  1781. }
  1782. void HqlLex::reportWarning(WarnErrorCategory category, const YYSTYPE & returnToken, int warnNo, const char *format, ...)
  1783. {
  1784. if (yyParser)
  1785. {
  1786. va_list args;
  1787. va_start(args, format);
  1788. yyParser->reportWarningVa(category, warnNo, returnToken, format, args);
  1789. va_end(args);
  1790. }
  1791. }
  1792. //====================================== XML DB =============================================
  1793. IXmlScope *HqlLex::queryTopXmlScope()
  1794. {
  1795. IXmlScope *top = NULL;
  1796. HqlLex *inlex = this;
  1797. while (inlex->inmacro)
  1798. inlex = inlex->inmacro;
  1799. while (inlex && !top)
  1800. {
  1801. top = inlex->xmlScope;
  1802. inlex = inlex->parentLex;
  1803. }
  1804. return top;
  1805. }
  1806. IXmlScope *HqlLex::ensureTopXmlScope(const YYSTYPE & errpos)
  1807. {
  1808. IXmlScope *top = queryTopXmlScope();
  1809. if (!top)
  1810. {
  1811. reportError(errpos, ERR_XML_NOSCOPE, "No XML scope active");
  1812. // recovery: create a default XML scope
  1813. top = xmlScope = ::loadXML("<xml></xml>");
  1814. }
  1815. return top;
  1816. }
  1817. StringBuffer &HqlLex::lookupXmlSymbol(const YYSTYPE & errpos, const char *name, StringBuffer &ret)
  1818. {
  1819. if (*name==0)
  1820. name=NULL;
  1821. IXmlScope *top = ensureTopXmlScope(errpos);
  1822. top->getValue(name, ret);
  1823. return ret;
  1824. }
  1825. void HqlLex::setXmlSymbol(const YYSTYPE & errpos, const char *name, const char *value, bool append)
  1826. {
  1827. IXmlScope *top = ensureTopXmlScope(errpos);
  1828. bool ok;
  1829. if (append)
  1830. ok = top->appendValue(name, value);
  1831. else
  1832. ok = top->setValue(name, value);
  1833. if (!ok)
  1834. {
  1835. StringBuffer msg("Symbol has not been declared: ");
  1836. msg.append(name);
  1837. reportError(errpos, ERR_TMPLT_SYMBOLNOTDECLARED, "%s", msg.str());
  1838. }
  1839. }
  1840. void HqlLex::declareXmlSymbol(const YYSTYPE & errpos, const char *name)
  1841. {
  1842. IXmlScope *top = ensureTopXmlScope(errpos);
  1843. if (!top->declareValue(name))
  1844. {
  1845. StringBuffer msg("Symbol has already been declared: ");
  1846. msg.append(name);
  1847. reportError(errpos, ERR_TMPLT_SYMBOLREDECLARE, "%s", msg.str());
  1848. }
  1849. }
  1850. IIterator *HqlLex::getSubScopes(const YYSTYPE & errpos, const char *name, bool doAll)
  1851. {
  1852. IXmlScope *top = ensureTopXmlScope(errpos);
  1853. return top->getScopes(name, doAll);
  1854. }
  1855. void HqlLex::loadXML(const YYSTYPE & errpos, const char *name, const char * child)
  1856. {
  1857. if (xmlScope && child)
  1858. {
  1859. xmlScope->loadXML(name, child);
  1860. return;
  1861. }
  1862. if (false && inmacro)
  1863. {
  1864. inmacro->loadXML(errpos, name);
  1865. return;
  1866. }
  1867. // MORE - give an error if an XML scope is active...
  1868. ::Release(xmlScope);
  1869. try
  1870. {
  1871. xmlScope = ::loadXML(name);
  1872. }
  1873. catch (IException* e)
  1874. {
  1875. e->Release();
  1876. xmlScope = NULL;
  1877. }
  1878. catch (...)
  1879. {
  1880. xmlScope = NULL;
  1881. }
  1882. if (!xmlScope)
  1883. {
  1884. if (name && strlen(name))
  1885. {
  1886. StringBuffer msg;
  1887. msg.appendf("Load XML(\'%s\') failed",name);
  1888. reportError(errpos, ERR_TMPLT_LOADXMLFAILED, "%s", msg.str());
  1889. }
  1890. // recovery: create a default XML scope
  1891. xmlScope = ::loadXML("<xml></xml>");
  1892. }
  1893. }
  1894. IPropertyTree * HqlLex::getClearJavadoc()
  1895. {
  1896. if (javaDocComment.length() == 0)
  1897. return NULL;
  1898. IPropertyTree * tree = createPTree("javadoc");
  1899. extractJavadoc(tree, javaDocComment.str());
  1900. javaDocComment.clear();
  1901. return tree;
  1902. }
  1903. unsigned HqlLex::getTypeSize(unsigned lengthTypeName)
  1904. {
  1905. const char * tok = get_yyText();
  1906. if (strlen(tok)> lengthTypeName)
  1907. return atoi(tok + lengthTypeName);
  1908. return UNKNOWN_LENGTH;
  1909. }
  1910. void HqlLex::enterEmbeddedMode()
  1911. {
  1912. doEnterEmbeddedMode(scanner);
  1913. inCpp = true;
  1914. }
  1915. int HqlLex::yyLex(YYSTYPE & returnToken, bool lookup, const short * activeState)
  1916. {
  1917. loop
  1918. {
  1919. while (inmacro)
  1920. {
  1921. int ret = inmacro->yyLex(returnToken, lookup, activeState);
  1922. if (ret > 0 && ret != HASHBREAK)
  1923. {
  1924. lastToken = ret;
  1925. return ret;
  1926. }
  1927. #if defined(TRACE_MACRO)
  1928. PrintLog("MACRO>> inmacro %p deleted\n", inmacro);
  1929. #endif
  1930. delete inmacro;
  1931. inmacro = NULL;
  1932. if (ret == HASHBREAK)
  1933. {
  1934. if (forLoop)
  1935. {
  1936. forLoop->Release();
  1937. forLoop = NULL;
  1938. }
  1939. else
  1940. {
  1941. lastToken = ret;
  1942. return ret;
  1943. }
  1944. }
  1945. if (forLoop)
  1946. checkNextLoop(returnToken, false,0,0);
  1947. }
  1948. returnToken.clear();
  1949. yyStartPos = yyPosition;
  1950. int ret = doyyFlex(returnToken, scanner, this, lookup, activeState);
  1951. if (ret == 0) ret = EOF;
  1952. if (ret == INTERNAL_READ_NEXT_TOKEN)
  1953. continue;
  1954. if (ret == EOF)
  1955. {
  1956. setTokenPosition(returnToken);
  1957. if (inComment)
  1958. reportError(returnToken, ERR_COMMENT_UNENDED,"Comment is not terminated");
  1959. else if (inCpp)
  1960. reportError(returnToken, ERR_COMMENT_UNENDED,"BEGINC++ or EMBED is not terminated");
  1961. if (hashendKinds.ordinality())
  1962. {
  1963. StringBuffer msg("Unexpected EOF: ");
  1964. msg.append(hashendKinds.ordinality()).append(" more #END needed");
  1965. reportError(returnToken, ERR_TMPLT_HASHENDEXPECTED, "%s", msg.str());
  1966. clearNestedHash();
  1967. }
  1968. }
  1969. lastToken = ret;
  1970. return ret;
  1971. }
  1972. }