jregexp.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745
  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. #include "jlib.hpp"
  15. #include "jmisc.hpp"
  16. #include "jregexp.hpp"
  17. #define FAIL(s) { /*assert(!s);*/ return NULL; }
  18. #define SUBPARENL '{'
  19. #define SUBPARENR '}'
  20. // NB Meta must change if the above change
  21. typedef unsigned REGFLAGS;
  22. #define MAXEXPR 0xf000
  23. #define MAXSUBST 0xf000
  24. #define NSUBEXP 10
  25. class RECOMP
  26. {
  27. public:
  28. const char *s_start[NSUBEXP];
  29. const char *s_end[NSUBEXP];
  30. const char *s_save; // save text after find
  31. const char *s_savestr[NSUBEXP];
  32. size32_t s_savelen[NSUBEXP];
  33. char start;
  34. char anch;
  35. char *must;
  36. size32_t mlen;
  37. char *program;
  38. const char *parse; /* Input-scan pointer. */
  39. int npar; /* {} count. */
  40. char *code; /* Code-emit pointer. */
  41. const char *input; /* String-input pointer. */
  42. const char *bol; /* Beginning of input, for ^ check. */
  43. const char **startp; /* Pointer to startp array. */
  44. const char **endp; /* Ditto for end. */
  45. char * reg(bool sub, REGFLAGS &);
  46. char *branch (REGFLAGS &);
  47. char *piece (REGFLAGS &);
  48. char *atom (REGFLAGS &);
  49. char *rnode (char);
  50. #ifdef _DEBUG
  51. void regc (char b) {
  52. if (code-program>=MAXEXPR-3)
  53. assertex(!"regular expression too complicated!");
  54. *code++ = b;
  55. };
  56. #endif
  57. void insert (char, char *);
  58. void tail (char *, char *);
  59. void optail (char *, char *);
  60. char *next (char *);
  61. bool match (char *prog);
  62. char *rtry (const char *);
  63. int repeat (char *);
  64. const char * findstart;
  65. const char * findend;
  66. size32_t replacemax; // needed for replace (clarion)
  67. bool nocase;
  68. const char *rstrchr(const char *s,int c);
  69. bool strnequ(const char *s1,const char *s2,size32_t n);
  70. bool eob(const char *s) { return s==findend; };
  71. bool claeol(const char *s);
  72. bool equch(int c1,int c2) { if (nocase) return (toupper(c1)==toupper(c2)); return c1==c2; };
  73. void adjustptrs(const char *e,size32_t lo,size32_t lr);
  74. size32_t rstrlen(const char *s) {size32_t l=0; while (s++!=findend) l++; return l; };
  75. bool clarion;
  76. bool suboverlap(int n,int m);
  77. RECOMP() { _clear(s_start); s_save=NULL; program = NULL; };
  78. ~RECOMP() {
  79. free((void *)s_save);
  80. free((void *)program);
  81. }
  82. };
  83. #ifndef _DEBUG
  84. #define REGC(b) *code++ = b
  85. #else
  86. #define REGC(b) regc(b)
  87. #endif
  88. //----
  89. /*
  90. * The "internal use only" fields in regexp.h are present to pass info from
  91. * compile to execute that permits the execute phase to run lots faster on
  92. * simple cases. They are:
  93. *
  94. * regstart char that must begin a match; '\0' if none obvious
  95. * reganch is the match anchored (at beginning-of-line only)?
  96. * regmust string (pointer into program) that match must include, or NULL
  97. * regmlen length of regmust string
  98. *
  99. * Regstart and reganch permit very fast decisions on suitable starting points
  100. * for a match, cutting down the work a lot. Regmust permits fast rejection
  101. * of lines that cannot possibly match. The regmust tests are costly enough
  102. * that regcomp() supplies a regmust only if the r.e. contains something
  103. * potentially expensive (at present, the only such thing detected is * or +
  104. * at the start of the r.e., which can involve a lot of backup). Regmlen is
  105. * supplied because the test in regexec() needs it and regcomp() is computing
  106. * it anyway.
  107. */
  108. /*
  109. * Structure for regexp "program". This is essentially a linear encoding
  110. * of a nondeterministic finite-state machine (aka syntax charts or
  111. * "railroad normal form" in parsing technology). Each node is an opcode
  112. * plus a "next" pointer, possibly plus an operand. "Next" pointers of
  113. * all nodes except BRANCH implement concatenation; a "next" pointer with
  114. * a BRANCH on both ends of it is connecting two alternatives. (Here we
  115. * have one of the subtle syntax dependencies: an individual BRANCH (as
  116. * opposed to a collection of them) is never concatenated with anything
  117. * because of operator precedence.) The operand of some types of node is
  118. * a literal string; for others, it is a node leading into a sub-FSM. In
  119. * particular, the operand of a BRANCH node is the first node of the branch.
  120. * (NB this is *not* a tree structure: the tail of the branch connects
  121. * to the thing following the set of BRANCHes.) The opcodes are:
  122. */
  123. /* definition number opnd? meaning */
  124. #define END 0 /* no End of program. */
  125. #define BOL 1 /* no Match "" at beginning of line. */
  126. #define EOL 2 /* no Match "" at end of line. */
  127. #define ANY 3 /* no Match any one character. */
  128. #define ANYOF 4 /* str Match any character in this string. */
  129. #define ANYBUT 5 /* str Match any character not in this string. */
  130. #define BRANCH 6 /* node Match this alternative, or the next... */
  131. #define BACK 7 /* no Match "", "next" ptr points backward. */
  132. #define EXACTLY 8 /* str Match this string. */
  133. #define NOTHING 9 /* no Match empty string. */
  134. #define STAR 10 /* node Match this (simple) thing 0 or more times. */
  135. #define PLUS 11 /* node Match this (simple) thing 1 or more times. */
  136. #define OPEN 20 /* no Mark this point in input as start of #n. */
  137. /* OPEN+1 is number 1, etc. */
  138. #define CLOSE 30 /* no Analogous to OPEN. */
  139. /*
  140. * Opcode notes:
  141. *
  142. * BRANCH The set of branches constituting a single choice are hooked
  143. * together with their "next" pointers, since precedence prevents
  144. * anything being concatenated to any individual branch. The
  145. * "next" pointer of the last BRANCH in a choice points to the
  146. * thing following the whole choice. This is also where the
  147. * final "next" pointer of each individual branch points; each
  148. * branch starts with the operand node of a BRANCH node.
  149. *
  150. * BACK Normal "next" pointers all implicitly point forward; BACK
  151. * exists to make loop structures possible.
  152. *
  153. * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
  154. * BRANCH structures using BACK. Simple cases (one character
  155. * per match) are implemented with STAR and PLUS for speed
  156. * and to minimize recursive plunges.
  157. *
  158. * OPEN,CLOSE ...are numbered at compile time.
  159. */
  160. /*
  161. * A node is one char of opcode followed by two chars of "next" pointer.
  162. * "Next" pointers are stored as two 8-bit pieces, high order first. The
  163. * value is a positive offset from the opcode of the node containing it.
  164. * An operand, if any, simply follows the node. (Note that much of the
  165. * code generation knows about this implicit relationship.)
  166. *
  167. * Using two bytes for the "next" pointer is vast overkill for most things,
  168. * but allows patterns to get big without disasters.
  169. */
  170. #define OP(p) (*(p))
  171. #define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
  172. #define OPERAND(p) ((p) + 3)
  173. // Utility definitions.
  174. #define UCHARAT(p) ((int)*(unsigned char *)(p))
  175. #define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
  176. #define META "^$.[{}|?+*\\"
  177. // Flags to be passed up and down.
  178. #define HASWIDTH 01 /* Known never to match null string. */
  179. #define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
  180. #define SPSTART 04 /* Starts with * or +. */
  181. #define WORST 0 /* Worst case. */
  182. RegExpr::RegExpr()
  183. {
  184. re = NULL;
  185. }
  186. RegExpr::~RegExpr()
  187. {
  188. delete re;
  189. }
  190. RegExpr::RegExpr(const char *r,bool nocase)
  191. {
  192. re = NULL;
  193. init(r,nocase);
  194. }
  195. bool RegExpr::init(const char *exp,bool nocase)
  196. // Compiles the regular expression ready for Find
  197. // if nocase = 1 the matching is case insensitive (where possible)
  198. {
  199. kill();
  200. char *scan;
  201. char *longest;
  202. memsize_t len;
  203. REGFLAGS flags;
  204. assertex(exp!=NULL);
  205. delete re;
  206. re = new RECOMP;
  207. re->clarion = false;
  208. re->parse = exp;
  209. re->npar = 1;
  210. re->program = (char *)malloc(MAXEXPR);
  211. re->code = re->program;
  212. re->nocase = nocase;
  213. re->start = '\0'; /* Worst-case defaults. */
  214. re->anch = 0;
  215. re->must = NULL;
  216. re->mlen = 0;
  217. if (re->reg(0, flags) == NULL)
  218. return false;
  219. /* Dig out information for optimizations. */
  220. scan = re->program; /* First BRANCH. */
  221. if (OP(re->next(scan)) == END) { /* Only one top-level choice. */
  222. scan = OPERAND(scan);
  223. /* Starting-point info. */
  224. if (OP(scan) == EXACTLY)
  225. re->start = *OPERAND(scan);
  226. else if (OP(scan) == BOL)
  227. re->anch++;
  228. /*
  229. * If there's something expensive in the r.e., find the
  230. * longest literal string that must appear and make it the
  231. * regmust. Resolve ties in favor of later strings, since
  232. * the regstart check works with the beginning of the r.e.
  233. * and avoiding duplication strengthens checking. Not a
  234. * strong reason, but sufficient in the absence of others.
  235. */
  236. if (flags&SPSTART) {
  237. longest = NULL;
  238. len = 0;
  239. for (; scan != NULL; scan = re->next(scan))
  240. if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= (size32_t) len) {
  241. longest = OPERAND(scan);
  242. len = strlen(OPERAND(scan));
  243. }
  244. re->must = longest;
  245. re->mlen = (size32_t)len;
  246. }
  247. }
  248. int reloc;
  249. if (re->must)
  250. reloc = re->must-re->program;
  251. re->program = (char *)realloc(re->program,(re->code-re->program)+1);
  252. if (re->must)
  253. re->must = (char *)(re->program + reloc);
  254. return true;
  255. }
  256. const char * RegExpr::find(const char *string,size32_t from,size32_t len,size32_t maxlen)
  257. // finds the first occurrence of the RE in string
  258. {
  259. /* Be paranoid... */
  260. if (re == NULL || re->program== NULL) {
  261. assertex(!"NULL parameter");
  262. return NULL;
  263. }
  264. if (!string) { // find again
  265. if (re->findstart == NULL) {
  266. assertex(!"NULL parameter");
  267. return NULL;
  268. }
  269. string = (char *)re->s_end[0];
  270. if ((string==NULL)||(string == re->findend))
  271. return NULL;
  272. }
  273. else {
  274. re->findstart = string;
  275. string+=from;
  276. re->replacemax = maxlen;
  277. if (maxlen) {
  278. re->clarion = true;
  279. re->findend = re->findstart+maxlen;
  280. }
  281. else {
  282. const char *s=string;
  283. for (size32_t l=0;*s&&(l<len);l++) s++;
  284. re->findend = s;
  285. }
  286. }
  287. free((void *)re->s_save);
  288. re->s_save = NULL; // clear saved (replaced string)
  289. /* If there is a "must appear" string, look for it. */
  290. if (re->must != NULL) {
  291. const char *s = string;
  292. while ((s = re->rstrchr(s, re->must[0])) != NULL) {
  293. if (re->strnequ(s, re->must, re->mlen))
  294. break; /* Found it. */
  295. s++;
  296. }
  297. if (s == NULL) /* Not present. */
  298. return 0;
  299. }
  300. /* Mark beginning of line for ^ . */
  301. re->bol = string;
  302. /* Simplest case: anchored match need be tried only once. */
  303. char *ret = NULL;
  304. if (re->anch)
  305. ret = re->rtry(string);
  306. else {
  307. /* Messy cases: unanchored match. */
  308. const char *s = string;
  309. if (re->start != '\0')
  310. /* We know what char it must start with. */
  311. while ((s = re->rstrchr(s, re->start)) != NULL) {
  312. if ((ret=re->rtry(s))!=NULL)
  313. break;
  314. s++;
  315. }
  316. else
  317. /* We don't -- general case. */
  318. do {
  319. if ((ret=re->rtry(s))!=NULL)
  320. break;
  321. } while (!re->eob(s++));
  322. }
  323. if (ret) {
  324. const char *ss = re->s_start[0];
  325. size32_t tl = re->s_end[0]-ss;
  326. char *ds=(char *)malloc(tl+1);
  327. memcpy(ds,ss,tl);
  328. ds[tl] = 0;
  329. for (int i = 0;i<NSUBEXP;i++) {
  330. const char *ss2 = re->s_start[i];
  331. if (ss2) {
  332. re->s_savelen[i] = re->s_end[i]-ss2;
  333. re->s_savestr[i] = ds+(ss2-ss);
  334. }
  335. else {
  336. re->s_savelen[i] = 0;
  337. re->s_savestr[i] = NULL;
  338. }
  339. }
  340. re->s_save = ds;
  341. }
  342. else {
  343. _clear(re->s_start);
  344. }
  345. return ret;
  346. }
  347. size32_t RegExpr::findlen(unsigned n)
  348. // size of string last matched using find
  349. {
  350. if (re == NULL || re->program== NULL) {
  351. assertex(!"NULL parameter");
  352. return 0;
  353. }
  354. assertex(n<NSUBEXP);
  355. if ((n>=NSUBEXP)) return 0;
  356. if (re->s_save)
  357. return re->s_savelen[n];
  358. return 0;
  359. }
  360. const char *RegExpr::findstr(StringBuffer &s,unsigned n)
  361. // returns string last matched (n = 0) or substring n (n>0)
  362. {
  363. size32_t l = findlen(n);
  364. if (l && re->s_save) {
  365. s.append(l,re->s_savestr[n]);
  366. }
  367. return s.str();
  368. }
  369. const char *RegExpr::findnext()
  370. {
  371. return find(NULL);
  372. }
  373. void RegExpr::replace(const char *rs,unsigned maxlen,unsigned n)
  374. // replaces string (n = 0), or substring (n>0) by 's'
  375. // in string at position previously found by Find or FindNext.
  376. // Multiple replaces may be called on a single Find/FindNext
  377. {
  378. if (re == NULL || re->program== NULL) {
  379. assertex(!"NULL parameter");
  380. return;
  381. }
  382. assertex(n<NSUBEXP);
  383. if ((n>=NSUBEXP)) return;
  384. const char *s=re->s_start[n];
  385. if (!s) return;
  386. if (maxlen==0) maxlen = re->replacemax;
  387. if (maxlen==0) return;
  388. const char *e=re->s_end[n];
  389. if (!e) return;
  390. size32_t lo=e-s;
  391. size32_t lt=re->rstrlen(e);
  392. size32_t lr = (size32_t)strlen(rs);
  393. if (lr>lo) {
  394. size32_t d = lr-lo; // delta
  395. size32_t l = ((e-re->findstart)+lt); // total length
  396. size32_t r = maxlen;
  397. if (l>r) {
  398. assertex(!"replace - maxlen too small for passed string!");
  399. return;
  400. }
  401. r-=l; // r = max gap left
  402. if (!re->clarion) r--; // for null
  403. if (r<d) {
  404. if (lt<d-r) {
  405. lr+=lt;
  406. if (lr<=(d-r)) return; // can't really happen
  407. lr-=(d-r); // new string too big
  408. lt=0; // lose tail
  409. }
  410. else
  411. lt-=(d-r); // losing part of tail
  412. }
  413. if (lt) memmove((void *)(e+d),e,lt);
  414. if (!re->clarion) *((char *)(s+(lr+lt))) = 0; // terminate
  415. }
  416. else if (lr<lo) {
  417. size32_t d2 = lo-lr; // delta
  418. // must be enough room so fairly simple
  419. if (re->clarion) {
  420. memmove((void *)(e-d2),e,lt);
  421. memset((void *)(e+(lt-d2)),' ',d2);
  422. }
  423. else
  424. memmove((void *)(e-lo+lr),e,lt+1);
  425. }
  426. memcpy((void *)s,rs,lr);
  427. re->adjustptrs(e,lo,lr);
  428. }
  429. static void dosubstitute(RegExpr *re,StringBuffer &out,char *s)
  430. {
  431. for (char* b= strchr(s,'#');b;b=strchr(b+1,'#')) {
  432. char c = b[1];
  433. if (c=='#') {
  434. *(++b)=0;
  435. out.append(s);
  436. s = b+1;
  437. }
  438. else if (!isdigit(c))
  439. continue;
  440. else {
  441. (*b++)=0;
  442. out.append(s);
  443. re->findstr(out,c-'0');
  444. }
  445. s = b+1; // reset start
  446. }
  447. out.append(s);
  448. }
  449. const char * RegExpr::substitute(StringBuffer &out,const char *mask,...)
  450. {
  451. char * str = (char *)malloc(MAXSUBST);
  452. va_list ap;
  453. va_start(ap,mask);
  454. vsprintf(str,mask,ap);
  455. va_end(ap);
  456. dosubstitute(this,out,str);
  457. free(str);
  458. return (char*)out.str();
  459. }
  460. void RegExpr::kill()
  461. // releases extra storage used by RegularExpressionClass
  462. {
  463. delete re;
  464. re = NULL;
  465. }
  466. char *RECOMP::reg (bool paren, REGFLAGS &flags)
  467. {
  468. char *ret;
  469. char *br;
  470. char *ender;
  471. int parno;
  472. flags = HASWIDTH; /* Tentatively. */
  473. /* Make an OPEN node, if parenthesized. */
  474. if (paren) {
  475. if (npar >= NSUBEXP)
  476. FAIL("too many {}");
  477. parno = npar;
  478. npar++;
  479. ret = rnode((char)(OPEN+parno));
  480. } else
  481. ret = NULL;
  482. /* Pick up the branches, linking them together. */
  483. REGFLAGS bflags;
  484. br = branch(bflags);
  485. if (br == NULL)
  486. return(NULL);
  487. if (ret != NULL)
  488. tail(ret, br); /* OPEN -> first. */
  489. else
  490. ret = br;
  491. if (!(bflags&HASWIDTH))
  492. flags &= ~HASWIDTH;
  493. flags |= bflags&SPSTART;
  494. while (*parse == '|') {
  495. parse++;
  496. br = branch(bflags);
  497. if (br == NULL)
  498. return(NULL);
  499. tail(ret, br); /* BRANCH -> BRANCH. */
  500. if (!(bflags&HASWIDTH))
  501. flags &= ~HASWIDTH;
  502. flags |= bflags&SPSTART;
  503. }
  504. /* Make a closing node, and hook it on the end. */
  505. ender = rnode((char)((paren) ? CLOSE+parno : END));
  506. tail(ret, ender);
  507. /* Hook the tails of the branches to the closing node. */
  508. for (br = ret; br != NULL; br = next(br))
  509. optail(br, ender);
  510. /* Check for proper termination. */
  511. if (paren && *parse++ != SUBPARENR) {
  512. FAIL("unmatched {}");
  513. } else if (!paren && *parse != '\0') {
  514. if (*parse == SUBPARENR) {
  515. FAIL("unmatched {}");
  516. } else
  517. FAIL("junk on end"); /* "Can't happen". */
  518. /* NOTREACHED */
  519. }
  520. return(ret);
  521. }
  522. char *RECOMP::branch (REGFLAGS &flags)
  523. /*
  524. - branch - one alternative of an | operator
  525. *
  526. * Implements the concatenation operator.
  527. */
  528. {
  529. char *ret;
  530. char *chain;
  531. char *latest;
  532. flags = WORST; /* Tentatively. */
  533. ret = rnode(BRANCH);
  534. chain = NULL;
  535. REGFLAGS pflags;
  536. while (*parse != '\0' && *parse != '|' && *parse != SUBPARENR) {
  537. latest = piece(pflags);
  538. if (latest == NULL)
  539. return(NULL);
  540. flags |= pflags&HASWIDTH;
  541. if (chain == NULL) /* First piece. */
  542. flags |= pflags&SPSTART;
  543. else
  544. tail(chain, latest);
  545. chain = latest;
  546. }
  547. if (chain == NULL) /* Loop ran zero times. */
  548. (void) rnode(NOTHING);
  549. return(ret);
  550. }
  551. char *RECOMP::piece (REGFLAGS &flags)
  552. /*
  553. - piece - something followed by possible [*+?]
  554. *
  555. * Note that the branching code sequences used for ? and the general cases
  556. * of * and + are somewhat optimized: they use the same NOTHING node as
  557. * both the endmarker for their branch list and the body of the last branch.
  558. * It might seem that this node could be dispensed with entirely, but the
  559. * endmarker role is not redundant.
  560. */
  561. {
  562. char *ret;
  563. char op;
  564. char *next;
  565. REGFLAGS aflags;
  566. ret = atom(aflags);
  567. if (ret == NULL)
  568. return(NULL);
  569. op = *parse;
  570. if (!ISMULT(op)) {
  571. flags = aflags;
  572. return(ret);
  573. }
  574. if (!(aflags&HASWIDTH) && op != '?')
  575. FAIL("*+ operand could be empty");
  576. flags = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
  577. if (op == '*' && (aflags&SIMPLE))
  578. insert(STAR, ret);
  579. else if (op == '*') {
  580. /* Emit x* as (x&|), where & means "self". */
  581. insert(BRANCH, ret); /* Either x */
  582. optail(ret, rnode(BACK)); /* and loop */
  583. optail(ret, ret); /* back */
  584. tail(ret, rnode(BRANCH)); /* or */
  585. tail(ret, rnode(NOTHING)); /* null. */
  586. } else if (op == '+' && (aflags&SIMPLE))
  587. insert(PLUS, ret);
  588. else if (op == '+') {
  589. /* Emit x+ as x(&|), where & means "self". */
  590. next = rnode(BRANCH); /* Either */
  591. tail(ret, next);
  592. tail(rnode(BACK), ret); /* loop back */
  593. tail(next, rnode(BRANCH)); /* or */
  594. tail(ret, rnode(NOTHING)); /* null. */
  595. } else if (op == '?') {
  596. /* Emit x? as (x|) */
  597. insert(BRANCH, ret); /* Either x */
  598. tail(ret, rnode(BRANCH)); /* or */
  599. next = rnode(NOTHING); /* null. */
  600. tail(ret, next);
  601. optail(ret, next);
  602. }
  603. parse++;
  604. if (ISMULT(*parse))
  605. FAIL("nested *?+");
  606. return(ret);
  607. }
  608. char *RECOMP::atom (REGFLAGS &flags)
  609. /*
  610. - atom - the lowest level
  611. *
  612. * Optimization: gobbles an entire sequence of ordinary characters so that
  613. * it can turn them into a single node, which is smaller to store and
  614. * faster to run. Backslashed characters are exceptions, each becoming a
  615. * separate node; the code is simpler that way and it's not worth fixing.
  616. */
  617. {
  618. char *ret;
  619. flags = WORST; /* Tentatively. */
  620. switch (*parse++) {
  621. case '^':
  622. ret = rnode(BOL);
  623. break;
  624. case '$':
  625. ret = rnode(EOL);
  626. break;
  627. case '.':
  628. ret = rnode(ANY);
  629. flags |= HASWIDTH|SIMPLE;
  630. break;
  631. case '[': {
  632. int clss;
  633. int clssend;
  634. if ((*parse == '^') || (*parse == '~')) { /* Complement of range. */
  635. ret = rnode(ANYBUT);
  636. parse++;
  637. } else
  638. ret = rnode(ANYOF);
  639. if (*parse == ']' || *parse == '-')
  640. REGC(*parse++);
  641. while (*parse != '\0' && *parse != ']') {
  642. if (*parse == '-') {
  643. parse++;
  644. if (*parse == ']' || *parse == '\0')
  645. REGC('-');
  646. else {
  647. clss = UCHARAT(parse-2)+1;
  648. clssend = UCHARAT(parse);
  649. if (clss > clssend+1)
  650. FAIL("invalid [] range");
  651. for (; clss <= clssend; clss++)
  652. REGC((char) clss);
  653. parse++;
  654. }
  655. } else
  656. REGC(*parse++);
  657. }
  658. REGC('\0');
  659. if (*parse != ']')
  660. FAIL("unmatched []");
  661. parse++;
  662. flags |= HASWIDTH|SIMPLE;
  663. }
  664. break;
  665. case SUBPARENL: {
  666. REGFLAGS sflags;
  667. ret = reg(1, sflags);
  668. if (ret == NULL)
  669. return(NULL);
  670. flags |= sflags&(HASWIDTH|SPSTART);
  671. }
  672. break;
  673. case '\0':
  674. case '|':
  675. case SUBPARENR:
  676. FAIL("internal urp"); /* Supposed to be caught earlier. */
  677. break;
  678. case '?':
  679. case '+':
  680. case '*':
  681. FAIL("?+* follows nothing");
  682. break;
  683. case '\\':
  684. if (*parse == '\0')
  685. FAIL("trailing \\");
  686. ret = rnode(EXACTLY);
  687. REGC(*parse++);
  688. REGC('\0');
  689. flags |= HASWIDTH|SIMPLE;
  690. break;
  691. default: {
  692. memsize_t len;
  693. char ender;
  694. parse--;
  695. len = strcspn(parse, META);
  696. if (len <= 0)
  697. FAIL("internal disaster");
  698. ender = *(parse+len);
  699. if (len > 1 && ISMULT(ender))
  700. len--; /* Back off clear of ?+* operand. */
  701. flags |= HASWIDTH;
  702. if (len == 1)
  703. flags |= SIMPLE;
  704. ret = rnode(EXACTLY);
  705. while (len > 0) {
  706. REGC(*parse++);
  707. len--;
  708. }
  709. REGC('\0');
  710. }
  711. break;
  712. }
  713. return(ret);
  714. }
  715. char *RECOMP::rnode (char op)
  716. /*
  717. - rnode - emit a node
  718. */
  719. {
  720. char *ret = code;
  721. REGC(op);
  722. REGC(0);
  723. REGC(0);
  724. return(ret);
  725. }
  726. void RECOMP::insert (char op, char *opnd)
  727. /*
  728. - insert - insert an operator in front of already-emitted operand
  729. *
  730. * Means relocating the operand.
  731. */
  732. {
  733. char *src=code;
  734. code+=3;
  735. char *dst=code;
  736. while (src > opnd)
  737. *--dst = *--src;
  738. char *place = (char *)opnd; /* Op node, where operand used to be. */
  739. *place++ = op;
  740. *place++ = '\0';
  741. *place++ = '\0';
  742. }
  743. void RECOMP::tail (char *p, char *val)
  744. /*
  745. - tail - set the next-pointer at the end of a node chain
  746. */
  747. {
  748. char *scan;
  749. char *temp;
  750. int offset;
  751. /* Find last node. */
  752. scan = p;
  753. for (;;) {
  754. temp = next(scan);
  755. if (temp == NULL)
  756. break;
  757. scan = temp;
  758. }
  759. if (OP(scan) == BACK)
  760. offset = scan - val;
  761. else
  762. offset = val - scan;
  763. *(scan+1) = (char) ((offset>>8)&0377);
  764. *(scan+2) = (char) (offset&0377);
  765. }
  766. void RECOMP::optail (char *p, char *val)
  767. /*
  768. - optail - tail on operand of first argument; nop if operandless
  769. */
  770. {
  771. /* "Operandless" and "op != BRANCH" are synonymous in practice. */
  772. if (p == NULL || OP(p) != BRANCH)
  773. return;
  774. tail(OPERAND(p), val);
  775. }
  776. char *RECOMP::next (char *p)
  777. /*
  778. - next - dig the "next" pointer out of a node
  779. */
  780. {
  781. int offset = NEXT(p);
  782. if (offset == 0)
  783. return(NULL);
  784. if (OP(p) == BACK)
  785. return(p-offset);
  786. else
  787. return(p+offset);
  788. }
  789. /*
  790. - rtry - try match at specific point
  791. */
  792. char * RECOMP::rtry (const char *string)
  793. {
  794. input = string;
  795. startp = s_start;
  796. endp = s_end;
  797. _clear(s_start);
  798. _clear(s_end);
  799. if (match(program)) {
  800. s_start[0] = string;
  801. s_end[0] = input;
  802. return (char *)string;
  803. }
  804. return NULL;
  805. }
  806. bool RECOMP::match (char *prog)
  807. {
  808. char *scan; /* Current node. */
  809. char *n; /* Next node. */
  810. scan = prog;
  811. while (scan != NULL) {
  812. n = next(scan);
  813. switch (OP(scan)) {
  814. case BOL:
  815. if (input != bol)
  816. return false;
  817. break;
  818. case EOL:
  819. if (clarion) {
  820. if (!claeol(input))
  821. return false;
  822. }
  823. else if (!eob(input))
  824. return false;
  825. break;
  826. case ANY:
  827. if (eob(input))
  828. return false;
  829. input++;
  830. break;
  831. case EXACTLY: {
  832. memsize_t len;
  833. char *opnd;
  834. opnd = OPERAND(scan);
  835. /* Inline the first character, for speed. */
  836. if (!equch(*opnd,*input))
  837. return false;
  838. len = strlen(opnd);
  839. if (len > 1 && !strnequ(input, opnd, (size32_t)len))
  840. return false;
  841. input += len;
  842. }
  843. break;
  844. case ANYOF:
  845. if (eob(input) || strchr(OPERAND(scan), *input) == NULL)
  846. return false;
  847. input++;
  848. break;
  849. case ANYBUT:
  850. if (eob(input) || strchr(OPERAND(scan), *input) != NULL)
  851. return false;
  852. input++;
  853. break;
  854. case NOTHING:
  855. break;
  856. case BACK:
  857. break;
  858. case OPEN+1:
  859. case OPEN+2:
  860. case OPEN+3:
  861. case OPEN+4:
  862. case OPEN+5:
  863. case OPEN+6:
  864. case OPEN+7:
  865. case OPEN+8:
  866. case OPEN+9: {
  867. int no;
  868. const char *save;
  869. no = OP(scan) - OPEN;
  870. save = input;
  871. if (match(n)) {
  872. /*
  873. * Don't set start if some later
  874. * invocation of the same parentheses
  875. * already has.
  876. */
  877. if (startp[no] == NULL)
  878. startp[no] = save;
  879. return true;
  880. } else
  881. return false;
  882. }
  883. break;
  884. case CLOSE+1:
  885. case CLOSE+2:
  886. case CLOSE+3:
  887. case CLOSE+4:
  888. case CLOSE+5:
  889. case CLOSE+6:
  890. case CLOSE+7:
  891. case CLOSE+8:
  892. case CLOSE+9: {
  893. int no;
  894. const char *save;
  895. no = OP(scan) - CLOSE;
  896. save = input;
  897. if (match(n)) {
  898. /*
  899. * Don't set end if some later
  900. * invocation of the same parentheses
  901. * already has.
  902. */
  903. if (endp[no] == NULL)
  904. endp[no] = save;
  905. return true;
  906. } else
  907. return false;
  908. }
  909. break;
  910. case BRANCH: {
  911. const char *save;
  912. if (OP(n) != BRANCH) /* No choice. */
  913. n = OPERAND(scan); /* Avoid recursion. */
  914. else {
  915. do {
  916. save = input;
  917. if (match(OPERAND(scan)))
  918. return true;
  919. input = save;
  920. scan = next(scan);
  921. } while (scan != NULL && OP(scan) == BRANCH);
  922. return false;
  923. /* NOTREACHED */
  924. }
  925. }
  926. break;
  927. case STAR:
  928. case PLUS: {
  929. char nextch;
  930. int no;
  931. const char *save;
  932. int min;
  933. /*
  934. * Lookahead to avoid useless match attempts
  935. * when we know what character comes n.
  936. */
  937. nextch = '\0';
  938. if (OP(n) == EXACTLY)
  939. nextch = *OPERAND(n);
  940. min = (OP(scan) == STAR) ? 0 : 1;
  941. save = input;
  942. no = repeat(OPERAND(scan));
  943. while (no >= min) {
  944. /* If it could work, try it. */
  945. if (nextch == '\0' || equch(*input,nextch))
  946. if (match(n))
  947. return true;
  948. /* Couldn't or didn't -- back up. */
  949. no--;
  950. input = save + no;
  951. }
  952. return false;
  953. }
  954. break;
  955. case END:
  956. return true; /* Success! */
  957. break;
  958. default:
  959. assertex(!"memory corruption");
  960. return false;
  961. break;
  962. }
  963. scan = n;
  964. }
  965. /*
  966. * We get here only if there's trouble -- normally "case END" is
  967. * the terminating point.
  968. */
  969. assertex(!"corrupted pointers");
  970. return false;
  971. }
  972. int RECOMP::repeat (char *p)
  973. /*
  974. - regrepeat - repeatedly match something simple, report how many
  975. */
  976. {
  977. int count = 0;
  978. const char *scan = input;
  979. char *opnd = OPERAND(p);
  980. switch (OP(p)) {
  981. case ANY:
  982. count = rstrlen(scan);
  983. scan += count;
  984. break;
  985. case EXACTLY:
  986. while (equch(*opnd,*scan)) {
  987. count++;
  988. scan++;
  989. }
  990. break;
  991. case ANYOF:
  992. while (!eob(scan) && strchr(opnd, *scan) != NULL) { // NB not rstrchr!
  993. count++;
  994. scan++;
  995. }
  996. break;
  997. case ANYBUT:
  998. while (!eob(scan) && strchr(opnd, *scan) == NULL) { // NB nnot rstrchr
  999. count++;
  1000. scan++;
  1001. }
  1002. break;
  1003. default: /* Oh dear. Called inappropriately. */
  1004. assertex(!"internal foulup");
  1005. count = 0; /* Best compromise. */
  1006. break;
  1007. }
  1008. input = scan;
  1009. return(count);
  1010. }
  1011. void RECOMP::adjustptrs(const char *e,size32_t lo,size32_t lr)
  1012. {
  1013. if (lo==lr) return;
  1014. size32_t o=e-findstart;
  1015. for (int i=0;i<NSUBEXP;i++) {
  1016. const char *s= s_start[i];
  1017. if (s) {
  1018. size32_t so = s-findstart;
  1019. if (so>=o) {
  1020. s_start[i]=s+lr-lo;
  1021. }
  1022. so = s_end[i]-findstart;
  1023. if (so>=o)
  1024. s_end[i]+=lr-lo;
  1025. }
  1026. }
  1027. findend+=(lr-lo);
  1028. }
  1029. const char *RECOMP::rstrchr(const char *s,int c)
  1030. {
  1031. if (nocase) {
  1032. c = toupper(c);
  1033. while (s!=findend) {
  1034. if (toupper(*s)==c) return s;
  1035. s++;
  1036. }
  1037. }
  1038. else {
  1039. while (s!=findend) {
  1040. if (*s==c) return s;
  1041. s++;
  1042. }
  1043. }
  1044. return NULL;
  1045. }
  1046. bool RECOMP::strnequ(const char *s1,const char *s2,size32_t n)
  1047. { // s1 is in regsearch
  1048. if (findend-s1 < (signed)n) return false;
  1049. if (nocase) {
  1050. while (n--) {
  1051. if (toupper(*s1)!=toupper(*s2)) return false;
  1052. s1++;
  1053. s2++;
  1054. }
  1055. }
  1056. else {
  1057. while (n--) {
  1058. if (*s1!=*s2) return false;
  1059. s1++;
  1060. s2++;
  1061. }
  1062. }
  1063. return true;
  1064. }
  1065. bool RECOMP::claeol(const char *s)
  1066. {
  1067. do {
  1068. if (eob(s)) return true;
  1069. }
  1070. while ((*(s++))==' ');
  1071. return false;
  1072. }
  1073. unsigned char xlat[26]={0,'1','2','3',0,'1','2',0,0,'2','2','4','5','5',0,'1','2','6','2','3',0,'1',0,'2',0,'2'};
  1074. static char *SoundexCode(const char *s,int l,char *res)
  1075. {
  1076. char *r=res;
  1077. r[1] = '0';
  1078. r[2] = '0';
  1079. r[3] = '0';
  1080. r[4] = 0;
  1081. loop {
  1082. if (!l||!*s) {
  1083. *r = '!';
  1084. return res;
  1085. }
  1086. if (isalpha(*s)) break;
  1087. s++;
  1088. l--;
  1089. }
  1090. char c=toupper(*s);
  1091. *r = c;
  1092. r++; s++;
  1093. char dl = ((c>='A')&&(c<='Z'))?xlat[c-'A']:0;
  1094. while (l&&*s) {
  1095. c = toupper(*s);
  1096. s++;
  1097. l--;
  1098. if ((c>='A')&&(c<='Z')) {
  1099. char d = xlat[c-'A'];
  1100. if (d) {
  1101. if(d!=dl) {
  1102. *r = d;
  1103. r++;
  1104. if (!*r) break;
  1105. }
  1106. }
  1107. else if (c != 'H' && c != 'W')
  1108. dl = d;
  1109. }
  1110. }
  1111. return res;
  1112. }
  1113. static bool WildMatchN ( const char *src, int srclen, int srcidx,
  1114. const char *pat, int patlen, int patidx,int nocase)
  1115. {
  1116. char next_char;
  1117. for (;;) {
  1118. if (patidx == patlen)
  1119. return (srcidx == srclen);
  1120. next_char = pat[patidx++];
  1121. if (next_char == '?') {
  1122. if (srcidx == srclen)
  1123. return false;
  1124. srcidx++;
  1125. }
  1126. else if (next_char != '*') {
  1127. if (nocase) {
  1128. if ((srcidx == srclen) ||
  1129. (toupper(src[srcidx])!=toupper(next_char)))
  1130. return false;
  1131. }
  1132. else
  1133. if ((srcidx == srclen) || (src[srcidx]!=next_char))
  1134. return false;
  1135. srcidx++;
  1136. }
  1137. else {
  1138. loop {
  1139. if (patidx == patlen)
  1140. return true;
  1141. if (pat[patidx] != '*')
  1142. break;
  1143. patidx++;
  1144. }
  1145. loop {
  1146. //No need to guard patLen since guaranteed to contain an ASTERISK
  1147. const char tail_char = pat[patlen-1];
  1148. if (tail_char == '*')
  1149. break;
  1150. if (srcidx == srclen)
  1151. return false;
  1152. if (tail_char != '?') {
  1153. if (nocase) {
  1154. if ((toupper(tail_char)!=toupper(src[srclen-1])))
  1155. return false;
  1156. }
  1157. else {
  1158. if ((tail_char!=src[srclen-1]))
  1159. return false;
  1160. }
  1161. }
  1162. patlen--;
  1163. srclen--;
  1164. if (patidx == patlen)
  1165. return true;
  1166. }
  1167. while (srcidx < srclen) {
  1168. if (WildMatchN(src,srclen,srcidx,
  1169. pat, patlen, patidx,nocase))
  1170. return true;
  1171. srcidx++;
  1172. }
  1173. return false;
  1174. }
  1175. }
  1176. }
  1177. bool jlib_decl WildMatch(const char *src, int srclen, const char *pat, int patlen,bool nocase)
  1178. {
  1179. return WildMatchN(src,srclen,0,pat,patlen,0,nocase);
  1180. }
  1181. bool jlib_decl WildMatch(const char *src, const char *pat, bool nocase)
  1182. {
  1183. return WildMatch(src,(size32_t)strlen(src),pat,(size32_t)strlen(pat),nocase);
  1184. }
  1185. static bool WildMatchNreplace ( const char *src, int srclen, int srcidx,
  1186. const char *pat, int patlen, int patidx,
  1187. int nocase,
  1188. UnsignedArray &wild, UnsignedArray &wildlen
  1189. )
  1190. {
  1191. unsigned wl = wild.ordinality();
  1192. char next_char;
  1193. for (;;) {
  1194. if (patidx == patlen) {
  1195. if (srcidx == srclen)
  1196. return true;
  1197. goto Fail;
  1198. }
  1199. next_char = pat[patidx++];
  1200. if (next_char == '?') {
  1201. if (srcidx == srclen)
  1202. goto Fail;
  1203. wild.append(srcidx++);
  1204. wildlen.append(1);
  1205. }
  1206. else if (next_char != '*') {
  1207. if (nocase) {
  1208. if ((srcidx == srclen) ||
  1209. (toupper(src[srcidx])!=toupper(next_char)))
  1210. goto Fail;
  1211. }
  1212. else
  1213. if ((srcidx == srclen) || (src[srcidx]!=next_char))
  1214. goto Fail;
  1215. srcidx++;
  1216. }
  1217. else {
  1218. loop {
  1219. if (patidx == patlen) {
  1220. wild.append(srcidx);
  1221. wildlen.append(srclen-srcidx);
  1222. return true;
  1223. }
  1224. wild.append(srcidx);
  1225. wildlen.append(0); // placemarker
  1226. if (pat[patidx] != '*')
  1227. break;
  1228. patidx++; // someone being silly!
  1229. }
  1230. while (srcidx < srclen) {
  1231. if (WildMatchNreplace(src,srclen,srcidx,
  1232. pat, patlen, patidx,nocase, wild,wildlen))
  1233. return true;
  1234. wildlen.append(wildlen.pop()+1); // prob can do a bit better than this!
  1235. srcidx++;
  1236. }
  1237. break; // fail
  1238. }
  1239. }
  1240. Fail:
  1241. unsigned pn = wild.ordinality()-wl;
  1242. if (pn) {
  1243. wild.popn(pn);
  1244. wildlen.popn(pn);
  1245. }
  1246. return false;
  1247. }
  1248. bool jlib_decl WildMatchReplace(const char *src, const char *pat, const char *repl, bool nocase, StringBuffer &out)
  1249. {
  1250. UnsignedArray wild;
  1251. UnsignedArray wildlen;
  1252. if (!WildMatchNreplace(src,(size32_t)strlen(src),0,pat,(size32_t)strlen(pat),0,nocase,wild,wildlen))
  1253. return false;
  1254. loop {
  1255. char c = *(repl++);
  1256. if (!c)
  1257. break;
  1258. if (c!='$')
  1259. out.append(c);
  1260. else {
  1261. char c2 = *(repl++);
  1262. if (!c2) {
  1263. out.append(c);
  1264. break;
  1265. }
  1266. if (c2=='$')
  1267. out.append(c);
  1268. else {
  1269. unsigned idx = c2-'0';
  1270. if (idx==0)
  1271. out.append(src);
  1272. else if ((idx<=9)&&(idx<=wild.ordinality()))
  1273. out.append(wildlen.item(idx-1),src+wild.item(idx-1));
  1274. else
  1275. out.append(c).append(c2);
  1276. }
  1277. }
  1278. }
  1279. return true;
  1280. }
  1281. bool jlib_decl SoundexMatch(const char *src, const char *pat)
  1282. {
  1283. char s1[5];
  1284. char s2[5];
  1285. return memcmp(SoundexCode(src,(size32_t)strlen(src),s1),SoundexCode(pat,(size32_t)strlen(pat),s2),4)==0;
  1286. }
  1287. //---------------------------------------------------------------------------
  1288. StringMatcher::StringMatcher()
  1289. {
  1290. for (unsigned idx=0; idx < 256; idx++)
  1291. {
  1292. firstLevel[idx].value = 0;
  1293. firstLevel[idx].table = NULL;
  1294. }
  1295. }
  1296. void StringMatcher::freeLevel(entry * elems)
  1297. {
  1298. for (unsigned idx = 0; idx < 256; idx++)
  1299. {
  1300. if (elems[idx].table)
  1301. {
  1302. freeLevel(elems[idx].table);
  1303. free(elems[idx].table);
  1304. elems[idx].table = NULL;
  1305. }
  1306. elems[idx].value = 0;
  1307. }
  1308. }
  1309. StringMatcher::~StringMatcher()
  1310. {
  1311. freeLevel(firstLevel);
  1312. }
  1313. void StringMatcher::addEntry(const char * text, unsigned action)
  1314. {
  1315. if (!queryAddEntry((size32_t)strlen(text), text, action))
  1316. throw MakeStringException(-1, "Duplicate entry \"%s\" added to string matcher", text);
  1317. }
  1318. void StringMatcher::addEntry(unsigned len, const char * text, unsigned action)
  1319. {
  1320. if (!queryAddEntry(len, text, action))
  1321. throw MakeStringException(-1, "Duplicate entry \"%*s\" added to string matcher", len, text);
  1322. }
  1323. bool StringMatcher::queryAddEntry(unsigned len, const char * text, unsigned action)
  1324. {
  1325. if (len == 0)
  1326. return false;
  1327. entry * curTable = firstLevel;
  1328. loop
  1329. {
  1330. byte c = *text++;
  1331. entry & curElement = curTable[c];
  1332. if (--len == 0)
  1333. {
  1334. if (curElement.value != 0)
  1335. return false;
  1336. curElement.value = action;
  1337. return true;
  1338. }
  1339. if (!curElement.table)
  1340. curElement.table = (entry *)calloc(sizeof(entry), 256);
  1341. curTable = curElement.table;
  1342. }
  1343. }
  1344. unsigned StringMatcher::getMatch(unsigned maxLen, const char * text, unsigned & matchLen)
  1345. {
  1346. unsigned bestValue = 0;
  1347. unsigned bestLen = 0;
  1348. if (maxLen)
  1349. {
  1350. const byte * start = (const byte *)text;
  1351. const byte * cursor = (const byte *)text;
  1352. const byte * end = (const byte *)cursor+maxLen;
  1353. byte next = *cursor++;
  1354. entry * cur = &firstLevel[next];
  1355. while ((cursor != end) && cur->table)
  1356. {
  1357. if (cur->value)
  1358. {
  1359. bestValue = cur->value;
  1360. bestLen = cursor-start;
  1361. }
  1362. next = *cursor++;
  1363. cur = &cur->table[next];
  1364. }
  1365. if (cur->value)
  1366. {
  1367. matchLen = cursor-start;
  1368. return cur->value;
  1369. }
  1370. }
  1371. matchLen = bestLen;
  1372. return bestValue;
  1373. }
  1374. void addActionList(StringMatcher & matcher, const char * text, unsigned action, unsigned * maxElementLength)
  1375. {
  1376. if (!text)
  1377. return;
  1378. unsigned idx=0;
  1379. while (*text)
  1380. {
  1381. StringBuffer str;
  1382. while (*text)
  1383. {
  1384. char next = *text++;
  1385. if (next == ',')
  1386. break;
  1387. if (next == '\\' && *text)
  1388. {
  1389. next = *text++;
  1390. switch (next)
  1391. {
  1392. case 'r': next = '\r'; break;
  1393. case 'n': next = '\n'; break;
  1394. case 't': next = '\t'; break;
  1395. case 'x':
  1396. //hex constant - at least we can define spaces then...
  1397. if (text[0] && text[1])
  1398. {
  1399. next = (hex2num(*text) << 4) | hex2num(text[1]);
  1400. text+=2;
  1401. }
  1402. break;
  1403. default:
  1404. break; //otherwise \ just quotes the character e.g. \,
  1405. }
  1406. }
  1407. str.append(next);
  1408. }
  1409. if (str.length())
  1410. {
  1411. matcher.addEntry(str.str(), action+(idx++<<8));
  1412. if (maxElementLength && (str.length() > *maxElementLength))
  1413. *maxElementLength = str.length();
  1414. }
  1415. }
  1416. }
  1417. //---------------------------------------------------------------------------
  1418. #if 0
  1419. #define MATCHsimple 0
  1420. #define MATCHwild 1
  1421. #define MATCHregular 2
  1422. #define MATCHsoundex 3
  1423. #define MATCHmask 0x0f
  1424. #define MATCHnocase 0x10
  1425. static class _MatchRE : public RegExpr
  1426. {
  1427. public:
  1428. bool init(const char *rexpr,int nocase) {
  1429. if (!cachere||(cachenocase!=nocase)||!strequ(cachere,rexpr)) {
  1430. free(cachere);
  1431. cachere = strdup(rexpr);
  1432. cachenocase = (unsigned char)nocase;
  1433. return RegExpr::init(cachere,cachenocase);
  1434. }
  1435. return true;
  1436. }
  1437. _MatchRE() { cachere=NULL; }
  1438. ~_MatchRE() { free(cachere); }
  1439. private:
  1440. char *cachere;
  1441. unsigned char cachenocase;
  1442. } MatchRE;
  1443. extern "Pascal"
  1444. long Cla$MATCH(/* STRING s, STRING p, */ unsigned char flags)
  1445. {
  1446. StringBuffer s;
  1447. s.PopString();
  1448. s.clip();
  1449. StringBuffer p;
  1450. p.PopString();
  1451. p.clip();
  1452. int nocase = flags&MATCHnocase?1:0;
  1453. switch(flags&MATCHmask) {
  1454. case MATCHsimple: {
  1455. if (s.strlen()!=p.strlen()) return false;
  1456. if (nocase)
  1457. return striequ((char *)s,(char *)p);
  1458. return strequ((char *)s,(char *)p);
  1459. }
  1460. break;
  1461. case MATCHwild:
  1462. return WildMatch(s,s.strlen(),p,p.strlen(),nocase);
  1463. case MATCHregular: {
  1464. if (!MatchRE.init(p,nocase))
  1465. return false;
  1466. const char *fs=MatchRE.find(s,0,RE_ALL,0);
  1467. return (fs!=NULL);
  1468. }
  1469. break;
  1470. case MATCHsoundex: {
  1471. char s1[5];
  1472. char s2[5];
  1473. return memcmp(SoundexCode(s,s.strlen(),s1),SoundexCode(p,p.strlen(),s2),4)==0;
  1474. }
  1475. break;
  1476. }
  1477. return false;
  1478. }
  1479. #endif
  1480. //--------------------------------
  1481. // Testing
  1482. #ifdef _DEBUG
  1483. void tr (RegExpr &RE,const char *s,const char *p,const char *r=NULL,size32_t n=0,bool nocase=false)
  1484. {
  1485. PrintLog("Test '%s','%s','%s',%d,%s\r\n",s,p,r?r:"-",n,nocase?"NOCASE":"");
  1486. char l[256];
  1487. strcpy(l,s);
  1488. StringBuffer ds;
  1489. RE.init(p,nocase);
  1490. const char * f = RE.find(l,0,RE_ALL);
  1491. if (!f)
  1492. PrintLog("Not Found\r\n");
  1493. else {
  1494. PrintLog("Found '%s'\r\n",RE.findstr(ds));
  1495. for (int i = 1;i<=9;i++) {
  1496. size32_t s = RE.findlen(i);
  1497. if (s) {
  1498. ds.clear();
  1499. PrintLog("Found Sub %d,%d,'%s'\r\n",i,s,RE.findstr(ds,i));
  1500. }
  1501. }
  1502. }
  1503. if (r) {
  1504. RE.replace(r,sizeof(l));
  1505. PrintLog("Replace to '%s'\r\n",l);
  1506. }
  1507. }
  1508. #define QBF "the quick brown fox jumped over the lazy dogs"
  1509. #define RS "Nigel Was Here"
  1510. void RE$Test()
  1511. {
  1512. RegExpr RE;
  1513. tr(RE,QBF,"the",RS);
  1514. tr(RE,QBF,"quick",RS);
  1515. tr(RE,QBF,"dogs",RS);
  1516. tr(RE,QBF,"lazz",RS);
  1517. tr(RE,QBF,"laz.",RS);
  1518. tr(RE,QBF,"^laz.",RS);
  1519. tr(RE,QBF,"laz.$",RS);
  1520. tr(RE,QBF,"^the.",RS);
  1521. tr(RE,QBF,"dogs^",RS);
  1522. tr(RE,QBF,"^t.*dogs^",RS);
  1523. tr(RE,QBF,"dog.",RS);
  1524. tr(RE,QBF,".the",RS);
  1525. tr(RE,QBF,".he",RS);
  1526. tr(RE,QBF,".*",RS);
  1527. tr(RE,QBF,"q.*",RS);
  1528. tr(RE,QBF,"q.*z",RS);
  1529. tr(RE,QBF,"qu.*k",RS);
  1530. tr(RE,QBF,"d{[oa]g}s",RS);
  1531. tr(RE,QBF,"laz[a-z]",RS);
  1532. tr(RE,QBF,"{laz[a-z]} {dogs}",RS);
  1533. tr(RE,QBF,"the",RS,50);
  1534. tr(RE,QBF,"quick",RS,50);
  1535. tr(RE,QBF,"dogs",RS,50);
  1536. tr(RE,QBF,"lazz",RS,50);
  1537. tr(RE,QBF,"laz.",RS,50);
  1538. tr(RE,QBF,"^laz.",RS,50);
  1539. tr(RE,QBF,"laz.$",RS,50);
  1540. tr(RE,QBF,"^the.",RS,50);
  1541. tr(RE,QBF,"dogs^",RS,50);
  1542. tr(RE,QBF,"^t.*dogs^",RS,50);
  1543. tr(RE,QBF,"dog.",RS,50);
  1544. tr(RE,QBF,".the",RS,50);
  1545. tr(RE,QBF,".he",RS,50);
  1546. tr(RE,QBF,".*",RS,50);
  1547. tr(RE,QBF,"q.*",RS,50);
  1548. tr(RE,QBF,"q.*z",RS,50);
  1549. tr(RE,QBF,"qu.*k",RS,50);
  1550. tr(RE,QBF,"d{[oa]g}s",RS,50);
  1551. tr(RE,QBF,"laz[a-z]",RS,50);
  1552. tr(RE,QBF,"{laz[a-z]} {dogs}",RS,50);
  1553. tr(RE,"INRANGE (a,b)","[ ,]INRANGE *({.+},{.+})");
  1554. tr(RE," inrange (a,b)","[ ,]INRANGE *({.+},{.+})",NULL,0,true);
  1555. tr(RE,",INRANGE(aa,bb)","[ ,]INRANGE *({.+},{.+})");
  1556. tr(RE,",INRANGE(,bb)","[ ,]INRANGE *({.+},{.+})");
  1557. tr(RE,"10/14/1998","^{.*}/{.*}/{.*}$");
  1558. tr(RE,"freddy","^{|{.+}\\@}{.+}$");
  1559. tr(RE,"myname@freddy","^{|{.+}\\@}{.+}$");
  1560. tr(RE,"freddy","^{{.+}\\@|}{.+}$");
  1561. tr(RE,"myname@freddy","^{{.+}\\@|}{.+}$");
  1562. tr(RE,"freddy","^{[^@]+}@?{[^@]+}$");
  1563. tr(RE,"myname@freddy","^{.+}@{.+}$|{.+}$");
  1564. tr(RE,"freddy","^{|{.+}@}{[^@]+}$");
  1565. char str[256];
  1566. strcpy(str,"myname@freddy");
  1567. RE.init("^{|{.+}@}{[^@]+}$");
  1568. RE.find(str);
  1569. StringBuffer t;
  1570. PrintLog("Substitute to '%s'\r\n",RE.substitute(t,"#'#3###2'#"));
  1571. t.clear();
  1572. RE.replace(RE.findstr(t,2),sizeof(str),3);
  1573. t.clear();
  1574. RE.replace(RE.findstr(t,3),sizeof(str),2);
  1575. PrintLog("Replace to '%s'\r\n",str);
  1576. }
  1577. void FixDate(char *buff,size32_t max)
  1578. {
  1579. RegExpr RE("[0-9]+/[0-9]+/{[0-9]+}");
  1580. const char *s = RE.find(buff);
  1581. while (s) {
  1582. StringBuffer ys;
  1583. int y=atoi(RE.findstr(ys,1));
  1584. if (y<1000) {
  1585. ys.clear();
  1586. ys.append(y+1900);
  1587. RE.replace(ys.str(),max,1);
  1588. }
  1589. s = RE.findnext();
  1590. }
  1591. }
  1592. #endif