hqlregex.cpp 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. #ifndef U_OVERRIDE_CXX_ALLOCATION
  15. #define U_OVERRIDE_CXX_ALLOCATION 0 // Enabling this forces all allocation of ICU objects to ICU's heap, but is incompatible with jmemleak
  16. #endif
  17. #include <algorithm>
  18. #include "jliball.hpp"
  19. #include "eclrtl.hpp"
  20. #include "hqlexpr.hpp"
  21. #include "hqlcerrors.hpp"
  22. #include "hqlutil.hpp"
  23. #include "hqlregex.ipp"
  24. #include "hqlhtcpp.ipp"
  25. #include "hqlcatom.hpp"
  26. #include "hqlcpputil.hpp"
  27. #include "thorrparse.ipp"
  28. #include "hqlthql.hpp"
  29. #include "unicode/uchar.h"
  30. //#define NEW_DFA_CALC
  31. //#define DEFAULT_DFA_COMPLEXITY 0
  32. #define DEFAULT_UNICODE_DFA_COMPLEXITY 0
  33. #define DEFAULT_UTF8_DFA_COMPLEXITY 2000
  34. #define DEFAULT_DFA_COMPLEXITY 10000
  35. inline unsigned addWithoutOverflow(unsigned x, unsigned y)
  36. {
  37. if (UINT_MAX - x <= y)
  38. return UINT_MAX;
  39. return x + y;
  40. }
  41. inline unsigned multiplyWithoutOverflow(unsigned x, unsigned y)
  42. {
  43. if (UINT_MAX / x <= y)
  44. return UINT_MAX;
  45. return x * y;
  46. }
  47. //===========================================================================
  48. static IValue * getCastConstant(IValue * value, type_t tc)
  49. {
  50. switch (tc)
  51. {
  52. case type_unicode:
  53. return value->castTo(unknownUnicodeType);
  54. case type_utf8:
  55. return value->castTo(unknownUtf8Type);
  56. case type_string:
  57. return value->castTo(unknownStringType);
  58. }
  59. throwUnexpected();
  60. }
  61. static HqlRegexExpr * createRegexExpr(const ParseInformation & options, IHqlExpression * expr, bool caseSensitive)
  62. {
  63. switch (expr->getOperator())
  64. {
  65. case no_null:
  66. case no_pat_beginrecursive:
  67. case no_pat_beginpattern:
  68. case no_pat_endpattern:
  69. case no_pat_singlechar:
  70. return new HqlSimpleRegexExpr(options, expr, caseSensitive);
  71. }
  72. return new HqlComplexRegexExpr(options, expr, caseSensitive);
  73. }
  74. static HqlRegexExpr * createRegexExpr(const ParseInformation & options, node_operator op, IHqlExpression * expr, bool caseSensitive)
  75. {
  76. switch (op)
  77. {
  78. case no_null:
  79. case no_pat_beginrecursive:
  80. case no_pat_beginpattern:
  81. case no_pat_endpattern:
  82. case no_pat_singlechar:
  83. return new HqlSimpleRegexExpr(options, op, expr, caseSensitive);
  84. }
  85. return new HqlComplexRegexExpr(options, op, expr, caseSensitive);
  86. }
  87. //---------------------------------------------------------------------------
  88. void HqlRegexHashTable::onAdd(void *et)
  89. {
  90. ((HqlRegexExpr*)et)->Link();
  91. }
  92. void HqlRegexHashTable::onRemove(void *et)
  93. {
  94. ((HqlRegexExpr*)et)->Release();
  95. }
  96. unsigned HqlRegexHashTable::getHashFromElement(const void *et) const
  97. {
  98. return ((HqlRegexExpr*)et)->getHash();
  99. }
  100. unsigned HqlRegexHashTable::getHashFromFindParam(const void *fp) const
  101. {
  102. return ((HqlRegexExpr*)fp)->getHash();
  103. }
  104. const void * HqlRegexHashTable::getFindParam(const void *et) const
  105. {
  106. return et;
  107. }
  108. bool HqlRegexHashTable::matchesFindParam(const void *et, const void *key, unsigned fphash) const
  109. {
  110. return et == key;
  111. }
  112. void HqlRegexUniqueArray::append(HqlRegexExpr & expr)
  113. {
  114. if (!hash.find(&expr))
  115. {
  116. array.append(expr);
  117. hash.add(&expr);
  118. }
  119. else
  120. {
  121. expr.Release();
  122. }
  123. }
  124. //---------------------------------------------------------------------------
  125. inline unsigned limitedAdd(unsigned a, unsigned b)
  126. {
  127. if (PATTERN_UNLIMITED_LENGTH - a <= b)
  128. return PATTERN_UNLIMITED_LENGTH;
  129. return a+b;
  130. }
  131. inline unsigned limitedMult(unsigned a, unsigned b)
  132. {
  133. if (a == 0)
  134. return 0;
  135. if (PATTERN_UNLIMITED_LENGTH / a <= b)
  136. return PATTERN_UNLIMITED_LENGTH;
  137. return a*b;
  138. }
  139. IHqlExpression * RegexIdAllocator::createKey(IHqlExpression * expr, _ATOM name)
  140. {
  141. if (!expr)
  142. return NULL;
  143. IHqlExpression * body = expr->queryBody();
  144. if (name)
  145. return createSymbol(name, body->getType(), LINK(body));
  146. return LINK(body);
  147. }
  148. void RegexIdAllocator::setID(IHqlExpression * expr, _ATOM name, unsigned value)
  149. {
  150. OwnedHqlExpr key = createKey(expr, name);
  151. map.setValue(key, value);
  152. }
  153. regexid_t RegexIdAllocator::queryID(IHqlExpression * expr, _ATOM name)
  154. {
  155. OwnedHqlExpr key = createKey(expr, name);
  156. regexid_t * match = map.getValue(key);
  157. if (match)
  158. return *match;
  159. map.setValue(key, ++nextId);
  160. return nextId;
  161. }
  162. int compareUnsigned(unsigned * left, unsigned * right)
  163. {
  164. return (*left < *right) ? -1 : (*left > *right) ? +1 : 0;
  165. }
  166. class SymbolArray
  167. {
  168. friend class SymbolArrayIterator;
  169. public:
  170. void addUniqueRange(unsigned low, unsigned high)
  171. {
  172. unsigned max = symbols.ordinality();
  173. unsigned i;
  174. for (i = 0; i < max; i++)
  175. {
  176. unsigned cur = symbols.item(i);
  177. if (cur == low)
  178. low++;
  179. if (cur > low)
  180. {
  181. if (cur > high)
  182. cur = high+1;
  183. while (low != cur)
  184. symbols.add(low++, i++);
  185. low++;
  186. }
  187. if (cur > high)
  188. return;
  189. }
  190. while (low <= high)
  191. symbols.append(low++);
  192. }
  193. inline void addUnique(unsigned value)
  194. {
  195. bool isNew;
  196. symbols.bAdd(value, compareUnsigned, isNew);
  197. }
  198. protected:
  199. UnsignedArray symbols;
  200. };
  201. class SymbolArrayIterator
  202. {
  203. public:
  204. SymbolArrayIterator(SymbolArray & _table) : table(_table) { cur = 0; }
  205. inline bool first()
  206. {
  207. cur = 0; return table.symbols.isItem(cur);
  208. }
  209. inline bool isValid()
  210. {
  211. return table.symbols.isItem(cur);
  212. }
  213. inline unsigned get()
  214. {
  215. return table.symbols.item(cur);
  216. }
  217. inline bool next()
  218. {
  219. cur++; return table.symbols.isItem(cur);
  220. }
  221. protected:
  222. SymbolArray & table;
  223. unsigned cur;
  224. };
  225. //---------------------------------------------------------------------------
  226. HqlNamedRegex::HqlNamedRegex(IHqlExpression * _expr, _ATOM _name, IHqlExpression * _searchExpr, node_operator _kind, bool _caseSensitive, bool _isMatched)
  227. {
  228. kind = _kind;
  229. expr.set(_expr);
  230. searchExpr.set(_searchExpr);
  231. name = _name;
  232. numUses = 1;
  233. isMatched = _isMatched;
  234. isRecursive = false;
  235. doneCalcDfaScore = false;
  236. doneCreateDFA = false;
  237. doneExpandNamed = false;
  238. doneExpandRecursion = false;
  239. doneMarkDfas = false;
  240. noGenerate = (kind == no_pat_dfa);
  241. caseSensitive = _caseSensitive;
  242. }
  243. HqlNamedRegex::~HqlNamedRegex()
  244. {
  245. cleanup();
  246. }
  247. void HqlNamedRegex::addBeginEnd(const ParseInformation & options)
  248. {
  249. //Add nodes at either end of the pattern - at the start as a placeholder for all the possible first patterns,
  250. //and at the end to mark which paths are terminal.
  251. HqlRegexExpr * follow = createRegexExpr(options, no_pat_follow, NULL, caseSensitive);
  252. follow->addOperand(createRegexExpr(options, isRecursive ? no_pat_beginrecursive : no_pat_beginpattern, NULL, caseSensitive));
  253. follow->addOperand(LINK(def));
  254. if (isRecursive)
  255. follow->addOperand(createRegexExpr(options, no_pat_endrecursive, NULL, caseSensitive));
  256. follow->addOperand(createRegexExpr(options, no_pat_endpattern, NULL, caseSensitive));
  257. def.setown(follow);
  258. }
  259. void HqlNamedRegex::analyseNullLeadTrail()
  260. {
  261. def->analyseNullLeadTrail();
  262. limit = def->limit;
  263. }
  264. void HqlNamedRegex::calcDfaScore()
  265. {
  266. if (!doneCalcDfaScore)
  267. {
  268. doneCalcDfaScore = true;
  269. def->calcDfaScore();
  270. }
  271. }
  272. void HqlNamedRegex::calculateNext()
  273. {
  274. def->calculateNext();
  275. }
  276. bool HqlNamedRegex::canBeNull()
  277. {
  278. return limit.canBeNull();
  279. }
  280. void HqlNamedRegex::cleanup()
  281. {
  282. if (def)
  283. def->cleanup();
  284. if (created)
  285. created->dispose();
  286. }
  287. void HqlNamedRegex::createDFAs(RegexContext & ctx)
  288. {
  289. if (!doneCreateDFA)
  290. {
  291. doneCreateDFA = true;
  292. def.setown(def->createDFAs(ctx));
  293. }
  294. }
  295. void HqlNamedRegex::expandNamedSymbols()
  296. {
  297. if (!doneExpandNamed)
  298. {
  299. doneExpandNamed = true;
  300. def.setown(def->expandNamedSymbols());
  301. }
  302. }
  303. void HqlNamedRegex::expandRecursion(RegexContext & ctx, HqlNamedRegex * self)
  304. {
  305. if (!doneExpandRecursion)
  306. {
  307. doneExpandRecursion = true;
  308. if (kind == no_pat_instance)
  309. self = this;
  310. def.setown(def->expandRecursion(ctx, self));
  311. }
  312. }
  313. void HqlNamedRegex::generateDFAs()
  314. {
  315. if (!noGenerate)
  316. def->generateDFAs();
  317. }
  318. void HqlNamedRegex::generateRegex(GenerateRegexCtx & ctx)
  319. {
  320. if (created || noGenerate)
  321. return;
  322. node_operator savedKind = ctx.namedKind;
  323. ctx.namedKind = kind;
  324. created.setown(new RegexNamed(name, ctx.idAllocator.queryID(expr, name)));
  325. def->generateRegex(ctx);
  326. def->connectRegex();
  327. HqlRegexExpr * first = def->queryChild(0);
  328. if ((first->getOperator() == no_pat_beginpattern) && (first->following.ordinality() == 1))
  329. first = &first->following.item(0);
  330. created->setFirst(first->created);
  331. ctx.namedKind = savedKind;
  332. }
  333. unsigned HqlNamedRegex::getDfaScore()
  334. {
  335. if (isRecursive)
  336. return NO_DFA_SCORE;
  337. return def->dfaScore;
  338. }
  339. void HqlNamedRegex::insertSeparators(IHqlExpression * separator, RegexContext * ctx)
  340. {
  341. if (expr->queryType()->getTypeCode() == type_pattern)
  342. return;
  343. def.setown(def->insertSeparators(separator, ctx));
  344. }
  345. void HqlNamedRegex::markDFAs(unsigned complexity)
  346. {
  347. if (!doneMarkDfas)
  348. {
  349. doneMarkDfas = true;
  350. def->markDFAs(complexity);
  351. }
  352. }
  353. bool HqlNamedRegex::matchesDefine(IHqlExpression * name, bool _caseSensitive)
  354. {
  355. return (name->queryBody() == defineName) && (caseSensitive == _caseSensitive);
  356. }
  357. void HqlNamedRegex::mergeCreateSets()
  358. {
  359. def.setown(def->mergeCreateSets());
  360. }
  361. bool HqlNamedRegex::queryExpandInline()
  362. {
  363. expandNamedSymbols();
  364. if (!isMatched)
  365. {
  366. if (numUses == 1)
  367. return true;
  368. //expand if trivial - this should be improved once dfa support is implemented.
  369. switch (def->getOperator())
  370. {
  371. case no_pat_instance:
  372. case no_pat_set:
  373. case no_pat_const:
  374. case no_pat_first:
  375. case no_pat_last:
  376. case no_pat_anychar:
  377. return true;
  378. }
  379. }
  380. return false;
  381. }
  382. RegexPattern * HqlNamedRegex::queryRootPattern()
  383. {
  384. //return a reference to the begin
  385. HqlRegexExpr * first = def->queryChild(0);
  386. if ((first->getOperator() == no_pat_beginpattern) && (first->following.ordinality() == 1))
  387. first = &first->following.item(0);
  388. return first->created;
  389. }
  390. void HqlNamedRegex::setRegexOwn(HqlRegexExpr * _def)
  391. {
  392. def.setown(_def);
  393. IHqlExpression * defExpr = def->expr;
  394. if (def->getOperator() == no_define)
  395. defineName.set(defExpr->queryChild(1)->queryBody());
  396. }
  397. //---------------------------------------------------------------------------
  398. static HqlRegexExpr * expandStringAsChars(IHqlExpression * expr, const ParseInformation & options, bool caseSensitive)
  399. {
  400. Owned<IValue> castValue = getCastConstant(expr->queryChild(0)->queryValue(), options.type);
  401. //convert text strings into a sequence of characters...
  402. ITypeInfo * type = castValue->queryType();
  403. unsigned len = type->getStringLen();
  404. if (len == 0)
  405. return createRegexExpr(options, no_null, NULL, caseSensitive);
  406. HqlRegexExpr * expanded = createRegexExpr(options, no_pat_follow, NULL, caseSensitive);
  407. bool readUChar = false;
  408. const void * value = castValue->queryValue();
  409. switch (options.type)
  410. {
  411. case type_unicode:
  412. readUChar = true;
  413. break;
  414. case type_utf8:
  415. //UTF8 is matched as a sequence of characters...
  416. len = rtlUtf8Size(len, value);
  417. break;
  418. }
  419. for (unsigned i = 0; i < len; i++)
  420. {
  421. unsigned nextValue;
  422. if (readUChar)
  423. nextValue = ((UChar *)value)[i];
  424. else
  425. nextValue = ((unsigned char *)value)[i];
  426. OwnedHqlExpr next = getSizetConstant(nextValue);
  427. expanded->addOperand(createRegexExpr(options, no_pat_singlechar, next, caseSensitive));
  428. }
  429. return expanded;
  430. }
  431. //---------------------------------------------------------------------------
  432. HqlRegexExpr::HqlRegexExpr(const ParseInformation & _options, IHqlExpression * _expr, bool _caseSensitive) : options(_options)
  433. {
  434. expr.set(_expr);
  435. op = expr->getOperator();
  436. caseSensitive = _caseSensitive;
  437. init();
  438. }
  439. HqlRegexExpr::HqlRegexExpr(const ParseInformation & _options, node_operator _op, IHqlExpression * _expr, bool _caseSensitive) : options(_options)
  440. {
  441. expr.set(_expr);
  442. op = _op;
  443. caseSensitive = _caseSensitive;
  444. init();
  445. }
  446. HqlRegexExpr::~HqlRegexExpr()
  447. {
  448. ::Release(dfa);
  449. }
  450. void HqlRegexExpr::init()
  451. {
  452. uid = (unsigned)(getUniqueId()-options.uidBase);
  453. cleaned = false;
  454. connected = false;
  455. analysed = false;
  456. createDFA = false;
  457. dfaScore = NO_DFA_SCORE;
  458. dfa = NULL;
  459. added = false;
  460. }
  461. void inherit(HqlRegexUniqueArray & target, const HqlRegexUniqueArray & source)
  462. {
  463. ForEachItemIn(idx, source)
  464. target.append(OLINK(source.item(idx)));
  465. }
  466. void HqlRegexExpr::calcDfaScore()
  467. {
  468. ForEachItemIn(idx, args)
  469. args.item(idx).calcDfaScore();
  470. if (querySubPattern())
  471. querySubPattern()->calcDfaScore();
  472. if (queryNamed())
  473. queryNamed()->calcDfaScore();
  474. //on entry dfaScore = NO_DFA_SCORE
  475. switch (getOperator())
  476. {
  477. case no_null:
  478. dfaScore = 0;
  479. break;
  480. case no_pat_const:
  481. dfaScore = expr->queryChild(0)->queryType()->getStringLen();
  482. break;
  483. case no_pat_anychar:
  484. dfaScore = 1;
  485. break;
  486. case no_pat_set:
  487. {
  488. unsigned score = 0;
  489. ForEachChild(idx, expr)
  490. {
  491. IHqlExpression * child = expr->queryChild(idx);
  492. switch (child->getOperator())
  493. {
  494. case no_range:
  495. {
  496. unsigned low = (unsigned)child->queryChild(0)->queryValue()->getIntValue();
  497. unsigned high = (unsigned)child->queryChild(1)->queryValue()->getIntValue();
  498. score = addWithoutOverflow(score, (high-low)+1);
  499. break;
  500. }
  501. case no_constant:
  502. score = addWithoutOverflow(score, 1);
  503. break;
  504. }
  505. }
  506. dfaScore = score;
  507. break;
  508. }
  509. case no_pat_repeat:
  510. if (isStandardRepeat())
  511. {
  512. unsigned argScore = args.item(0).dfaScore;
  513. if ((getRepeatMax() > 1) && (argScore != NO_DFA_SCORE))
  514. dfaScore = addWithoutOverflow(argScore, argScore);
  515. else
  516. dfaScore = argScore;
  517. }
  518. else if (!expr->hasProperty(minimalAtom))
  519. {
  520. unsigned max = getRepeatMax();
  521. unsigned namedDfaScore = queryNamed()->getDfaScore();
  522. if (max <= options.dfaRepeatMax)
  523. dfaScore = multiplyWithoutOverflow(max, namedDfaScore);
  524. }
  525. break;
  526. case no_pat_instance:
  527. if (!queryNamed()->isMatched)
  528. dfaScore = queryNamed()->getDfaScore();
  529. break;
  530. case no_pat_or:
  531. {
  532. unsigned totalScore = 0;
  533. ForEachItemIn(idx, args)
  534. {
  535. unsigned score = args.item(idx).dfaScore;
  536. if (score == NO_DFA_SCORE)
  537. {
  538. totalScore = NO_DFA_SCORE;
  539. break;
  540. }
  541. totalScore = addWithoutOverflow(totalScore, score);
  542. }
  543. dfaScore = totalScore;
  544. if (dfaScore == NO_DFA_SCORE)
  545. {
  546. //Work out if there are two or more entires which can be converted into a dfa, and if so combine them
  547. //Also potentially separate simple sting lists into a separate or, so we always generate them
  548. unsigned scoreCount = 0;
  549. unsigned stringListCount = 0;
  550. ForEachItemIn(iCount, args)
  551. {
  552. HqlRegexExpr & cur = args.item(iCount);
  553. if (cur.dfaScore != NO_DFA_SCORE)
  554. {
  555. scoreCount++;
  556. if (cur.isSimpleStringList())
  557. stringListCount++;
  558. }
  559. }
  560. if (scoreCount > 1)
  561. {
  562. HqlRegexExpr * newor = createRegexExpr(options, no_pat_or, NULL, caseSensitive);
  563. HqlRegexExpr * stringListOr = ((stringListCount > 1) && (scoreCount != stringListCount)) ? createRegexExpr(options, no_pat_or, NULL, caseSensitive) : NULL;
  564. unsigned totalScore = 0;
  565. unsigned stringListScore = 0;
  566. for (unsigned i =0; i < args.ordinality(); )
  567. {
  568. HqlRegexExpr & cur = args.item(i);
  569. unsigned score = cur.dfaScore;
  570. if (score != NO_DFA_SCORE)
  571. {
  572. if (stringListOr && cur.isSimpleStringList())
  573. {
  574. stringListScore = addWithoutOverflow(stringListScore, score);
  575. stringListOr->addOperand(&OLINK(cur));
  576. }
  577. else
  578. newor->addOperand(&OLINK(cur));
  579. totalScore = addWithoutOverflow(totalScore, score);
  580. args.remove(i);
  581. }
  582. else
  583. i++;
  584. }
  585. if (stringListOr)
  586. {
  587. stringListOr->dfaScore = stringListScore;
  588. newor->addOperand(stringListOr);
  589. }
  590. newor->dfaScore = totalScore;
  591. //add the dfa first - since it will probably be quickest
  592. args.add(*newor, 0);
  593. }
  594. }
  595. break;
  596. }
  597. case no_pat_follow:
  598. {
  599. //MORE: Should extract applicable subranges out of the sequences
  600. //MORE: This should multiple rather than add.
  601. dfaScore = 0;
  602. ForEachItemIn(idx, args)
  603. {
  604. unsigned score = args.item(idx).dfaScore;
  605. if (score == NO_DFA_SCORE)
  606. {
  607. dfaScore = NO_DFA_SCORE;
  608. break;
  609. }
  610. dfaScore = addWithoutOverflow(dfaScore, score);
  611. }
  612. if (dfaScore == NO_DFA_SCORE)
  613. {
  614. //Try and find ranges that are valid, and extract those into sub-elements.
  615. for (unsigned i =0; i < args.ordinality(); i++)
  616. {
  617. unsigned score = args.item(i).dfaScore;
  618. if (score != NO_DFA_SCORE)
  619. {
  620. unsigned max = args.ordinality();
  621. unsigned j;
  622. for (j=i+1; j < max; j++)
  623. {
  624. unsigned thisScore = args.item(j).dfaScore;
  625. if (thisScore == NO_DFA_SCORE)
  626. break;
  627. score = addWithoutOverflow(score, thisScore);
  628. }
  629. if (j != i+1)
  630. {
  631. HqlRegexExpr * follow = createRegexExpr(options, no_pat_follow, NULL, caseSensitive);
  632. for (unsigned k=i; k < j; k++)
  633. follow->addOperand(&OLINK(args.item(k)));
  634. follow->dfaScore = score;
  635. while (j != i)
  636. args.remove(--j);
  637. args.add(*follow, i);
  638. }
  639. }
  640. }
  641. }
  642. break;
  643. }
  644. }
  645. }
  646. void HqlRegexExpr::calculateNext()
  647. {
  648. //Dragon p138
  649. //if a concatenation (a,b), then all the trailing from (a) have leading(b) in their following set
  650. //if a repeat [max > 1] then all positions in leading(x) are also in the following list
  651. //Limited/minimal repeats aren't done the same way - so they aren't added in the same way
  652. //Because I am cheating the order is important - repeats need to be done first since they are greedy.
  653. switch (getOperator())
  654. {
  655. case no_pat_repeat:
  656. if (isStandardRepeat() && getRepeatMax() > 1)
  657. {
  658. //All the trailing elements have the leading elements as possible next.
  659. unsigned max = numTrailing();
  660. for (unsigned idx=0; idx < max; idx++)
  661. gatherLeading(queryTrailing(idx).following);
  662. }
  663. break;
  664. }
  665. ForEachItemIn(idx, args)
  666. args.item(idx).calculateNext();
  667. switch (getOperator())
  668. {
  669. case no_pat_follow:
  670. case no_pat_separator:
  671. {
  672. //Internally connect up following items within the no_pat_follow.
  673. unsigned max = args.ordinality();
  674. assertex(max);
  675. for (unsigned pairs=0; pairs<max-1; pairs++)
  676. {
  677. HqlRegexExpr * left = queryChild(pairs);
  678. for (unsigned other=pairs+1; other<max; other++)
  679. {
  680. HqlRegexExpr * right = queryChild(other);
  681. unsigned maxTrail = left->numTrailing();
  682. for (unsigned trailIdx=0; trailIdx<maxTrail; trailIdx++)
  683. {
  684. HqlRegexExpr & cur = left->queryTrailing(trailIdx);
  685. right->gatherLeading(cur.following);
  686. }
  687. if (!right->canBeNull())
  688. break;
  689. }
  690. }
  691. break;
  692. }
  693. }
  694. }
  695. #if 0
  696. //convert strings/unicode to correct kind depending on what is being searched, when the expr is built.
  697. UBool U_CALL_CONV noteUCharRange(const void * context, UChar32 start, UChar limit, UCharCategory type)
  698. {
  699. }
  700. void gatherRange(void * context, UCharCategory type)
  701. {
  702. u_enumCharTypes(noteUCharRange range, context);
  703. }
  704. #endif
  705. static bool canConsume(const ParseInformation & options, unsigned nextChar, unsigned matcherChar, bool caseSensitive)
  706. {
  707. if (nextChar == matcherChar)
  708. return true;
  709. if (matcherChar & RegexSpecialMask)
  710. {
  711. assertex(options.type != type_utf8);
  712. if (!(nextChar & RegexSpecialMask))
  713. {
  714. if (options.type != type_string)
  715. return isUnicodeMatch(matcherChar, nextChar);
  716. else
  717. return isAsciiMatch(matcherChar, nextChar);
  718. }
  719. //Should only occur if unicode.
  720. switch (matcherChar)
  721. {
  722. case RCCalnum:
  723. return (nextChar == RCCalpha) || (nextChar == RCClower) || (nextChar == RCCupper) || (nextChar == RCCdigit);
  724. case RCCalpha:
  725. return (nextChar == RCClower) || (nextChar == RCCupper);
  726. case RCCspace:
  727. return (nextChar == RCCblank);
  728. case RCCprint:
  729. return (nextChar == RCCalnum) || (nextChar == RCCalpha) || (nextChar == RCClower) || (nextChar == RCCupper) || (nextChar == RCCdigit) || (nextChar == RCCpunct) || (nextChar == RCCxdigit) || (nextChar == RCCgraph);
  730. case RCCgraph:
  731. return (nextChar == RCCalnum) || (nextChar == RCCalpha) || (nextChar == RCClower) || (nextChar == RCCupper) || (nextChar == RCCdigit) || (nextChar == RCCpunct) || (nextChar == RCCxdigit);
  732. case RCCxdigit:
  733. return (nextChar == RCCdigit);
  734. case RCCany:
  735. return true;
  736. }
  737. return false;
  738. }
  739. else if (nextChar & RegexSpecialMask)
  740. return false;
  741. if (caseSensitive || (options.type == type_utf8))
  742. return false;
  743. if (options.type == type_unicode)
  744. {
  745. //MORE: This needs improving for full folding.
  746. return u_foldCase(nextChar, U_FOLD_CASE_DEFAULT) == u_foldCase(matcherChar, U_FOLD_CASE_DEFAULT);
  747. }
  748. return (nextChar == tolower(matcherChar)) || (nextChar == toupper(matcherChar));
  749. }
  750. bool HqlRegexExpr::canConsume(unsigned nextChar)
  751. {
  752. switch (getOperator())
  753. {
  754. case no_pat_singlechar:
  755. return ::canConsume(options, nextChar, (unsigned)expr->queryValue()->getIntValue(), caseSensitive);
  756. case no_pat_utf8single:
  757. assertex(!(nextChar & RegexSpecialMask));
  758. return nextChar < 0x80;
  759. case no_pat_utf8lead:
  760. assertex(!(nextChar & RegexSpecialMask));
  761. return nextChar >= 0xc0;
  762. case no_pat_utf8follow:
  763. assertex(!(nextChar & RegexSpecialMask));
  764. return nextChar >= 0x80 && nextChar <= 0xbf;
  765. case no_pat_anychar:
  766. assertex(options.type != type_utf8);
  767. return true;
  768. case no_pat_set:
  769. {
  770. assertex(options.type != type_utf8);
  771. bool invert = expr->hasProperty(notAtom);
  772. ForEachChild(idx, expr)
  773. {
  774. IHqlExpression * child = expr->queryChild(idx);
  775. switch (child->getOperator())
  776. {
  777. case no_range:
  778. {
  779. unsigned low = (unsigned)child->queryChild(0)->queryValue()->getIntValue();
  780. unsigned high = (unsigned)child->queryChild(1)->queryValue()->getIntValue();
  781. if (!(nextChar & RegexSpecialMask))
  782. {
  783. if (!caseSensitive)
  784. {
  785. if (options.type == type_unicode)
  786. {
  787. //MORE: Improved unicode
  788. if (u_foldCase(nextChar, U_FOLD_CASE_DEFAULT) >= u_foldCase(low, U_FOLD_CASE_DEFAULT) &&
  789. u_foldCase(nextChar, U_FOLD_CASE_DEFAULT) <= u_foldCase(high, U_FOLD_CASE_DEFAULT))
  790. return !invert;
  791. }
  792. else
  793. {
  794. if (nextChar >= (unsigned)tolower(low) && nextChar <= (unsigned)tolower(high))
  795. return !invert;
  796. if (nextChar >= (unsigned)toupper(low) && nextChar <= (unsigned)toupper(high))
  797. return !invert;
  798. }
  799. }
  800. else
  801. {
  802. if (nextChar >= low && nextChar <= high)
  803. return !invert;
  804. }
  805. }
  806. break;
  807. }
  808. case no_constant:
  809. {
  810. unsigned value = (unsigned)child->queryValue()->getIntValue();
  811. if (::canConsume(options, nextChar, value, caseSensitive))
  812. return !invert;
  813. break;
  814. }
  815. case no_attr:
  816. case no_attr_expr:
  817. case no_attr_link:
  818. break;
  819. default:
  820. UNIMPLEMENTED;
  821. }
  822. }
  823. return invert;
  824. }
  825. case no_pat_endpattern:
  826. return false;
  827. default:
  828. UNIMPLEMENTED;
  829. }
  830. }
  831. void HqlRegexExpr::gatherConsumeSymbols(SymbolArray & symbols)
  832. {
  833. switch (getOperator())
  834. {
  835. case no_pat_singlechar:
  836. {
  837. unsigned charValue = (unsigned)expr->queryValue()->getIntValue();
  838. if (!caseSensitive && (options.type != type_utf8))
  839. {
  840. if (options.type == type_unicode)
  841. {
  842. //MORE: Unicode - can you have several values, what about case conversion?
  843. //MORE: String might need expanding to ('a'|'A')('ss'|'SS'|'B') or something similar.
  844. symbols.addUnique(u_tolower(charValue));
  845. symbols.addUnique(u_toupper(charValue));
  846. }
  847. else
  848. {
  849. symbols.addUnique(tolower(charValue));
  850. symbols.addUnique(toupper(charValue));
  851. }
  852. }
  853. else
  854. symbols.addUnique(charValue);
  855. break;
  856. }
  857. case no_pat_anychar:
  858. assertex(options.type != type_utf8);
  859. if (options.type == type_unicode)
  860. symbols.addUnique(RCCany);
  861. else
  862. symbols.addUniqueRange(0, 255);
  863. return;
  864. case no_pat_endpattern:
  865. return;
  866. case no_pat_set:
  867. assertex(options.type == type_string);
  868. if (options.type == type_unicode)
  869. {
  870. //MORE: Need some kind of implementation for unicode - although invert and ranges may not be possible.
  871. if (expr->hasProperty(notAtom))
  872. throwError(HQLERR_DfaTooComplex);
  873. ForEachChild(idx, expr)
  874. {
  875. IHqlExpression * child = expr->queryChild(idx);
  876. switch (child->getOperator())
  877. {
  878. case no_range:
  879. {
  880. unsigned low = (unsigned)child->queryChild(0)->queryValue()->getIntValue();
  881. unsigned high = (unsigned)child->queryChild(1)->queryValue()->getIntValue();
  882. if (!caseSensitive)
  883. {
  884. //MORE: This really doesn't work very well - I'm not even sure what it means...
  885. symbols.addUniqueRange(u_tolower(low), u_tolower(high));
  886. symbols.addUniqueRange(u_toupper(low), u_toupper(high));
  887. }
  888. else
  889. symbols.addUniqueRange(low, high);
  890. break;
  891. }
  892. case no_constant:
  893. {
  894. unsigned value = (unsigned)child->queryValue()->getIntValue();
  895. if (caseSensitive || (value & RegexSpecialMask))
  896. symbols.addUnique(value);
  897. else
  898. {
  899. symbols.addUnique(u_tolower(value));
  900. symbols.addUnique(u_toupper(value));
  901. }
  902. break;
  903. }
  904. case no_attr:
  905. case no_attr_expr:
  906. case no_attr_link:
  907. break;
  908. default:
  909. UNIMPLEMENTED;
  910. }
  911. }
  912. }
  913. else
  914. {
  915. //This is probably the easiest way to cope with inverted sets and all other complications.
  916. for (unsigned i = 0; i < 256; i++)
  917. if (canConsume(i))
  918. symbols.addUnique(i);
  919. }
  920. return;
  921. case no_pat_utf8single:
  922. {
  923. for (unsigned i = 0; i < 0x80; i++)
  924. symbols.addUnique(i);
  925. break;
  926. }
  927. case no_pat_utf8lead:
  928. {
  929. for (unsigned i = 0xc0; i < 0x100; i++)
  930. symbols.addUnique(i);
  931. break;
  932. }
  933. case no_pat_utf8follow:
  934. {
  935. for (unsigned i = 0x80; i < 0xc0; i++)
  936. symbols.addUnique(i);
  937. break;
  938. }
  939. default:
  940. throwError1(HQLERR_BadDfaOperator, getOpString(getOperator()));
  941. }
  942. }
  943. void HqlRegexExpr::cleanup()
  944. {
  945. if (cleaned)
  946. return;
  947. cleaned = true;
  948. //kill anything that could have a loop.
  949. ForEachItemIn(i0, args)
  950. args.item(i0).cleanup();
  951. if (querySubPattern())
  952. querySubPattern()->cleanup();
  953. if (created)
  954. created->dispose();
  955. following.kill();
  956. args.kill();
  957. }
  958. HqlRegexExpr * HqlRegexExpr::clone()
  959. {
  960. assertex(!created && !analysed);
  961. HqlRegexExpr * cloned = createRegexExpr(options, op, expr, caseSensitive);
  962. ForEachItemIn(idx, args)
  963. cloned->args.append(*args.item(idx).clone());
  964. cloned->setNamed(queryNamed());
  965. cloned->setSubPattern(querySubPattern());
  966. return cloned;
  967. }
  968. void HqlRegexExpr::connectRegex()
  969. {
  970. if (connected)
  971. return;
  972. connected = true;
  973. ForEachItemIn(idx, args)
  974. args.item(idx).connectRegex();
  975. if (created)
  976. {
  977. ForEachItemIn(idx2, following)
  978. created->addLink(following.item(idx2).created);
  979. HqlNamedRegex * named = queryNamed();
  980. if (named && named->created && !named->noGenerate)
  981. created->setBody(named->created);
  982. if (querySubPattern())
  983. created->setSubPattern(querySubPattern()->queryRootPattern());
  984. }
  985. }
  986. HqlRegexExpr * HqlRegexExpr::createDFAs(RegexContext & ctx)
  987. {
  988. if (createDFA)
  989. {
  990. OwnedHqlExpr searchExpr = createValue(no_pat_dfa, makePatternType(), createUniqueId());
  991. HqlNamedRegex * newNamed = new HqlNamedRegex(searchExpr, NULL, searchExpr, no_pat_dfa, caseSensitive, false);
  992. ctx.named.append(*newNamed);
  993. newNamed->setRegexOwn(expandAsDFA());
  994. HqlRegexExpr * dfa = createRegexExpr(options, no_pat_dfa, NULL, caseSensitive);
  995. dfa->setNamed(newNamed);
  996. dfa->dfaScore = dfaScore;
  997. //MORE: Need to save the original as a *named/subPattern* attribute in case conversion to a DFA fails
  998. return dfa;
  999. }
  1000. unsigned max = args.ordinality();
  1001. unsigned idx;
  1002. for (idx = 0; idx < max; idx++)
  1003. {
  1004. HqlRegexExpr & cur = args.item(idx);
  1005. HqlRegexExpr * transformed = cur.createDFAs(ctx);
  1006. args.replace(*transformed, idx);
  1007. if (transformed->getOperator() == no_pat_dfa)
  1008. {
  1009. if ((idx != 0) && (idx+1 != max) && (getOperator() == no_pat_follow))
  1010. {
  1011. if ((args.item(idx-1).getOperator() == no_pat_begintoken) &&
  1012. (args.item(idx+1).getOperator() == no_pat_endtoken))
  1013. {
  1014. transformed->addOperand(&OLINK(args.item(idx-1)));
  1015. args.remove(idx+1);
  1016. args.remove(idx-1);
  1017. idx--;
  1018. max -= 2;
  1019. }
  1020. }
  1021. }
  1022. }
  1023. if (querySubPattern())
  1024. querySubPattern()->createDFAs(ctx);
  1025. if (queryNamed())
  1026. queryNamed()->createDFAs(ctx);
  1027. return LINK(this);
  1028. }
  1029. HqlRegexExpr * HqlRegexExpr::expandAsRepeatedDFA(unsigned count)
  1030. {
  1031. if (count == 0)
  1032. return createRegexExpr(options, no_null, NULL, caseSensitive);
  1033. if (count == 1)
  1034. return expandAsDFA();
  1035. HqlRegexExpr * cloned = createRegexExpr(options, no_pat_follow, NULL, caseSensitive);
  1036. for (unsigned i=0; i < count; i++)
  1037. cloned->args.append(*expandAsDFA());
  1038. return cloned;
  1039. }
  1040. HqlRegexExpr * HqlRegexExpr::expandAsDFA()
  1041. {
  1042. assertex(!created && !analysed);
  1043. switch (getOperator())
  1044. {
  1045. case no_pat_const:
  1046. return expandStringAsChars(expr, options, caseSensitive);
  1047. case no_pat_instance:
  1048. return queryNamed()->def->expandAsDFA();
  1049. case no_pat_or:
  1050. case no_pat_follow:
  1051. case no_null:
  1052. case no_pat_singlechar:
  1053. break;
  1054. case no_pat_anychar:
  1055. if (options.type == type_utf8)
  1056. {
  1057. // convert to low | follow(lead, tail+);
  1058. Owned<HqlRegexExpr> orRegexExpr = createRegexExpr(options, no_pat_or, NULL, caseSensitive);
  1059. orRegexExpr->addOperand(createRegexExpr(options, no_pat_utf8single, NULL, caseSensitive));
  1060. Owned<HqlRegexExpr> followRegexExpr = createRegexExpr(options, no_pat_follow, NULL, caseSensitive);
  1061. followRegexExpr->addOperand(createRegexExpr(options, no_pat_utf8lead, NULL, caseSensitive));
  1062. OwnedHqlExpr trailExpr = createValue(no_pat_utf8follow, makePatternType());
  1063. Owned<HqlRegexExpr> trailRegexExpr = createRegexExpr(options, no_pat_utf8follow, NULL, caseSensitive);
  1064. OwnedHqlExpr repeatExpr = createValue(no_pat_repeat, makePatternType(), LINK(trailExpr), createConstantOne(), createValue(no_any, makeNullType()));
  1065. Owned<HqlRegexExpr> repeatRegexExpr = createRegexExpr(options, no_pat_repeat, repeatExpr, caseSensitive);
  1066. repeatRegexExpr->addOperand(trailRegexExpr.getClear());
  1067. followRegexExpr->addOperand(repeatRegexExpr.getClear());
  1068. orRegexExpr->addOperand(followRegexExpr.getClear());
  1069. return orRegexExpr.getClear();
  1070. }
  1071. break;
  1072. case no_pat_set:
  1073. if (options.type == type_utf8)
  1074. {
  1075. throwUnexpected();
  1076. //expand set values...
  1077. // return low | follow(lead, tail+);
  1078. }
  1079. break;
  1080. case no_pat_dfa:
  1081. return queryNamed()->def->expandAsDFA();
  1082. case no_pat_repeat:
  1083. {
  1084. if (isStandardRepeat())
  1085. break;
  1086. unsigned min = getRepeatMin();
  1087. unsigned max = getRepeatMax();
  1088. if (min == max)
  1089. return queryNamed()->def->expandAsRepeatedDFA(min);
  1090. HqlRegexExpr * cloned = createRegexExpr(options, no_pat_or, NULL, caseSensitive);
  1091. for (unsigned i=min; i <= max; i++)
  1092. cloned->args.append(*queryNamed()->def->expandAsRepeatedDFA(i));
  1093. return cloned;
  1094. }
  1095. default:
  1096. UNIMPLEMENTED;
  1097. }
  1098. HqlRegexExpr * cloned = createRegexExpr(options, op, expr, caseSensitive);
  1099. ForEachItemIn(idx, args)
  1100. cloned->args.append(*args.item(idx).expandAsDFA());
  1101. assertex(!queryNamed());
  1102. assertex(!querySubPattern());
  1103. return cloned;
  1104. }
  1105. HqlRegexExpr * HqlRegexExpr::expandNamedSymbols()
  1106. {
  1107. ForEachItemIn(idx, args)
  1108. args.replace(*args.item(idx).expandNamedSymbols(), idx);
  1109. if (querySubPattern())
  1110. querySubPattern()->expandNamedSymbols();
  1111. if (queryNamed())
  1112. queryNamed()->expandNamedSymbols();
  1113. switch (getOperator())
  1114. {
  1115. case no_pat_instance:
  1116. if (queryNamed()->queryExpandInline())
  1117. {
  1118. queryNamed()->removeUse();
  1119. return queryNamed()->def->clone();
  1120. }
  1121. break;
  1122. case no_pat_follow:
  1123. {
  1124. ForEachItemIn(idx, args)
  1125. {
  1126. node_operator op = args.item(idx).getOperator();
  1127. switch (op)
  1128. {
  1129. //Remove begin_token/end_token around the following, otherwise
  1130. //we might get too many separators which may be non-optional
  1131. case no_pat_first:
  1132. case no_pat_last:
  1133. case no_penalty:
  1134. case no_pat_x_before_y:
  1135. case no_pat_before_y:
  1136. case no_pat_x_after_y:
  1137. case no_pat_after_y:
  1138. case no_pat_guard:
  1139. if ((idx > 0) && args.item(idx-1).getOperator() == no_pat_begintoken)
  1140. {
  1141. assertex(args.item(idx+1).getOperator() == no_pat_endtoken);
  1142. args.remove(idx+1);
  1143. args.remove(idx-1);
  1144. if (args.isItem(idx) && (args.item(idx).getOperator() == no_pat_separator))
  1145. args.remove(idx);
  1146. }
  1147. break;
  1148. }
  1149. }
  1150. break;
  1151. }
  1152. }
  1153. return LINK(this);
  1154. }
  1155. HqlRegexExpr * HqlRegexExpr::expandRecursion(RegexContext & ctx, HqlNamedRegex * self)
  1156. {
  1157. ForEachItemIn(idx, args)
  1158. args.replace(*args.item(idx).expandRecursion(ctx, self), idx);
  1159. if (querySubPattern())
  1160. querySubPattern()->expandRecursion(ctx, self);
  1161. if (queryNamed())
  1162. queryNamed()->expandRecursion(ctx, self);
  1163. HqlNamedRegex * replacement = NULL;
  1164. switch (getOperator())
  1165. {
  1166. case no_self:
  1167. replacement = self;
  1168. break;
  1169. case no_pat_use:
  1170. assertex(expr->queryChild(0)->queryValue());
  1171. replacement = ctx.queryDefine(expr->queryChild(0), caseSensitive);
  1172. break;
  1173. case no_define:
  1174. return LINK(&args.item(0));
  1175. }
  1176. if (replacement)
  1177. {
  1178. replacement->expandRecursion(ctx, self);
  1179. replacement->addRecursiveUse();
  1180. HqlRegexExpr * instance = createRegexExpr(options, no_pat_instance, NULL, caseSensitive);
  1181. instance->setNamed(replacement);
  1182. return instance;
  1183. }
  1184. return LINK(this);
  1185. }
  1186. void HqlRegexExpr::generateDFA(IDfaPattern * pattern)
  1187. {
  1188. //Estimate the number of transitions to avoid lots of reallocs.
  1189. unsigned numTransitions = 0;
  1190. {
  1191. ForEachItemIn(idx, dfa->states)
  1192. {
  1193. HqlDfaState & cur = dfa->states.item(idx);
  1194. unsigned min = 255;
  1195. unsigned max = 0;
  1196. ForEachItemIn(idx2, cur.transitions)
  1197. {
  1198. HqlDfaTransition & curTransition = cur.transitions.item(idx2);
  1199. if (curTransition.code < min) min = curTransition.code;
  1200. if (curTransition.code > max) max = curTransition.code;
  1201. }
  1202. if (min <= max)
  1203. numTransitions += (max-min)+1;
  1204. }
  1205. }
  1206. pattern->init(dfa->states.ordinality(), numTransitions);
  1207. ForEachItemIn(idx, dfa->states)
  1208. {
  1209. HqlDfaState & cur = dfa->states.item(idx);
  1210. assertex(cur.id == idx);
  1211. pattern->beginState(cur.id);
  1212. ForEachItemIn(idx, cur.position)
  1213. {
  1214. HqlRegexExpr & curExpr = cur.position.item(idx);
  1215. if (curExpr.getOperator() == no_pat_endpattern)
  1216. pattern->setStateAccept(curExpr.getAcceptId());
  1217. }
  1218. ForEachItemIn(idx2, cur.transitions)
  1219. {
  1220. HqlDfaTransition & curTransition = cur.transitions.item(idx2);
  1221. pattern->addTransition(curTransition.code, curTransition.next->id);
  1222. }
  1223. pattern->endState();
  1224. }
  1225. pattern->finished();
  1226. }
  1227. void HqlRegexExpr::generateRegex(GenerateRegexCtx & ctx)
  1228. {
  1229. ForEachItemIn(idx, args)
  1230. args.item(idx).generateRegex(ctx);
  1231. assertex(!created);
  1232. if (queryNamed())
  1233. queryNamed()->generateRegex(ctx);
  1234. if (querySubPattern())
  1235. querySubPattern()->generateRegex(ctx);
  1236. switch (getOperator())
  1237. {
  1238. case no_null:
  1239. case no_pat_beginpattern:
  1240. created.setown(new RegexNullPattern);
  1241. break;
  1242. case no_pat_beginrecursive:
  1243. created.setown(new RegexRecursivePattern);
  1244. break;
  1245. case no_pat_beginseparator:
  1246. created.setown(new RegexBeginSeparatorPattern);
  1247. break;
  1248. case no_pat_endseparator:
  1249. created.setown(new RegexEndSeparatorPattern);
  1250. break;
  1251. case no_pat_endrecursive:
  1252. created.setown(new RegexEndRecursivePattern);
  1253. break;
  1254. case no_pat_instance:
  1255. created.setown(new RegexNamedPattern);
  1256. break;
  1257. case no_pat_begincheck:
  1258. case no_pat_beginvalidate:
  1259. created.setown(new RegexBeginCheckPattern);
  1260. break;
  1261. case no_pat_endcheckin:
  1262. {
  1263. bool stripSeparator = ctx.info.addedSeparators && (expr->queryType()->getTypeCode() != type_pattern);
  1264. created.setown(new RegexCheckInPattern(expr->hasProperty(notAtom), stripSeparator));
  1265. break;
  1266. }
  1267. case no_pat_endchecklength:
  1268. {
  1269. unsigned minLength = 0;
  1270. unsigned maxLength = PATTERN_UNLIMITED_LENGTH;
  1271. getCheckRange(expr->queryChild(1), minLength, maxLength, ctx.info.charSize);
  1272. bool stripSeparator = ctx.info.addedSeparators && (expr->queryType()->getTypeCode() != type_pattern);
  1273. created.setown(new RegexCheckLengthPattern(expr->hasProperty(notAtom), stripSeparator, minLength, maxLength));
  1274. break;
  1275. }
  1276. case no_pat_endvalidate:
  1277. {
  1278. unsigned idx = ctx.regex.getValidatorIndex(expr);
  1279. assertex(idx != NotFound);
  1280. ValidateKind validatorKind = getValidateKind(ctx.regex.queryValidateExpr(expr));
  1281. bool stripSeparator = ctx.info.addedSeparators && (expr->queryType()->getTypeCode() != type_pattern);
  1282. switch (ctx.info.inputFormat())
  1283. {
  1284. case NlpUnicode:
  1285. if (validatorKind != ValidateIsString)
  1286. created.setown(new RegexValidateUniAsUniPattern(stripSeparator, idx));
  1287. else
  1288. created.setown(new RegexValidateUniAsAscPattern(stripSeparator, idx));
  1289. break;
  1290. case NlpUtf8:
  1291. if (validatorKind != ValidateIsString)
  1292. created.setown(new RegexValidateUtf8AsUniPattern(stripSeparator, idx));
  1293. else
  1294. created.setown(new RegexValidateUtf8AsAscPattern(stripSeparator, idx));
  1295. break;
  1296. case NlpAscii:
  1297. if (validatorKind != ValidateIsUnicode)
  1298. created.setown(new RegexValidateAscAsAscPattern(stripSeparator, idx));
  1299. else
  1300. created.setown(new RegexValidateAscAsUniPattern(stripSeparator, idx));
  1301. break;
  1302. }
  1303. break;
  1304. }
  1305. case no_pat_begintoken:
  1306. created.setown(new RegexBeginTokenPattern);
  1307. break;
  1308. case no_pat_endtoken:
  1309. created.setown(new RegexEndTokenPattern);
  1310. break;
  1311. case no_pat_x_before_y:
  1312. case no_pat_before_y:
  1313. created.setown(new RegexAssertNextPattern(expr->hasProperty(notAtom)));
  1314. break;
  1315. case no_pat_x_after_y:
  1316. case no_pat_after_y:
  1317. {
  1318. unsigned minSize = limitedMult(querySubPattern()->limit.minLength, ctx.info.charSize);
  1319. unsigned maxSize = limitedMult(querySubPattern()->limit.maxLength, ctx.info.charSize);
  1320. created.setown(new RegexAssertPrevPattern(expr->hasProperty(notAtom), minSize, maxSize));
  1321. break;
  1322. }
  1323. case no_pat_first:
  1324. created.setown(new RegexStartPattern);
  1325. break;
  1326. case no_pat_last:
  1327. created.setown(new RegexFinishPattern);
  1328. break;
  1329. case no_pat_anychar:
  1330. created.setown(new RegexAnyCharPattern);
  1331. break;
  1332. case no_penalty:
  1333. {
  1334. int penalty = 1;
  1335. if (expr->numChildren() > 0)
  1336. penalty = (int)expr->queryChild(0)->queryValue()->getIntValue();
  1337. created.setown(new RegexPenaltyPattern(penalty));
  1338. }
  1339. break;
  1340. case no_pat_set:
  1341. {
  1342. RegexSetBasePattern * pattern;
  1343. if (ctx.info.type != type_string)
  1344. pattern = new RegexUnicodeSetPattern(caseSensitive);
  1345. else if (caseSensitive)
  1346. pattern = new RegexAsciiSetPattern;
  1347. else
  1348. pattern = new RegexAsciiISetPattern;
  1349. created.setown(pattern);
  1350. if (expr->hasProperty(notAtom))
  1351. pattern->setInvert(true);
  1352. ForEachChild(idx, expr)
  1353. {
  1354. IHqlExpression * child = expr->queryChild(idx);
  1355. switch (child->getOperator())
  1356. {
  1357. case no_range:
  1358. pattern->addRange((unsigned)child->queryChild(0)->queryValue()->getIntValue(), (unsigned)child->queryChild(1)->queryValue()->getIntValue());
  1359. break;
  1360. case no_constant:
  1361. pattern->addRange((unsigned)child->queryValue()->getIntValue(), (unsigned)child->queryValue()->getIntValue());
  1362. break;
  1363. case no_attr:
  1364. case no_attr_expr:
  1365. case no_attr_link:
  1366. break;
  1367. default:
  1368. UNIMPLEMENTED;
  1369. }
  1370. }
  1371. break;
  1372. }
  1373. case no_pat_const:
  1374. {
  1375. IValue * value = expr->queryChild(0)->queryValue();
  1376. Owned<IValue> castValue = getCastConstant(value, ctx.info.type);
  1377. unsigned len = castValue->queryType()->getStringLen();
  1378. switch (ctx.info.type)
  1379. {
  1380. case type_unicode:
  1381. {
  1382. const UChar * data = (const UChar *)castValue->queryValue();
  1383. if (caseSensitive)
  1384. created.setown(new RegexUnicodePattern(len, data));
  1385. else
  1386. created.setown(new RegexUnicodeIPattern(len, data));
  1387. break;
  1388. }
  1389. case type_utf8:
  1390. {
  1391. const char * data = (const char *)castValue->queryValue();
  1392. if (caseSensitive)
  1393. created.setown(new RegexUtf8Pattern(len, data));
  1394. else
  1395. created.setown(new RegexUtf8IPattern(len, data));
  1396. break;
  1397. }
  1398. case type_string:
  1399. {
  1400. const char * data = (const char *)castValue->queryValue();
  1401. if (caseSensitive)
  1402. created.setown(new RegexAsciiPattern(len, data));
  1403. else
  1404. created.setown(new RegexAsciiIPattern(len, data));
  1405. break;
  1406. }
  1407. }
  1408. break;
  1409. }
  1410. case no_pat_or:
  1411. case no_pat_follow:
  1412. case no_pat_separator:
  1413. //Nothing is generated for these....
  1414. break;
  1415. case no_pat_dfa:
  1416. {
  1417. RegexDfaPattern * pattern;
  1418. bool isToken = false;
  1419. HqlRegexExpr * child = queryChild(0);
  1420. if (child && child->getOperator() == no_pat_begintoken)
  1421. isToken = true;
  1422. if (options.type == type_unicode)
  1423. {
  1424. throwUnexpected();
  1425. pattern = new RegexUnicodeDfaPattern;
  1426. }
  1427. else
  1428. pattern = new RegexAsciiDfaPattern(isToken);
  1429. created.setown(pattern);
  1430. Owned<IDfaPattern> builder = pattern->createBuilder();
  1431. generateDFA(builder);
  1432. }
  1433. break;
  1434. case no_pat_repeat:
  1435. if (!isStandardRepeat())
  1436. {
  1437. if (expr->queryChild(0)->getOperator() == no_pat_anychar)
  1438. {
  1439. created.setown(new RegexRepeatAnyPattern(getRepeatMin(), getRepeatMax(), expr->hasProperty(minimalAtom)));
  1440. queryNamed()->noGenerate = true;
  1441. }
  1442. else
  1443. created.setown(new RegexRepeatPattern(getRepeatMin(), getRepeatMax(), !expr->hasProperty(minimalAtom)));
  1444. }
  1445. break;
  1446. case no_pat_endpattern:
  1447. switch (ctx.namedKind)
  1448. {
  1449. case no_pat_instance:
  1450. case no_pat_repeat:
  1451. created.setown(new RegexEndNestedPattern);
  1452. break;
  1453. case no_pat_checkin:
  1454. created.setown(new RegexDonePattern);
  1455. break;
  1456. case no_parse:
  1457. created.setown(new RegexDonePattern);
  1458. break;
  1459. default:
  1460. UNIMPLEMENTED;
  1461. }
  1462. break;
  1463. default:
  1464. UNIMPLEMENTED;
  1465. }
  1466. }
  1467. unsigned HqlRegexExpr::getAcceptId()
  1468. {
  1469. //Overloaded, and a bit nasty, but will do for the moment....
  1470. if (dfaScore == NO_DFA_SCORE)
  1471. return 99;
  1472. return dfaScore;
  1473. }
  1474. unsigned HqlRegexExpr::getRepeatMin()
  1475. {
  1476. return ::getRepeatMin(expr);
  1477. }
  1478. unsigned HqlRegexExpr::getRepeatMax()
  1479. {
  1480. return ::getRepeatMax(expr);
  1481. }
  1482. bool HqlRegexExpr::isStandardRepeat()
  1483. {
  1484. if (::isStandardRepeat(expr))
  1485. {
  1486. if (options.expandRepeatAnyAsDfa || expr->queryChild(0)->getOperator() != no_pat_anychar)
  1487. return true;
  1488. }
  1489. return false;
  1490. }
  1491. HqlRegexExpr * HqlRegexExpr::insertSeparators(IHqlExpression * separator, RegexContext * ctx)
  1492. {
  1493. switch (getOperator())
  1494. {
  1495. case no_pat_follow:
  1496. {
  1497. ForEachItemInRev(idx, args)
  1498. {
  1499. HqlRegexExpr & cur = args.item(idx);
  1500. if (cur.getOperator() == no_pat_endtoken)
  1501. {
  1502. if (args.item(idx-1).getOperator() != no_pat_last)
  1503. {
  1504. //Separators are slightly weird. Because they are implicit, the whole thing should
  1505. //be optional (unlike a name where just the contents are optional).
  1506. //Should probably remove the optionality from the separator's value, and
  1507. //put it on the surrounding separator instead.
  1508. HqlRegexExpr * sepRegex = createRegexExpr(options, no_pat_separator, NULL, caseSensitive);
  1509. sepRegex->addOperand(createRegexExpr(options, no_pat_beginseparator, NULL, caseSensitive));
  1510. sepRegex->addOperand(ctx->createStructure(separator, ctx->isCaseSensitive()));
  1511. sepRegex->addOperand(createRegexExpr(options, no_pat_endseparator, NULL, caseSensitive));
  1512. args.add(*sepRegex, idx+1);
  1513. }
  1514. }
  1515. }
  1516. break;
  1517. }
  1518. }
  1519. ForEachChild(idx, this)
  1520. {
  1521. replaceOperand(queryChild(idx)->insertSeparators(separator, ctx), idx);
  1522. }
  1523. return LINK(this);
  1524. }
  1525. bool HqlRegexExpr::isWorthConvertingToDFA()
  1526. {
  1527. switch (getOperator())
  1528. {
  1529. case no_pat_or: case no_pat_repeat:
  1530. case no_pat_follow:
  1531. return true;
  1532. }
  1533. ForEachItemIn(idx, args)
  1534. if (args.item(idx).isWorthConvertingToDFA())
  1535. return true;
  1536. return false;
  1537. }
  1538. bool HqlRegexExpr::isSimpleStringList()
  1539. {
  1540. switch (getOperator())
  1541. {
  1542. case no_pat_or:
  1543. case no_pat_case:
  1544. case no_pat_nocase:
  1545. break;
  1546. case no_pat_const:
  1547. return true;
  1548. default:
  1549. return false;
  1550. }
  1551. ForEachItemIn(idx, args)
  1552. if (!args.item(idx).isSimpleStringList())
  1553. return false;
  1554. return true;
  1555. }
  1556. void HqlRegexExpr::markDFAs(unsigned complexity)
  1557. {
  1558. if (dfaScore != NO_DFA_SCORE)
  1559. {
  1560. //Don't convert instances - convert the definition so it can be reused.
  1561. //and if not worth converting, then children won't be either.
  1562. if (getOperator() != no_pat_instance)
  1563. {
  1564. if (dfaScore <= complexity)
  1565. {
  1566. createDFA = isWorthConvertingToDFA();
  1567. return;
  1568. }
  1569. else if (isSimpleStringList())
  1570. {
  1571. createDFA = true;
  1572. return;
  1573. }
  1574. }
  1575. }
  1576. ForEachItemIn(idx, args)
  1577. args.item(idx).markDFAs(complexity);
  1578. if (queryNamed())
  1579. queryNamed()->markDFAs(complexity);
  1580. if (querySubPattern())
  1581. querySubPattern()->markDFAs(complexity);
  1582. }
  1583. HqlRegexExpr * HqlRegexExpr::mergeCreateSets()
  1584. {
  1585. ForEachItemIn(idx, args)
  1586. replaceOperand(args.item(idx).mergeCreateSets(), idx);
  1587. if (getOperator() == no_pat_or)
  1588. {
  1589. unsigned singleCount = 0;
  1590. unsigned setCount = 0;
  1591. unsigned nullCount = 0;
  1592. HqlExprArray setArgs;
  1593. HqlRegexExprArray newArgs;
  1594. ForEachItemIn(idx, args)
  1595. {
  1596. HqlRegexExpr * cur = &args.item(idx);
  1597. bool curIsOptional = false;
  1598. if ((cur->getOperator() == no_pat_repeat) && (cur->getRepeatMin() == 0) && (cur->getRepeatMax() == 1))
  1599. {
  1600. curIsOptional = true;
  1601. cur = cur->queryChild(0);
  1602. }
  1603. if (cur->caseSensitive == caseSensitive)
  1604. {
  1605. switch (cur->getOperator())
  1606. {
  1607. case no_null:
  1608. nullCount++;
  1609. break;
  1610. case no_pat_set:
  1611. {
  1612. setCount++;
  1613. ForEachChild(iset, cur->expr)
  1614. {
  1615. IHqlExpression * child = cur->expr->queryChild(iset);
  1616. if (setArgs.find(*child) == NotFound)
  1617. setArgs.append(*LINK(child));
  1618. }
  1619. if (curIsOptional) nullCount++;
  1620. break;
  1621. }
  1622. case no_pat_const:
  1623. {
  1624. ITypeInfo * type = cur->expr->queryChild(0)->queryType();
  1625. unsigned len = type->getStringLen();
  1626. if (len == 0)
  1627. nullCount++;
  1628. else if (len == 1)
  1629. {
  1630. const void * value = cur->expr->queryChild(0)->queryValue()->queryValue();
  1631. unsigned nextValue;
  1632. if (type->getTypeCode() == type_utf8)
  1633. nextValue = rtlUtf8Char(value);
  1634. else if (isUnicodeType(type))
  1635. nextValue = *(UChar *)value;
  1636. else
  1637. nextValue = *(unsigned char *)value;
  1638. OwnedHqlExpr nextExpr = createConstant((int)nextValue);
  1639. if (setArgs.find(*nextExpr) == NotFound)
  1640. setArgs.append(*nextExpr.getClear());
  1641. singleCount++;
  1642. if (curIsOptional) nullCount++;
  1643. }
  1644. else
  1645. newArgs.append(*LINK(cur));
  1646. break;
  1647. }
  1648. default:
  1649. newArgs.append(*LINK(cur));
  1650. break;
  1651. }
  1652. }
  1653. else
  1654. newArgs.append(*LINK(cur));
  1655. }
  1656. if ((setCount > 1) || (setCount == 1 && singleCount > 0) || (singleCount > 1))
  1657. {
  1658. OwnedHqlExpr newSetExpr = createValue(no_pat_set, makePatternType(), setArgs);
  1659. if (nullCount)
  1660. newSetExpr.setown(createValue(no_pat_repeat, makePatternType(), newSetExpr.getClear(), createConstant(0), createConstantOne()));
  1661. HqlRegexExpr * newSetRegex = createRegexExpr(options, newSetExpr, caseSensitive);
  1662. if (newArgs.ordinality() == 0)
  1663. return newSetRegex;
  1664. args.kill();
  1665. ForEachItemIn(idx, newArgs)
  1666. args.append(OLINK(newArgs.item(idx)));
  1667. args.append(*newSetRegex);
  1668. }
  1669. }
  1670. return LINK(this);
  1671. }
  1672. #if 0
  1673. HqlRegexExpr * HqlRegexExpr::removeTrivialInstances()
  1674. {
  1675. node_operator op = expr->getOperator();
  1676. switch (op)
  1677. {
  1678. case no_pat_instance:
  1679. {
  1680. IHqlExpression * def = expr->queryChild(0);
  1681. if (!queryNamed()->isMatched && def->getOperator() == no_pat_instance)
  1682. {
  1683. queryNamed()->removeUse();
  1684. return
  1685. #if 0
  1686. //Do this later - recursion means we can't do it yet
  1687. //Optimization whilst building the tree. If a named symbol is just a definition of another named symbol
  1688. //and this named symbol isn't matched explicitly, then expand it.
  1689. if (!isMatched(def) && def->getOperator() == no_pat_instance)
  1690. return createStructure(def);
  1691. else
  1692. }
  1693. }
  1694. }
  1695. }
  1696. #endif
  1697. #endif
  1698. //---------------------------------------------------------------------------
  1699. void HqlSimpleRegexExpr::analyseNullLeadTrail()
  1700. {
  1701. if (analysed)
  1702. return;
  1703. analysed = true;
  1704. switch (getOperator())
  1705. {
  1706. case no_null:
  1707. limit.minLength = 0;
  1708. limit.maxLength = 0;
  1709. break;
  1710. case no_pat_beginrecursive:
  1711. limit.minLength = 0;
  1712. limit.maxLength = 0;
  1713. limit.containsAssertion = true;
  1714. break;
  1715. case no_pat_beginpattern:
  1716. limit.minLength = 0;
  1717. limit.maxLength = 0;
  1718. break;
  1719. case no_pat_endpattern:
  1720. limit.minLength = 0;
  1721. limit.maxLength = 0;
  1722. limit.containsAssertion = true;
  1723. break;
  1724. case no_pat_singlechar:
  1725. limit.minLength = 1;
  1726. limit.maxLength = 1;
  1727. break;
  1728. }
  1729. }
  1730. void HqlSimpleRegexExpr::gatherLeading(HqlRegexUniqueArray & target)
  1731. {
  1732. switch (op)
  1733. {
  1734. case no_null:
  1735. case no_pat_beginrecursive:
  1736. case no_pat_beginpattern:
  1737. break;
  1738. case no_pat_endpattern:
  1739. case no_pat_singlechar:
  1740. target.append(OLINK(*this));
  1741. break;
  1742. default:
  1743. UNIMPLEMENTED;
  1744. }
  1745. }
  1746. void HqlSimpleRegexExpr::gatherTrailing(HqlRegexUniqueArray & target)
  1747. {
  1748. unsigned max = numTrailing();
  1749. for (unsigned i = 0; i < max; i++)
  1750. target.append(OLINK(queryTrailing(i)));
  1751. }
  1752. unsigned HqlSimpleRegexExpr::numTrailing() const
  1753. {
  1754. switch (getOperator())
  1755. {
  1756. case no_null:
  1757. case no_pat_endpattern:
  1758. return 0;
  1759. case no_pat_beginrecursive:
  1760. case no_pat_beginpattern:
  1761. case no_pat_singlechar:
  1762. return 1;
  1763. default:
  1764. UNIMPLEMENTED;
  1765. }
  1766. }
  1767. HqlRegexExpr & HqlSimpleRegexExpr::queryTrailing(unsigned idx)
  1768. {
  1769. switch (getOperator())
  1770. {
  1771. case no_pat_beginrecursive:
  1772. case no_pat_beginpattern:
  1773. case no_pat_singlechar:
  1774. if (idx == 0)
  1775. return *this;
  1776. break;
  1777. }
  1778. UNIMPLEMENTED;
  1779. }
  1780. //---------------------------------------------------------------------------
  1781. void HqlComplexRegexExpr::analyseNullLeadTrail()
  1782. {
  1783. if (analysed)
  1784. return;
  1785. analysed = true;
  1786. ForEachItemIn(idx, args)
  1787. args.item(idx).analyseNullLeadTrail();
  1788. if (queryNamed())
  1789. named->analyseNullLeadTrail();
  1790. switch (getOperator())
  1791. {
  1792. case no_null:
  1793. case no_pat_beginrecursive:
  1794. case no_pat_beginpattern:
  1795. case no_pat_endpattern:
  1796. case no_pat_singlechar:
  1797. //Should be handled by simpleRegex
  1798. UNIMPLEMENTED;
  1799. break;
  1800. case no_pat_instance:
  1801. limit = named->queryLimit();
  1802. limit.containsAssertion = true; // require us to walk it, even if internally matches nothing.
  1803. leading.append(*LINK(this));
  1804. trailing.append(*LINK(this));
  1805. break;
  1806. case no_pat_dfa:
  1807. limit = named->queryLimit();
  1808. limit.containsAssertion = true; // this means that it will process optional values
  1809. leading.append(*LINK(this));
  1810. trailing.append(*LINK(this));
  1811. break;
  1812. case no_pat_endrecursive:
  1813. case no_pat_x_before_y:
  1814. case no_pat_before_y:
  1815. case no_pat_x_after_y:
  1816. case no_pat_after_y:
  1817. case no_pat_first:
  1818. case no_pat_last:
  1819. case no_pat_begintoken:
  1820. case no_pat_endtoken:
  1821. case no_pat_begincheck:
  1822. case no_pat_endcheckin:
  1823. case no_pat_endchecklength:
  1824. case no_pat_beginseparator:
  1825. case no_pat_endseparator:
  1826. case no_pat_beginvalidate:
  1827. case no_pat_endvalidate:
  1828. case no_penalty:
  1829. limit.containsAssertion = true;
  1830. limit.minLength = 0;
  1831. limit.maxLength = 0;
  1832. leading.append(*LINK(this));
  1833. trailing.append(*LINK(this));
  1834. break;
  1835. case no_pat_anychar:
  1836. case no_pat_set:
  1837. limit.minLength = 1;
  1838. limit.maxLength = 1;
  1839. leading.append(*LINK(this));
  1840. trailing.append(*LINK(this));
  1841. break;
  1842. case no_pat_const:
  1843. {
  1844. unsigned len = expr->queryChild(0)->queryType()->getStringLen();
  1845. limit.minLength = len;
  1846. limit.maxLength = len;
  1847. if (len != 0)
  1848. {
  1849. leading.append(*LINK(this));
  1850. trailing.append(*LINK(this));
  1851. }
  1852. }
  1853. break;
  1854. case no_pat_or:
  1855. {
  1856. limit.minLength = PATTERN_UNLIMITED_LENGTH;
  1857. limit.maxLength = 0;
  1858. limit.containsAssertion = true;
  1859. ForEachItemIn(idx, args)
  1860. {
  1861. HqlRegexExpr & cur = args.item(idx);
  1862. if (cur.limit.minLength < limit.minLength)
  1863. limit.minLength = cur.limit.minLength;
  1864. if (cur.limit.maxLength > limit.maxLength)
  1865. limit.maxLength = cur.limit.maxLength;
  1866. if (cur.limit.canBeNull())
  1867. limit.containsAssertion = false;
  1868. cur.gatherLeading(leading);
  1869. cur.gatherTrailing(trailing);
  1870. }
  1871. break;
  1872. }
  1873. case no_pat_separator:
  1874. {
  1875. assertex(args.ordinality() == 3);
  1876. limit = args.item(1).limit;
  1877. leading.append(OLINK(args.item(0)));
  1878. trailing.append(OLINK(args.item(2)));
  1879. break;
  1880. }
  1881. case no_pat_follow:
  1882. {
  1883. limit.minLength = 0;
  1884. limit.maxLength = 0;
  1885. ForEachItemIn(idx0, args)
  1886. {
  1887. HqlRegexExpr & cur = args.item(idx0);
  1888. limit.minLength = limitedAdd(limit.minLength, cur.limit.minLength);
  1889. limit.maxLength = limitedAdd(limit.maxLength, cur.limit.maxLength);
  1890. if (cur.limit.containsAssertion)
  1891. limit.containsAssertion = true;
  1892. }
  1893. ForEachItemIn(idx1, args)
  1894. {
  1895. HqlRegexExpr & cur = args.item(idx1);
  1896. cur.gatherLeading(leading);
  1897. if (!cur.canBeNull())
  1898. break;
  1899. }
  1900. ForEachItemInRev(idx2, args)
  1901. {
  1902. HqlRegexExpr & cur = args.item(idx2);
  1903. cur.gatherTrailing(trailing);
  1904. if (!cur.canBeNull())
  1905. break;
  1906. }
  1907. break;
  1908. }
  1909. case no_pat_repeat:
  1910. {
  1911. if (isStandardRepeat())
  1912. {
  1913. HqlRegexExpr & arg = args.item(0);
  1914. limit.minLength = limitedMult(getRepeatMin(), arg.limit.minLength);
  1915. limit.maxLength = limitedMult(getRepeatMax(), arg.limit.maxLength);
  1916. if (getRepeatMin() != 0) limit.containsAssertion = arg.limit.containsAssertion;
  1917. arg.gatherLeading(leading);
  1918. arg.gatherTrailing(trailing);
  1919. }
  1920. else
  1921. {
  1922. limit.minLength = limitedMult(getRepeatMin(), named->getMinLength());
  1923. limit.maxLength = limitedMult(getRepeatMax(), named->getMaxLength());
  1924. //if (getRepeatMin() != 0) limit.containsAssertion = named->queryLimit().containsAssertion;
  1925. limit.containsAssertion = true;
  1926. leading.append(*LINK(this));
  1927. trailing.append(*LINK(this));
  1928. }
  1929. break;
  1930. }
  1931. case no_pat_pattern:
  1932. // Should have been converted by the time we get here...
  1933. default:
  1934. UNIMPLEMENTED;
  1935. break;
  1936. }
  1937. }
  1938. void HqlComplexRegexExpr::cleanup()
  1939. {
  1940. if (cleaned)
  1941. return;
  1942. HqlRegexExpr::cleanup();
  1943. trailing.kill();
  1944. leading.kill();
  1945. subPattern.clear();
  1946. }
  1947. void HqlComplexRegexExpr::gatherLeading(HqlRegexUniqueArray & target)
  1948. {
  1949. inherit(target, leading);
  1950. }
  1951. void HqlComplexRegexExpr::gatherTrailing(HqlRegexUniqueArray & target)
  1952. {
  1953. inherit(target, trailing);
  1954. }
  1955. //---------------------------------------------------------------------------
  1956. // DFA helper classes.
  1957. inline int compareHqlRegexExpr(HqlRegexExpr * left, HqlRegexExpr * right)
  1958. {
  1959. unique_id_t idl = left->queryUid();
  1960. unique_id_t idr = right->queryUid();
  1961. return (idl < idr) ? -1 : (idl > idr) ? +1 : 0;
  1962. }
  1963. int compareHqlRegexExpr(CInterface * * left, CInterface * * right)
  1964. {
  1965. return compareHqlRegexExpr((HqlRegexExpr *)*left, (HqlRegexExpr *)*right);
  1966. }
  1967. void HqlRegexExprSet::add(HqlRegexExpr * value)
  1968. {
  1969. bool isNew;
  1970. CInterface * castValue = value;
  1971. values.bAdd(castValue, compareHqlRegexExpr, isNew);
  1972. }
  1973. int HqlRegexExprSet::compare(const HqlRegexExprSet & other) const
  1974. {
  1975. unsigned numThis = values.ordinality();
  1976. unsigned numOther = other.values.ordinality();
  1977. unsigned numCommon = std::min(numThis, numOther);
  1978. for (unsigned i = 0; i < numCommon; i++)
  1979. {
  1980. HqlRegexExpr & left = values.item(i);
  1981. HqlRegexExpr & right = other.values.item(i);
  1982. int c = compareHqlRegexExpr(&left, &right);
  1983. if (c)
  1984. return c;
  1985. }
  1986. if (numThis > numOther)
  1987. return +1;
  1988. else if (numThis < numOther)
  1989. return -1;
  1990. else
  1991. return 0;
  1992. }
  1993. bool HqlRegexExprSet::equals(const HqlRegexExprSet & other) const
  1994. {
  1995. unsigned numThis = values.ordinality();
  1996. unsigned numOther = other.values.ordinality();
  1997. if (numThis != numOther)
  1998. return false;
  1999. for (unsigned i = 0; i < numThis; i++)
  2000. {
  2001. if (&values.item(i) != &other.values.item(i))
  2002. return false;
  2003. }
  2004. return true;
  2005. }
  2006. bool HqlDfaState::isAccepting()
  2007. {
  2008. ForEachItemIn(idx, position)
  2009. if (position.item(idx).getOperator() == no_pat_endpattern)
  2010. return true;
  2011. return false;
  2012. }
  2013. static inline int compareState(HqlDfaState * left, HqlDfaState * right)
  2014. {
  2015. return left->position.compare(right->position);
  2016. }
  2017. static int compareState(CInterface * * left, CInterface * * right)
  2018. {
  2019. return compareState((HqlDfaState *)*left, (HqlDfaState *)*right);
  2020. }
  2021. void HqlRegexExpr::generateDFAs()
  2022. {
  2023. if (op != no_pat_dfa)
  2024. {
  2025. ForEachItemIn(idx, args)
  2026. args.item(idx).generateDFAs();
  2027. return;
  2028. }
  2029. //Adapted from Dragon p141 Fig 3.44
  2030. //Main variation is that the set of potential symbols is calculated first, rather than trying the whole alphabet
  2031. //it might also have character-classes e.g., [[:alpha:]] in the stream.
  2032. dfa = new HqlDfaInfo;
  2033. HqlDfaState * firstState = new HqlDfaState(0);
  2034. HqlRegexExpr * first = queryNamed()->def->queryChild(0);
  2035. ForEachItemIn(idx, first->following)
  2036. firstState->position.add(&first->following.item(idx));
  2037. //Store a list of states, and an ordered list. First marks which have been processed,
  2038. //second gives efficient duplicate detection.
  2039. dfa->states.append(*firstState);
  2040. dfa->orderedStates.append(*LINK(firstState));
  2041. unsigned curStateIndex = 0;
  2042. while (curStateIndex < dfa->states.ordinality())
  2043. {
  2044. HqlDfaState & curState = dfa->states.item(curStateIndex++);
  2045. //First gather the potential symbols that come next (otherwise we would die with unicode!)
  2046. //it also speeds up ascii by a fairly large factor on sets of strings.
  2047. SymbolArray nextSymbols;
  2048. ForEachItemIn(ip, curState.position)
  2049. curState.position.item(ip).gatherConsumeSymbols(nextSymbols);
  2050. //For each symbol, work out what combination of states we could become translated to.
  2051. SymbolArrayIterator iter(nextSymbols);
  2052. ForEach(iter)
  2053. {
  2054. unsigned curSymbol = iter.get();
  2055. HqlDfaState * nextState = new HqlDfaState(dfa->states.ordinality());
  2056. //For each NFA state we could be in, what new NFA state could be now be in...
  2057. ForEachItemIn(ip, curState.position)
  2058. {
  2059. HqlRegexExpr & curRegex = curState.position.item(ip);
  2060. if (curRegex.canConsume(curSymbol))
  2061. {
  2062. ForEachItemIn(idx2, curRegex.following)
  2063. nextState->position.add(&curRegex.following.item(idx2));
  2064. }
  2065. }
  2066. //If no states, then don't bother adding a transition - we're done..
  2067. if (nextState->position.ordinality())
  2068. {
  2069. bool isNew = false;
  2070. CInterface * castState = nextState;
  2071. unsigned matchIndex = dfa->orderedStates.bAdd(castState, compareState, isNew);
  2072. if (isNew)
  2073. dfa->states.append(*LINK(nextState));
  2074. else
  2075. nextState->Release();
  2076. HqlDfaState * matchedState = &dfa->orderedStates.item(matchIndex);
  2077. //Finally associate a transition for this symbol...
  2078. curState.transitions.append(*new HqlDfaTransition(curSymbol, matchedState));
  2079. }
  2080. else
  2081. nextState->Release();
  2082. }
  2083. }
  2084. }
  2085. /**
  2086. Some unicode pseudo code
  2087. ForEach(ip in curState.position)
  2088. {
  2089. position(ip).getConsumed(consumeSet);
  2090. positionSet = [ip];
  2091. if (consumeSet.ordinality())
  2092. Merge(consumeSet, 0, positionSet);
  2093. }
  2094. Merge(consumeSet, first, positionSet)
  2095. {
  2096. for (i = first; i < sets.ordinality(); i++)
  2097. {
  2098. diff = intersect(sets(i).consume, consumeSet);
  2099. if (diff.ordinality())
  2100. {
  2101. rightOnly = sets(i).consume - diff;
  2102. if (rightOnly.ordinality() == 0)
  2103. sets(i).positions.union(positionSet);
  2104. else
  2105. {
  2106. sets(i).consume = rightOnly;
  2107. Merge(diff, i+1, union(sets(i).positions, positionSet);
  2108. }
  2109. newOnly = consumeSet - diff;
  2110. if (newOnly = [])
  2111. return;
  2112. consumeSet = newOnly;
  2113. }
  2114. }
  2115. sets.append(consumeSet, positionSet);
  2116. }
  2117. Output would be a set of disjoint sets, together with a lits of positions that are matched by those sets.
  2118. They could then be used to generate the tables required by a dfa matcher list of
  2119. low, high, target-state
  2120. which was binary chopped.
  2121. It might be better to not use the icu sets, except for generating a set of ranges, and handle everything else ourselves.
  2122. Possibly a set of [low,high,positions], or maybe even [low, high, position], sorted by low
  2123. with some clever code to walk through and retain lists of which ones are active.
  2124. **/
  2125. //---------------------------------------------------------------------------
  2126. RegexContext::RegexContext(IHqlExpression * _expr, IWorkUnit * _wu, const HqlCppOptions & _options, ITimeReporter * _timeReporter, byte _algorithm) : NlpParseContext(_expr, _wu, _options, _timeReporter), parser(NULL, _algorithm)
  2127. {
  2128. info.addedSeparators = false;
  2129. switch (info.type)
  2130. {
  2131. case type_string: info.dfaComplexity = DEFAULT_DFA_COMPLEXITY; break;
  2132. case type_utf8: info.dfaComplexity = DEFAULT_UTF8_DFA_COMPLEXITY; break;
  2133. case type_unicode: info.dfaComplexity = DEFAULT_UNICODE_DFA_COMPLEXITY; break;
  2134. }
  2135. if (_options.parseDfaComplexity != (unsigned)-1)
  2136. info.dfaComplexity = _options.parseDfaComplexity;
  2137. info.expandRepeatAnyAsDfa = _options.expandRepeatAnyAsDfa;
  2138. createLexer = false;
  2139. }
  2140. RegexContext::~RegexContext()
  2141. {
  2142. ForEachItemIn(idx, named)
  2143. named.item(idx).cleanup();
  2144. }
  2145. HqlNamedRegex * RegexContext::queryNamed(IHqlExpression * defn, _ATOM name, node_operator op, bool caseSensitive)
  2146. {
  2147. ForEachItemIn(idx, named)
  2148. {
  2149. HqlNamedRegex & cur = named.item(idx);
  2150. if (cur.matches(defn, name, caseSensitive))
  2151. {
  2152. assertex(cur.matches(defn, name, op, caseSensitive));
  2153. return &cur;
  2154. }
  2155. }
  2156. return NULL;
  2157. }
  2158. HqlNamedRegex * RegexContext::createNamed(IHqlExpression * expr, _ATOM name, node_operator op, bool caseSensitive)
  2159. {
  2160. LinkedHqlExpr searchExpr = expr;
  2161. if (op != no_pat_instance)
  2162. //Create an expression that should never clash with anything we would find in the parse tree
  2163. searchExpr.setown(createValue(op, expr->getType(), LINK(expr), createAttribute(tempAtom)));
  2164. HqlNamedRegex * match = queryNamed(searchExpr, name, op, caseSensitive);
  2165. if (match)
  2166. match->addUse();
  2167. else
  2168. {
  2169. match = new HqlNamedRegex(expr, name, searchExpr, op, caseSensitive, isMatched(searchExpr, name));
  2170. named.append(*match); // add to list first to avoid recursion problems.
  2171. match->setRegexOwn(createStructure(expr, caseSensitive));
  2172. }
  2173. return match;
  2174. }
  2175. static HqlRegexExpr * createFollow(const ParseInformation & options, HqlRegexExpr * a1, HqlRegexExpr * a2, HqlRegexExpr * a3, bool caseSensitive)
  2176. {
  2177. HqlRegexExpr * follow = createRegexExpr(options, no_pat_follow, NULL, caseSensitive);
  2178. follow->addOperand(a1);
  2179. follow->addOperand(a2);
  2180. if (a3)
  2181. follow->addOperand(a3);
  2182. return follow;
  2183. }
  2184. HqlRegexExpr * RegexContext::createFollow(HqlRegexExpr * start, IHqlExpression * body, node_operator endOp, IHqlExpression * endExpr, bool caseSensitive)
  2185. {
  2186. HqlRegexExpr * next = createStructure(body, caseSensitive);
  2187. HqlRegexExpr * finish = createRegexExpr(info, endOp, endExpr, caseSensitive);
  2188. return ::createFollow(info, start, next, finish, caseSensitive);
  2189. }
  2190. HqlRegexExpr * RegexContext::createStructure(IHqlExpression * expr, bool caseSensitive)
  2191. {
  2192. node_operator op = expr->getOperator();
  2193. switch (op)
  2194. {
  2195. case no_pat_production:
  2196. throwError(HQLERR_RegexNoTransformSupport);
  2197. case no_pat_instance:
  2198. {
  2199. IHqlExpression * def = expr->queryChild(0);
  2200. if (createLexer)
  2201. return createStructure(def, caseSensitive);
  2202. Owned<HqlRegexExpr> instance = createRegexExpr(info, expr, caseSensitive);
  2203. IHqlExpression * nameExpr = expr->queryChild(1);
  2204. instance->setNamed(createNamed(def, nameExpr ? nameExpr->queryName() : NULL, op, caseSensitive));
  2205. return instance.getClear();
  2206. }
  2207. case no_pat_guard:
  2208. return createRegexExpr(info, no_null, NULL, caseSensitive);
  2209. case no_attr:
  2210. case no_attr_expr:
  2211. case no_attr_link:
  2212. return NULL;
  2213. case no_implicitcast:
  2214. //can sometimes occur when parameters are bound
  2215. return createStructure(expr->queryChild(0), caseSensitive);
  2216. case no_pat_const:
  2217. if (createLexer)
  2218. return expandStringAsChars(expr, info, caseSensitive);
  2219. return createRegexExpr(info, expr, caseSensitive);
  2220. case no_pat_set:
  2221. case no_penalty:
  2222. //Don't walk children...
  2223. return createRegexExpr(info, expr, caseSensitive);
  2224. case no_pat_x_before_y:
  2225. case no_pat_x_after_y:
  2226. {
  2227. Owned<HqlRegexExpr> pattern = createStructure(expr->queryChild(0), caseSensitive);
  2228. Owned<HqlRegexExpr> check = createRegexExpr(info, expr, caseSensitive);
  2229. check->setSubPattern(createNamed(expr->queryChild(1), NULL, no_pat_checkin, caseSensitive));
  2230. if (op == no_pat_x_before_y)
  2231. return ::createFollow(info, pattern.getClear(), check.getClear(), NULL, caseSensitive);
  2232. else
  2233. return ::createFollow(info, check.getClear(), pattern.getClear(), NULL, caseSensitive);
  2234. }
  2235. case no_pat_before_y:
  2236. case no_pat_after_y:
  2237. {
  2238. Owned<HqlRegexExpr> check = createRegexExpr(info, expr, caseSensitive);
  2239. check->setSubPattern(createNamed(expr->queryChild(0), NULL, no_pat_checkin, caseSensitive));
  2240. return check.getClear();
  2241. }
  2242. case no_pat_checkin:
  2243. {
  2244. Owned<HqlRegexExpr> start = createRegexExpr(info, no_pat_begincheck, expr, caseSensitive);
  2245. Owned<HqlRegexExpr> next = createStructure(expr->queryChild(0), caseSensitive);
  2246. Owned<HqlRegexExpr> finish = createRegexExpr(info, no_pat_endcheckin, expr, caseSensitive);
  2247. finish->setSubPattern(createNamed(expr->queryChild(1), NULL, no_pat_checkin, caseSensitive));
  2248. return ::createFollow(info, start.getClear(), next.getClear(), finish.getClear(), caseSensitive);
  2249. }
  2250. case no_pat_checklength:
  2251. {
  2252. HqlRegexExpr * start = createRegexExpr(info, no_pat_begincheck, expr, caseSensitive);
  2253. return createFollow(start, expr->queryChild(0), no_pat_endchecklength, expr, caseSensitive);
  2254. }
  2255. case no_pat_validate:
  2256. {
  2257. HqlRegexExpr * start = createRegexExpr(info, no_pat_beginvalidate, expr, caseSensitive);
  2258. return createFollow(start, expr->queryChild(0), no_pat_endvalidate, expr, caseSensitive);
  2259. }
  2260. case no_pat_token:
  2261. case no_pat_imptoken:
  2262. {
  2263. IHqlExpression * child = expr->queryChild(0);
  2264. //MORE: Covert into a function to allow multiple values of following:
  2265. switch (child->getOperator())
  2266. {
  2267. case no_null:
  2268. case no_pat_first:
  2269. case no_pat_last:
  2270. return createStructure(child, caseSensitive);
  2271. case no_penalty:
  2272. case no_pat_x_before_y:
  2273. case no_pat_before_y:
  2274. case no_pat_x_after_y:
  2275. case no_pat_after_y:
  2276. case no_pat_guard:
  2277. return createStructure(child, caseSensitive);
  2278. case no_pat_const:
  2279. // if (!info.separator)
  2280. // return createStructure(child);
  2281. break;
  2282. }
  2283. HqlRegexExpr * start = createRegexExpr(info, no_pat_begintoken, expr, caseSensitive);
  2284. return createFollow(start, expr->queryChild(0), no_pat_endtoken, expr, caseSensitive);
  2285. }
  2286. case no_pat_repeat:
  2287. {
  2288. HqlRegexExpr * ret = createRegexExpr(info, expr, caseSensitive);
  2289. IHqlExpression * repeated = expr->queryChild(0);
  2290. if (ret->isStandardRepeat())
  2291. ret->addOperand(createStructure(repeated, caseSensitive));
  2292. else
  2293. ret->setNamed(createNamed(repeated, NULL, op, caseSensitive));
  2294. return ret;
  2295. }
  2296. case no_pat_or:
  2297. case no_pat_follow:
  2298. {
  2299. //Expand these out as much as possible....
  2300. HqlExprArray args;
  2301. expr->unwindList(args, op);
  2302. OwnedHqlExpr flatExpr = expr->clone(args);
  2303. Owned<HqlRegexExpr> ret = createRegexExpr(info, flatExpr, caseSensitive);
  2304. ForEachChild(idx, flatExpr)
  2305. {
  2306. HqlRegexExpr * child = createStructure(flatExpr->queryChild(idx), caseSensitive);
  2307. if (child)
  2308. ret->addOperand(child);
  2309. }
  2310. return ret.getClear();
  2311. }
  2312. case no_pat_case:
  2313. case no_pat_nocase:
  2314. return createStructure(expr->queryChild(0), op==no_pat_case);
  2315. case no_pat_featureactual:
  2316. throwError(HQLERR_RegexFeatureNotSupport);
  2317. }
  2318. Owned<HqlRegexExpr> ret = createRegexExpr(info, expr, caseSensitive);
  2319. ForEachChild(idx, expr)
  2320. {
  2321. HqlRegexExpr * child = createStructure(expr->queryChild(idx), caseSensitive);
  2322. if (child)
  2323. ret->addOperand(child);
  2324. }
  2325. return ret.getClear();
  2326. }
  2327. void RegexContext::buildStructure()
  2328. {
  2329. unsigned startTime = msTick();
  2330. IHqlExpression * grammar = expr->queryChild(2);
  2331. assertex(grammar->getOperator() == no_pat_instance);
  2332. _ATOM name = grammar->queryChild(1)->queryName();
  2333. OwnedHqlExpr structure = LINK(grammar);//createValue(no_pat_instance, makeRuleType(NULL), LINK(grammar), LINK(grammar->queryChild(1)));
  2334. HqlRegexExpr * rootRegex = createStructure(structure, isCaseSensitive());
  2335. root.setown(new HqlNamedRegex(structure, internalAtom, structure, no_parse, isCaseSensitive(), false));
  2336. root->setRegexOwn(rootRegex);
  2337. named.append(*LINK(root));
  2338. DEBUG_TIMERX(timeReporter, "EclServer: Generate PARSE: Create Structure", msTick()-startTime);
  2339. }
  2340. void RegexContext::expandRecursion()
  2341. {
  2342. //First add all the symbols referenced by the use() attributes on the parse so they can be matched.
  2343. ForEachChild(idx, expr)
  2344. {
  2345. IHqlExpression * cur = expr->queryChild(idx);
  2346. if (cur->getOperator() == no_pat_use)
  2347. {
  2348. //NB: Does not return a linked item.
  2349. HqlNamedRegex * named = createNamed(cur->queryChild(0), NULL, no_pat_instance, true);
  2350. named->removeUse(); // Not actually used at the moment...
  2351. HqlNamedRegex * named2 = createNamed(cur->queryChild(0), NULL, no_pat_instance, false);
  2352. named2->removeUse(); // Not actually used at the moment...
  2353. }
  2354. }
  2355. root->expandRecursion(*this, NULL);
  2356. ForEachItemInRev(idx2, named)
  2357. if (!named.item(idx2).queryExpandedRecursion())
  2358. named.remove(idx2);
  2359. }
  2360. void RegexContext::insertSeparators()
  2361. {
  2362. if (info.separator)
  2363. {
  2364. ForEachItemIn(idx, named)
  2365. named.item(idx).insertSeparators(info.separator, this);
  2366. //add separator/first onto the front of root.
  2367. info.addedSeparators = true;
  2368. }
  2369. }
  2370. void RegexContext::optimizeSpotDFA()
  2371. {
  2372. if (info.dfaComplexity > 0)
  2373. {
  2374. ForEachItemIn(idx, named)
  2375. named.item(idx).calcDfaScore();
  2376. root->markDFAs(info.dfaComplexity);
  2377. ForEachItemIn(idx2, named)
  2378. named.item(idx2).createDFAs(*this);
  2379. }
  2380. }
  2381. void RegexContext::optimizePattern()
  2382. {
  2383. unsigned startTime = msTick();
  2384. ForEachItemIn(idx1, named)
  2385. named.item(idx1).mergeCreateSets();
  2386. root->expandNamedSymbols();
  2387. ForEachItemInRev(idx2, named)
  2388. {
  2389. if (!named.item(idx2).isUsed())
  2390. {
  2391. //Can't delete it otherwise everything gets cleaned up...
  2392. deadNamed.append(named.item(idx2));
  2393. named.remove(idx2, true);
  2394. }
  2395. }
  2396. optimizeSpotDFA();
  2397. DEBUG_TIMERX(timeReporter, "EclServer: Generate PARSE: Optimize", msTick()-startTime);
  2398. }
  2399. HqlNamedRegex * RegexContext::queryDefine(IHqlExpression * defineName, bool caseSensitive)
  2400. {
  2401. ForEachItemIn(idx, named)
  2402. {
  2403. HqlNamedRegex & cur = named.item(idx);
  2404. if (cur.matchesDefine(defineName,caseSensitive))
  2405. return &cur;
  2406. }
  2407. StringBuffer s;
  2408. defineName->toString(s);
  2409. throwError1(HQLERR_DefineUseStrNotFound, s.str());
  2410. return NULL;
  2411. }
  2412. void RegexContext::analysePattern()
  2413. {
  2414. unsigned startTime = msTick();
  2415. //This conversion is based around the description in the Dragon book:
  2416. //3.9 From a regular expression to a DFA
  2417. //even though we don't always convert it, the steps form a useful algorithm
  2418. ForEachItemIn(idx0, named)
  2419. named.item(idx0).addBeginEnd(info);
  2420. ForEachItemIn(idx1, named)
  2421. named.item(idx1).analyseNullLeadTrail();
  2422. ForEachItemIn(idx2, named)
  2423. named.item(idx2).calculateNext();
  2424. ForEachItemIn(idx3, named)
  2425. named.item(idx3).generateDFAs();
  2426. DEBUG_TIMERX(timeReporter, "EclServer: Generate PARSE: Analyse", msTick()-startTime);
  2427. }
  2428. void RegexContext::generateRegex()
  2429. {
  2430. unsigned startTime = msTick();
  2431. parser.addedSeparators = info.addedSeparators;
  2432. setParserOptions(parser);
  2433. GenerateRegexCtx ctx(*this, info, idAllocator);
  2434. ForEachItemIn(idx0, named)
  2435. {
  2436. HqlNamedRegex & cur = named.item(idx0);
  2437. cur.generateRegex(ctx);
  2438. }
  2439. parser.grammar.set(root->queryRootPattern());
  2440. parser.minPatternLength = root->getMinLength();
  2441. DEBUG_TIMERX(timeReporter, "EclServer: Generate PARSE: Generate", msTick()-startTime);
  2442. }
  2443. //void RegexContext::removeTrivialInstances()
  2444. //{
  2445. // ForEachItemIn(idx, named)
  2446. // named.item(idx).removeTrivialInstances();
  2447. //}
  2448. void RegexContext::compileSearchPattern()
  2449. {
  2450. checkValidMatches();
  2451. buildStructure();
  2452. expandRecursion();
  2453. // removeTrivialInstances();
  2454. insertSeparators();
  2455. optimizePattern();
  2456. analysePattern();
  2457. generateRegex();
  2458. compileMatched(parser);
  2459. }
  2460. void RegexContext::getDebugText(StringBuffer & s, unsigned detail)
  2461. {
  2462. NlpParseContext::getDebugText(s, detail);
  2463. regexToXml(s, parser.grammar, detail);
  2464. }
  2465. NlpParseContext * createRegexContext(IHqlExpression * expr, IWorkUnit * wu, const HqlCppOptions & options, ITimeReporter * timeReporter, byte algorithm)
  2466. {
  2467. return new RegexContext(expr, wu, options, timeReporter, algorithm);
  2468. }
  2469. //-- Lexer creation
  2470. void RegexContext::beginLexer()
  2471. {
  2472. createLexer = true;
  2473. info.expandRepeatAnyAsDfa = true;
  2474. OwnedHqlExpr searchExpr = createValue(no_pat_dfa, makePatternType(), createUniqueId());
  2475. lexerNamed.setown(new HqlNamedRegex(searchExpr, NULL, searchExpr, no_pat_dfa, isCaseSensitive(), false));
  2476. lexerOr.setown(createRegexExpr(info, no_pat_or, NULL, isCaseSensitive()));
  2477. lexerNamed->setRegexOwn(LINK(lexerOr));
  2478. lexerRoot.setown(createRegexExpr(info, no_pat_dfa, NULL, isCaseSensitive()));
  2479. lexerRoot->setNamed(lexerNamed);
  2480. root.setown(new HqlNamedRegex(expr, NULL, expr, no_parse, isCaseSensitive(), false));
  2481. root->setRegexOwn(LINK(lexerRoot));
  2482. named.append(*LINK(lexerNamed));
  2483. named.append(*LINK(root));
  2484. }
  2485. void RegexContext::addLexerToken(unsigned id, IHqlExpression * pattern)
  2486. {
  2487. HqlRegexExpr * token = createStructure(pattern, isCaseSensitive());
  2488. HqlRegexExpr * end = createRegexExpr(info, no_pat_endpattern, NULL, isCaseSensitive());
  2489. end->setAcceptId(id);
  2490. if (token->getOperator() == no_pat_follow)
  2491. token->addOperand(end);
  2492. else
  2493. {
  2494. HqlRegexExpr * follow = createRegexExpr(info, no_pat_follow, NULL, isCaseSensitive());
  2495. follow->addOperand(token);
  2496. follow->addOperand(end);
  2497. token = follow;
  2498. }
  2499. lexerOr->addOperand(token);
  2500. }
  2501. void RegexContext::generateLexer(IDfaPattern * builder)
  2502. {
  2503. //MORE: Need to call some elements of optimizePattern() to expand limited repeats.
  2504. analysePattern();
  2505. lexerRoot->generateDFA(builder);
  2506. }
  2507. /*
  2508. ToDo:
  2509. o Should move some of the logic from HqlregexExpr to complex + remove the queyNamed() etc. virtuals.
  2510. */