regex.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507
  1. /*************************************************************************/
  2. /* regex.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */
  9. /* */
  10. /* Permission is hereby granted, free of charge, to any person obtaining */
  11. /* a copy of this software and associated documentation files (the */
  12. /* "Software"), to deal in the Software without restriction, including */
  13. /* without limitation the rights to use, copy, modify, merge, publish, */
  14. /* distribute, sublicense, and/or sell copies of the Software, and to */
  15. /* permit persons to whom the Software is furnished to do so, subject to */
  16. /* the following conditions: */
  17. /* */
  18. /* The above copyright notice and this permission notice shall be */
  19. /* included in all copies or substantial portions of the Software. */
  20. /* */
  21. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  22. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  23. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  24. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  25. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  26. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  27. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  28. /*************************************************************************/
  29. #include "regex.h"
  30. #include <wctype.h>
  31. #include <wchar.h>
  32. static int RegEx_hex2int(const CharType c)
  33. {
  34. if ('0' <= c && c <= '9')
  35. return int(c - '0');
  36. else if ('a' <= c && c <= 'f')
  37. return int(c - 'a') + 10;
  38. else if ('A' <= c && c <= 'F')
  39. return int(c - 'A') + 10;
  40. return -1;
  41. }
  42. struct RegExSearch {
  43. Ref<RegExMatch> match;
  44. const CharType* str;
  45. int end;
  46. int eof;
  47. // For standard quantifier behaviour, test_parent is used to check the
  48. // rest of the pattern. If the pattern matches, to prevent the parent
  49. // from testing again, the complete flag is used as a shortcut out.
  50. bool complete;
  51. // With lookahead, the position needs to rewind to its starting position
  52. // when test_parent is used. Due to functional programming, this state
  53. // has to be kept as a parameter.
  54. Vector<int> lookahead_pos;
  55. CharType at(int p_pos) {
  56. return str[p_pos];
  57. }
  58. RegExSearch(Ref<RegExMatch>& p_match, int p_end, int p_lookahead) : match(p_match) {
  59. str = p_match->string.c_str();
  60. end = p_end;
  61. eof = p_match->string.length();
  62. complete = false;
  63. lookahead_pos.resize(p_lookahead);
  64. }
  65. };
  66. struct RegExNode {
  67. RegExNode* next;
  68. RegExNode* previous;
  69. RegExNode* parent;
  70. bool quantifiable;
  71. int length;
  72. RegExNode() {
  73. next = NULL;
  74. previous = NULL;
  75. parent = NULL;
  76. quantifiable = false;
  77. length = -1;
  78. }
  79. virtual ~RegExNode() {
  80. if (next)
  81. memdelete(next);
  82. }
  83. // For avoiding RTTI
  84. virtual bool is_look_behind() { return false; }
  85. virtual int test(RegExSearch& s, int pos) const {
  86. return next ? next->test(s, pos) : -1;
  87. }
  88. virtual int test_parent(RegExSearch& s, int pos) const {
  89. if (next)
  90. pos = next->test(s, pos);
  91. if (pos >= 0) {
  92. s.complete = true;
  93. if (parent)
  94. pos = parent->test_parent(s, pos);
  95. }
  96. if (pos < 0)
  97. s.complete = false;
  98. return pos;
  99. }
  100. void increment_length(int amount, bool subtract = false) {
  101. if (amount >= 0 && length >= 0) {
  102. if (!subtract)
  103. length += amount;
  104. else
  105. length -= amount;
  106. } else {
  107. length = -1;
  108. }
  109. if (parent)
  110. parent->increment_length(amount, subtract);
  111. }
  112. };
  113. struct RegExNodeChar : public RegExNode {
  114. CharType ch;
  115. RegExNodeChar(CharType p_char) {
  116. length = 1;
  117. quantifiable = true;
  118. ch = p_char;
  119. }
  120. virtual int test(RegExSearch& s, int pos) const {
  121. if (s.end <= pos || 0 > pos || s.at(pos) != ch)
  122. return -1;
  123. return next ? next->test(s, pos + 1) : pos + 1;
  124. }
  125. static CharType parse_escape(const CharType*& c) {
  126. int point = 0;
  127. switch (c[1]) {
  128. case 'x':
  129. for (int i = 2; i <= 3; ++i) {
  130. int res = RegEx_hex2int(c[i]);
  131. if (res == -1)
  132. return '\0';
  133. point = (point << 4) + res;
  134. }
  135. c = &c[3];
  136. return CharType(point);
  137. case 'u':
  138. for (int i = 2; i <= 5; ++i) {
  139. int res = RegEx_hex2int(c[i]);
  140. if (res == -1)
  141. return '\0';
  142. point = (point << 4) + res;
  143. }
  144. c = &c[5];
  145. return CharType(point);
  146. case '0': ++c; return '\0';
  147. case 'a': ++c; return '\a';
  148. case 'e': ++c; return '\e';
  149. case 'f': ++c; return '\f';
  150. case 'n': ++c; return '\n';
  151. case 'r': ++c; return '\r';
  152. case 't': ++c; return '\t';
  153. case 'v': ++c; return '\v';
  154. case 'b': ++c; return '\b';
  155. default: break;
  156. }
  157. return (++c)[0];
  158. }
  159. };
  160. struct RegExNodeRange : public RegExNode {
  161. CharType start;
  162. CharType end;
  163. RegExNodeRange(CharType p_start, CharType p_end) {
  164. length = 1;
  165. quantifiable = true;
  166. start = p_start;
  167. end = p_end;
  168. }
  169. virtual int test(RegExSearch& s, int pos) const {
  170. if (s.end <= pos || 0 > pos)
  171. return -1;
  172. CharType c = s.at(pos);
  173. if (c < start || end < c)
  174. return -1;
  175. return next ? next->test(s, pos + 1) : pos + 1;
  176. }
  177. };
  178. struct RegExNodeShorthand : public RegExNode {
  179. CharType repr;
  180. RegExNodeShorthand(CharType p_repr) {
  181. length = 1;
  182. quantifiable = true;
  183. repr = p_repr;
  184. }
  185. virtual int test(RegExSearch& s, int pos) const {
  186. if (s.end <= pos || 0 > pos)
  187. return -1;
  188. bool found = false;
  189. bool invert = false;
  190. CharType c = s.at(pos);
  191. switch (repr) {
  192. case '.':
  193. found = true;
  194. break;
  195. case 'W':
  196. invert = true;
  197. case 'w':
  198. found = (c == '_' || iswalnum(c) != 0);
  199. break;
  200. case 'D':
  201. invert = true;
  202. case 'd':
  203. found = ('0' <= c && c <= '9');
  204. break;
  205. case 'S':
  206. invert = true;
  207. case 's':
  208. found = (iswspace(c) != 0);
  209. break;
  210. default:
  211. break;
  212. }
  213. if (found == invert)
  214. return -1;
  215. return next ? next->test(s, pos + 1) : pos + 1;
  216. }
  217. };
  218. struct RegExNodeClass : public RegExNode {
  219. enum Type {
  220. Type_none,
  221. Type_alnum,
  222. Type_alpha,
  223. Type_ascii,
  224. Type_blank,
  225. Type_cntrl,
  226. Type_digit,
  227. Type_graph,
  228. Type_lower,
  229. Type_print,
  230. Type_punct,
  231. Type_space,
  232. Type_upper,
  233. Type_xdigit,
  234. Type_word
  235. };
  236. Type type;
  237. bool test_class(CharType c) const {
  238. static Vector<CharType> REGEX_NODE_SPACE = String(" \t\r\n\f");
  239. static Vector<CharType> REGEX_NODE_PUNCT = String("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~");
  240. switch (type) {
  241. case Type_alnum:
  242. if ('0' <= c && c <= '9') return true;
  243. if ('a' <= c && c <= 'z') return true;
  244. if ('A' <= c && c <= 'Z') return true;
  245. return false;
  246. case Type_alpha:
  247. if ('a' <= c && c <= 'z') return true;
  248. if ('A' <= c && c <= 'Z') return true;
  249. return false;
  250. case Type_ascii:
  251. return (0x00 <= c && c <= 0x7F);
  252. case Type_blank:
  253. return (c == ' ' || c == '\t');
  254. case Type_cntrl:
  255. return ((0x00 <= c && c <= 0x1F) || c == 0x7F);
  256. case Type_digit:
  257. return ('0' <= c && c <= '9');
  258. case Type_graph:
  259. return (0x20 < c && c < 0x7F);
  260. case Type_lower:
  261. return ('a' <= c && c <= 'z');
  262. case Type_print:
  263. return (0x1F < c && c < 0x1F);
  264. case Type_punct:
  265. return (REGEX_NODE_PUNCT.find(c) >= 0);
  266. case Type_space:
  267. return (REGEX_NODE_SPACE.find(c) >= 0);
  268. case Type_upper:
  269. return ('A' <= c && c <= 'Z');
  270. case Type_xdigit:
  271. if ('0' <= c && c <= '9') return true;
  272. if ('a' <= c && c <= 'f') return true;
  273. if ('A' <= c && c <= 'F') return true;
  274. return false;
  275. case Type_word:
  276. if ('0' <= c && c <= '9') return true;
  277. if ('a' <= c && c <= 'z') return true;
  278. if ('A' <= c && c <= 'Z') return true;
  279. return (c == '_');
  280. default:
  281. return false;
  282. }
  283. return false;
  284. }
  285. RegExNodeClass(Type p_type) {
  286. length = 1;
  287. quantifiable = true;
  288. type = p_type;
  289. }
  290. virtual int test(RegExSearch& s, int pos) const {
  291. if (s.end <= pos || 0 > pos)
  292. return -1;
  293. if (!test_class(s.at(pos)))
  294. return -1;
  295. return next ? next->test(s, pos + 1) : pos + 1;
  296. }
  297. #define REGEX_CMP_CLASS(POS, NAME) if (cmp_class(POS, #NAME)) return Type_ ## NAME
  298. static Type parse_type(const CharType*& p_pos) {
  299. REGEX_CMP_CLASS(p_pos, alnum);
  300. REGEX_CMP_CLASS(p_pos, alpha);
  301. REGEX_CMP_CLASS(p_pos, ascii);
  302. REGEX_CMP_CLASS(p_pos, blank);
  303. REGEX_CMP_CLASS(p_pos, cntrl);
  304. REGEX_CMP_CLASS(p_pos, digit);
  305. REGEX_CMP_CLASS(p_pos, graph);
  306. REGEX_CMP_CLASS(p_pos, lower);
  307. REGEX_CMP_CLASS(p_pos, print);
  308. REGEX_CMP_CLASS(p_pos, punct);
  309. REGEX_CMP_CLASS(p_pos, space);
  310. REGEX_CMP_CLASS(p_pos, upper);
  311. REGEX_CMP_CLASS(p_pos, xdigit);
  312. REGEX_CMP_CLASS(p_pos, word);
  313. return Type_none;
  314. }
  315. static bool cmp_class(const CharType*& p_pos, const char* p_text) {
  316. unsigned int i = 0;
  317. for (i = 0; p_text[i] != '\0'; ++i)
  318. if (p_pos[i] != p_text[i])
  319. return false;
  320. if (p_pos[i++] != ':' || p_pos[i] != ']')
  321. return false;
  322. p_pos = &p_pos[i];
  323. return true;
  324. }
  325. };
  326. struct RegExNodeAnchorStart : public RegExNode {
  327. RegExNodeAnchorStart() {
  328. length = 0;
  329. }
  330. virtual int test(RegExSearch& s, int pos) const {
  331. if (pos != 0)
  332. return -1;
  333. return next ? next->test(s, pos) : pos;
  334. }
  335. };
  336. struct RegExNodeAnchorEnd : public RegExNode {
  337. RegExNodeAnchorEnd() {
  338. length = 0;
  339. }
  340. virtual int test(RegExSearch& s, int pos) const {
  341. if (pos != s.eof)
  342. return -1;
  343. return next ? next->test(s, pos) : pos;
  344. }
  345. };
  346. struct RegExNodeWordBoundary : public RegExNode {
  347. bool inverse;
  348. RegExNodeWordBoundary(bool p_inverse) {
  349. length = 0;
  350. inverse = p_inverse;
  351. }
  352. virtual int test(RegExSearch& s, int pos) const {
  353. bool left = false;
  354. bool right = false;
  355. if (pos != 0) {
  356. CharType c = s.at(pos - 1);
  357. if (c == '_' || iswalnum(c))
  358. left = true;
  359. }
  360. if (pos != s.eof) {
  361. CharType c = s.at(pos);
  362. if (c == '_' || iswalnum(c))
  363. right = true;
  364. }
  365. if ((left == right) != inverse)
  366. return -1;
  367. return next ? next->test(s, pos) : pos;
  368. }
  369. };
  370. struct RegExNodeQuantifier : public RegExNode {
  371. int min;
  372. int max;
  373. bool greedy;
  374. RegExNode* child;
  375. RegExNodeQuantifier(int p_min, int p_max) {
  376. min = p_min;
  377. max = p_max;
  378. greedy = true;
  379. child = NULL;
  380. }
  381. ~RegExNodeQuantifier() {
  382. if (child)
  383. memdelete(child);
  384. }
  385. virtual int test(RegExSearch& s, int pos) const {
  386. return test_step(s, pos, 0, pos);
  387. }
  388. virtual int test_parent(RegExSearch& s, int pos) const {
  389. s.complete = false;
  390. return pos;
  391. }
  392. int test_step(RegExSearch& s, int pos, int level, int start) const {
  393. if (pos > s.end)
  394. return -1;
  395. if (!greedy && level > min) {
  396. int res = next ? next->test(s, pos) : pos;
  397. if (s.complete)
  398. return res;
  399. if (res >= 0 && parent->test_parent(s, res) >= 0)
  400. return res;
  401. }
  402. if (max >= 0 && level > max)
  403. return -1;
  404. int res = pos;
  405. if (level >= 1) {
  406. if (level > min + 1 && pos == start)
  407. return -1;
  408. res = child->test(s, pos);
  409. if (s.complete)
  410. return res;
  411. }
  412. if (res >= 0) {
  413. int res_step = test_step(s, res, level + 1, start);
  414. if (res_step >= 0)
  415. return res_step;
  416. if (greedy && level >= min) {
  417. if (next)
  418. res = next->test(s, res);
  419. if (s.complete)
  420. return res;
  421. if (res >= 0 && parent->test_parent(s, res) >= 0)
  422. return res;
  423. }
  424. }
  425. return -1;
  426. }
  427. };
  428. struct RegExNodeBackReference : public RegExNode {
  429. int id;
  430. RegExNodeBackReference(int p_id) {
  431. length = -1;
  432. quantifiable = true;
  433. id = p_id;
  434. }
  435. virtual int test(RegExSearch& s, int pos) const {
  436. RegExMatch::Group& ref = s.match->captures[id];
  437. for (int i = 0; i < ref.length; ++i) {
  438. if (pos + i >= s.end)
  439. return -1;
  440. if (s.at(ref.start + i) != s.at(pos + i))
  441. return -1;
  442. }
  443. return next ? next->test(s, pos + ref.length) : pos + ref.length;
  444. }
  445. };
  446. struct RegExNodeGroup : public RegExNode {
  447. bool inverse;
  448. bool reset_pos;
  449. Vector<RegExNode*> childset;
  450. RegExNode* back;
  451. RegExNodeGroup() {
  452. length = 0;
  453. quantifiable = true;
  454. inverse = false;
  455. reset_pos = false;
  456. back = NULL;
  457. }
  458. virtual ~RegExNodeGroup() {
  459. for (int i = 0; i < childset.size(); ++i)
  460. memdelete(childset[i]);
  461. }
  462. virtual int test(RegExSearch& s, int pos) const {
  463. for (int i = 0; i < childset.size(); ++i) {
  464. s.complete = false;
  465. int res = childset[i]->test(s, pos);
  466. if (s.complete)
  467. return res;
  468. if (inverse) {
  469. if (res < 0)
  470. res = pos + 1;
  471. else
  472. return -1;
  473. if (i + 1 < childset.size())
  474. continue;
  475. }
  476. if (res >= 0) {
  477. if (reset_pos)
  478. res = pos;
  479. return next ? next->test(s, res) : res;
  480. }
  481. }
  482. return -1;
  483. }
  484. void add_child(RegExNode* node) {
  485. node->parent = this;
  486. node->previous = back;
  487. if (back)
  488. back->next = node;
  489. else
  490. childset.push_back(node);
  491. increment_length(node->length);
  492. back = node;
  493. }
  494. void add_childset() {
  495. if (childset.size() > 0)
  496. length = -1;
  497. back = NULL;
  498. }
  499. RegExNode* swap_back(RegExNode* node) {
  500. RegExNode* old = back;
  501. if (old) {
  502. if (!old->previous)
  503. childset.remove(childset.size() - 1);
  504. back = old->previous;
  505. increment_length(old->length, true);
  506. }
  507. add_child(node);
  508. return old;
  509. }
  510. };
  511. struct RegExNodeCapturing : public RegExNodeGroup {
  512. int id;
  513. RegExNodeCapturing(int p_id = 0) {
  514. id = p_id;
  515. }
  516. virtual int test(RegExSearch& s, int pos) const {
  517. RegExMatch::Group& ref = s.match->captures[id];
  518. int old_start = ref.start;
  519. ref.start = pos;
  520. int res = RegExNodeGroup::test(s, pos);
  521. if (res >= 0) {
  522. if (!s.complete)
  523. ref.length = res - pos;
  524. } else {
  525. ref.start = old_start;
  526. }
  527. return res;
  528. }
  529. virtual int test_parent(RegExSearch& s, int pos) const {
  530. RegExMatch::Group& ref = s.match->captures[id];
  531. ref.length = pos - ref.start;
  532. return RegExNode::test_parent(s, pos);
  533. }
  534. static Variant parse_name(const CharType*& c, bool p_allow_numeric) {
  535. if (c[1] == '0') {
  536. return -1;
  537. } else if ('1' <= c[1] && c[1] <= '9') {
  538. if (!p_allow_numeric)
  539. return -1;
  540. int res = (++c)[0] - '0';
  541. while ('0' <= c[1] && c[1] <= '9')
  542. res = res * 10 + int((++c)[0] - '0');
  543. if ((++c)[0] != '>')
  544. return -1;
  545. return res;
  546. } else if (iswalnum(c[1])) {
  547. String res(++c, 1);
  548. while (iswalnum(c[1]))
  549. res += String(++c, 1);
  550. if ((++c)[0] != '>')
  551. return -1;
  552. return res;
  553. }
  554. return -1;
  555. }
  556. };
  557. struct RegExNodeLookAhead : public RegExNodeGroup {
  558. int id;
  559. RegExNodeLookAhead(bool p_inverse, int p_id = 0) {
  560. quantifiable = false;
  561. inverse = p_inverse;
  562. reset_pos = true;
  563. id = p_id;
  564. }
  565. virtual int test(RegExSearch& s, int pos) const {
  566. s.lookahead_pos[id] = pos;
  567. return RegExNodeGroup::test(s, pos);
  568. }
  569. virtual int test_parent(RegExSearch& s, int pos) const {
  570. return RegExNode::test_parent(s, s.lookahead_pos[id]);
  571. }
  572. };
  573. struct RegExNodeLookBehind : public RegExNodeGroup {
  574. RegExNodeLookBehind(bool p_inverse, int p_id = 0) {
  575. quantifiable = false;
  576. inverse = p_inverse;
  577. reset_pos = true;
  578. }
  579. virtual bool is_look_behind() { return true; }
  580. virtual int test(RegExSearch& s, int pos) const {
  581. if (pos < length)
  582. return -1;
  583. return RegExNodeGroup::test(s, pos - length);
  584. }
  585. };
  586. struct RegExNodeBracket : public RegExNode {
  587. bool inverse;
  588. Vector<RegExNode*> children;
  589. RegExNodeBracket() {
  590. length = 1;
  591. quantifiable = true;
  592. inverse = false;
  593. }
  594. virtual ~RegExNodeBracket() {
  595. for (int i = 0; i < children.size(); ++i)
  596. memdelete(children[i]);
  597. }
  598. virtual int test(RegExSearch& s, int pos) const {
  599. for (int i = 0; i < children.size(); ++i) {
  600. int res = children[i]->test(s, pos);
  601. if (inverse) {
  602. if (res < 0)
  603. res = pos + 1;
  604. else
  605. return -1;
  606. if (i + 1 < children.size())
  607. continue;
  608. }
  609. if (res >= 0)
  610. return next ? next->test(s, res) : res;
  611. }
  612. return -1;
  613. }
  614. void add_child(RegExNode* node) {
  615. node->parent = this;
  616. children.push_back(node);
  617. }
  618. void pop_back() {
  619. memdelete(children[children.size() - 1]);
  620. children.remove(children.size() - 1);
  621. }
  622. };
  623. #define REGEX_EXPAND_FAIL(MSG)\
  624. {\
  625. ERR_PRINT(MSG);\
  626. return String();\
  627. }
  628. String RegExMatch::expand(const String& p_template) const {
  629. String res;
  630. for (const CharType* c = p_template.c_str(); *c != '\0'; ++c) {
  631. if (c[0] == '\\') {
  632. if (('1' <= c[1] && c[1] <= '9') || (c[1] == 'g' && c[2] == '{')) {
  633. int ref = 0;
  634. bool unclosed = false;
  635. if (c[1] == 'g') {
  636. unclosed = true;
  637. c = &c[2];
  638. }
  639. while ('0' <= c[1] && c[1] <= '9') {
  640. ref = ref * 10 + int(c[1] - '0');
  641. ++c;
  642. }
  643. if (unclosed) {
  644. if (c[1] != '}')
  645. REGEX_EXPAND_FAIL("unclosed backreference '{'");
  646. ++c;
  647. }
  648. res += get_string(ref);
  649. } else if (c[1] =='g' && c[2] == '<') {
  650. const CharType* d = &c[2];
  651. Variant name = RegExNodeCapturing::parse_name(d, true);
  652. if (name == Variant(-1))
  653. REGEX_EXPAND_FAIL("unrecognised character for group name");
  654. c = d;
  655. res += get_string(name);
  656. } else {
  657. const CharType* d = c;
  658. CharType ch = RegExNodeChar::parse_escape(d);
  659. if (c == d)
  660. REGEX_EXPAND_FAIL("invalid escape token");
  661. res += String(&ch, 1);
  662. c = d;
  663. }
  664. } else {
  665. res += String(c, 1);
  666. }
  667. }
  668. return res;
  669. }
  670. int RegExMatch::get_group_count() const {
  671. int count = 0;
  672. for (int i = 1; i < captures.size(); ++i)
  673. if (captures[i].name.get_type() == Variant::INT)
  674. ++count;
  675. return count;
  676. }
  677. Array RegExMatch::get_group_array() const {
  678. Array res;
  679. for (int i = 1; i < captures.size(); ++i) {
  680. const RegExMatch::Group& capture = captures[i];
  681. if (capture.name.get_type() != Variant::INT)
  682. continue;
  683. if (capture.start >= 0)
  684. res.push_back(string.substr(capture.start, capture.length));
  685. else
  686. res.push_back(String());
  687. }
  688. return res;
  689. }
  690. Array RegExMatch::get_names() const {
  691. Array res;
  692. for (int i = 1; i < captures.size(); ++i)
  693. if (captures[i].name.get_type() == Variant::STRING)
  694. res.push_back(captures[i].name);
  695. return res;
  696. }
  697. Dictionary RegExMatch::get_name_dict() const {
  698. Dictionary res;
  699. for (int i = 1; i < captures.size(); ++i) {
  700. const RegExMatch::Group& capture = captures[i];
  701. if (capture.name.get_type() != Variant::STRING)
  702. continue;
  703. if (capture.start >= 0)
  704. res[capture.name] = string.substr(capture.start, capture.length);
  705. else
  706. res[capture.name] = String();
  707. }
  708. return res;
  709. }
  710. String RegExMatch::get_string(const Variant& p_name) const {
  711. for (int i = 0; i < captures.size(); ++i) {
  712. const RegExMatch::Group& capture = captures[i];
  713. if (capture.name != p_name)
  714. continue;
  715. if (capture.start == -1)
  716. return String();
  717. return string.substr(capture.start, capture.length);
  718. }
  719. return String();
  720. }
  721. int RegExMatch::get_start(const Variant& p_name) const {
  722. for (int i = 0; i < captures.size(); ++i)
  723. if (captures[i].name == p_name)
  724. return captures[i].start;
  725. return -1;
  726. }
  727. int RegExMatch::get_end(const Variant& p_name) const {
  728. for (int i = 0; i < captures.size(); ++i)
  729. if (captures[i].name == p_name)
  730. return captures[i].start + captures[i].length;
  731. return -1;
  732. }
  733. RegExMatch::RegExMatch() {
  734. }
  735. static bool RegEx_is_shorthand(CharType ch) {
  736. switch (ch) {
  737. case 'w':
  738. case 'W':
  739. case 'd':
  740. case 'D':
  741. case 's':
  742. case 'S':
  743. return true;
  744. default:
  745. break;
  746. }
  747. return false;
  748. }
  749. #define REGEX_COMPILE_FAIL(MSG)\
  750. {\
  751. ERR_PRINT(MSG);\
  752. clear();\
  753. return FAILED;\
  754. }
  755. Error RegEx::compile(const String& p_pattern) {
  756. ERR_FAIL_COND_V(p_pattern.length() == 0, FAILED);
  757. if (pattern == p_pattern && root)
  758. return OK;
  759. clear();
  760. pattern = p_pattern;
  761. group_names.push_back(0);
  762. RegExNodeGroup* root_group = memnew(RegExNodeCapturing(0));
  763. root = root_group;
  764. Vector<RegExNodeGroup*> stack;
  765. stack.push_back(root_group);
  766. int lookahead_level = 0;
  767. int numeric_groups = 0;
  768. const int numeric_max = 9;
  769. for (const CharType* c = p_pattern.c_str(); *c != '\0'; ++c) {
  770. switch (c[0]) {
  771. case '(':
  772. if (c[1] == '?') {
  773. RegExNodeGroup* group = NULL;
  774. switch (c[2]) {
  775. case ':':
  776. c = &c[2];
  777. group = memnew(RegExNodeGroup());
  778. break;
  779. case '!':
  780. case '=':
  781. group = memnew(RegExNodeLookAhead((c[2] == '!'), lookahead_level++));
  782. if (lookahead_depth < lookahead_level)
  783. lookahead_depth = lookahead_level;
  784. c = &c[2];
  785. break;
  786. case '<':
  787. if (c[3] == '!' || c[3] == '=') {
  788. group = memnew(RegExNodeLookBehind((c[3] == '!'), lookahead_level++));
  789. c = &c[3];
  790. }
  791. break;
  792. case 'P':
  793. if (c[3] == '<') {
  794. const CharType* d = &c[3];
  795. Variant name = RegExNodeCapturing::parse_name(d, false);
  796. if (name == Variant(-1))
  797. REGEX_COMPILE_FAIL("unrecognised character for group name");
  798. group = memnew(RegExNodeCapturing(group_names.size()));
  799. group_names.push_back(name);
  800. c = d;
  801. }
  802. default:
  803. break;
  804. }
  805. if (!group)
  806. REGEX_COMPILE_FAIL("unrecognised qualifier for group");
  807. stack[0]->add_child(group);
  808. stack.insert(0, group);
  809. } else if (numeric_groups < numeric_max) {
  810. RegExNodeCapturing* group = memnew(RegExNodeCapturing(group_names.size()));
  811. group_names.push_back(++numeric_groups);
  812. stack[0]->add_child(group);
  813. stack.insert(0, group);
  814. } else {
  815. RegExNodeGroup* group = memnew(RegExNodeGroup());
  816. stack[0]->add_child(group);
  817. stack.insert(0, group);
  818. }
  819. break;
  820. case ')':
  821. if (stack.size() == 1)
  822. REGEX_COMPILE_FAIL("unexpected ')'");
  823. stack.remove(0);
  824. break;
  825. case '\\':
  826. if (('1' <= c[1] && c[1] <= '9') || (c[1] == 'g' && c[2] == '{')) {
  827. int ref = 0;
  828. bool unclosed = false;
  829. if (c[1] == 'g') {
  830. unclosed = true;
  831. c = &c[2];
  832. }
  833. while ('0' <= c[1] && c[1] <= '9') {
  834. ref = ref * 10 + int(c[1] - '0');
  835. ++c;
  836. }
  837. if (unclosed) {
  838. if (c[1] != '}')
  839. REGEX_COMPILE_FAIL("unclosed backreference '{'");
  840. ++c;
  841. }
  842. if (ref > numeric_groups || ref <= 0)
  843. REGEX_COMPILE_FAIL("backreference not found");
  844. for (int i = 0; i < stack.size(); ++i)
  845. if (stack[i]->is_look_behind())
  846. REGEX_COMPILE_FAIL("backreferences inside lookbehind not supported");
  847. for (int i = 0; i < group_names.size(); ++i) {
  848. if (group_names[i].get_type() == Variant::INT && int(group_names[i]) == ref) {
  849. ref = group_names[i];
  850. break;
  851. }
  852. }
  853. stack[0]->add_child(memnew(RegExNodeBackReference(ref)));
  854. } if (c[1] =='g' && c[2] == '<') {
  855. const CharType* d = &c[2];
  856. Variant name = RegExNodeCapturing::parse_name(d, true);
  857. if (name == Variant(-1))
  858. REGEX_COMPILE_FAIL("unrecognised character for group name");
  859. c = d;
  860. for (int i = 0; i < stack.size(); ++i)
  861. if (stack[i]->is_look_behind())
  862. REGEX_COMPILE_FAIL("backreferences inside lookbehind not supported");
  863. int ref = -1;
  864. for (int i = 0; i < group_names.size(); ++i) {
  865. if (group_names[i].get_type() == Variant::INT && int(group_names[i]) == ref) {
  866. ref = group_names[i];
  867. break;
  868. }
  869. }
  870. if (ref == -1)
  871. REGEX_COMPILE_FAIL("backreference not found");
  872. stack[0]->add_child(memnew(RegExNodeBackReference(ref)));
  873. } else if (c[1] == 'b' || c[1] == 'B') {
  874. stack[0]->add_child(memnew(RegExNodeWordBoundary(*(++c) == 'B')));
  875. } else if (RegEx_is_shorthand(c[1])) {
  876. stack[0]->add_child(memnew(RegExNodeShorthand(*(++c))));
  877. } else {
  878. const CharType* d = c;
  879. CharType ch = RegExNodeChar::parse_escape(d);
  880. if (c == d)
  881. REGEX_COMPILE_FAIL("invalid escape token");
  882. stack[0]->add_child(memnew(RegExNodeChar(ch)));
  883. c = d;
  884. }
  885. break;
  886. case '[':
  887. {
  888. RegExNodeBracket* bracket = memnew(RegExNodeBracket());
  889. stack[0]->add_child(bracket);
  890. if (c[1] == '^') {
  891. bracket->inverse = true;
  892. ++c;
  893. }
  894. bool first_child = true;
  895. CharType previous_child;
  896. bool previous_child_single = false;
  897. while (true) {
  898. ++c;
  899. if (!first_child && c[0] == ']') {
  900. break;
  901. } else if (c[0] == '\0') {
  902. REGEX_COMPILE_FAIL("unclosed bracket expression '['");
  903. } else if (c[0] == '\\') {
  904. if (RegEx_is_shorthand(c[1])) {
  905. bracket->add_child(memnew(RegExNodeShorthand(*(++c))));
  906. } else {
  907. const CharType* d = c;
  908. CharType ch = RegExNodeChar::parse_escape(d);
  909. if (c == d)
  910. REGEX_COMPILE_FAIL("invalid escape token");
  911. bracket->add_child(memnew(RegExNodeChar(ch)));
  912. c = d;
  913. previous_child = ch;
  914. previous_child_single = true;
  915. }
  916. } else if (c[0] == ']' && c[1] == ':') {
  917. const CharType* d = &c[2];
  918. RegExNodeClass::Type type = RegExNodeClass::parse_type(d);
  919. if (type != RegExNodeClass::Type_none) {
  920. c = d;
  921. previous_child_single = false;
  922. } else {
  923. bracket->add_child(memnew(RegExNodeChar('[')));
  924. previous_child = '[';
  925. previous_child_single = true;
  926. }
  927. } else if (previous_child_single && c[0] == '-') {
  928. if (c[1] != '\0' && c[1] != ']') {
  929. CharType next;
  930. if (c[1] == '\\') {
  931. const CharType* d = ++c;
  932. next = RegExNodeChar::parse_escape(d);
  933. if (c == d)
  934. REGEX_COMPILE_FAIL("invalid escape token");
  935. } else {
  936. next = *(++c);
  937. }
  938. if (next < previous_child)
  939. REGEX_COMPILE_FAIL("text range out of order");
  940. bracket->pop_back();
  941. bracket->add_child(memnew(RegExNodeRange(previous_child, next)));
  942. previous_child_single = false;
  943. } else {
  944. bracket->add_child(memnew(RegExNodeChar('-')));
  945. previous_child = '-';
  946. previous_child_single = true;
  947. }
  948. } else {
  949. bracket->add_child(memnew(RegExNodeChar(c[0])));
  950. previous_child = c[0];
  951. previous_child_single = true;
  952. }
  953. first_child = false;
  954. }
  955. }
  956. break;
  957. case '|':
  958. for (int i = 0; i < stack.size(); ++i)
  959. if (stack[i]->is_look_behind())
  960. REGEX_COMPILE_FAIL("alternations inside lookbehind not supported");
  961. stack[0]->add_childset();
  962. break;
  963. case '^':
  964. stack[0]->add_child(memnew(RegExNodeAnchorStart()));
  965. break;
  966. case '$':
  967. stack[0]->add_child(memnew(RegExNodeAnchorEnd()));
  968. break;
  969. case '.':
  970. stack[0]->add_child(memnew(RegExNodeShorthand('.')));
  971. break;
  972. case '?':
  973. case '*':
  974. case '+':
  975. case '{':
  976. {
  977. int min_val = 0;
  978. int max_val = -1;
  979. bool valid = true;
  980. const CharType* d = c;
  981. bool max_set = true;
  982. switch (c[0]) {
  983. case '?':
  984. min_val = 0;
  985. max_val = 1;
  986. break;
  987. case '*':
  988. min_val = 0;
  989. max_val = -1;
  990. break;
  991. case '+':
  992. min_val = 1;
  993. max_val = -1;
  994. break;
  995. case '{':
  996. max_set = false;
  997. while (valid) {
  998. ++d;
  999. if (d[0] == '}') {
  1000. break;
  1001. } else if (d[0] == ',') {
  1002. max_set = true;
  1003. } else if ('0' <= d[0] && d[0] <= '9') {
  1004. if (max_set) {
  1005. if (max_val < 0)
  1006. max_val = int(d[0] - '0');
  1007. else
  1008. max_val = max_val * 10 + int(d[0] - '0');
  1009. } else {
  1010. min_val = min_val * 10 + int(d[0] - '0');
  1011. }
  1012. } else {
  1013. valid = false;
  1014. }
  1015. }
  1016. break;
  1017. default:
  1018. break;
  1019. }
  1020. if (!max_set)
  1021. max_val = min_val;
  1022. if (valid) {
  1023. c = d;
  1024. if (stack[0]->back == NULL || !stack[0]->back->quantifiable)
  1025. REGEX_COMPILE_FAIL("element not quantifiable");
  1026. if (min_val != max_val)
  1027. for (int i = 0; i < stack.size(); ++i)
  1028. if (stack[i]->is_look_behind())
  1029. REGEX_COMPILE_FAIL("variable length quantifiers inside lookbehind not supported");
  1030. RegExNodeQuantifier* quant = memnew(RegExNodeQuantifier(min_val, max_val));
  1031. quant->child = stack[0]->swap_back(quant);
  1032. quant->child->previous = NULL;
  1033. quant->child->parent = quant;
  1034. if (min_val == max_val && quant->child->length >= 0)
  1035. quant->length = max_val * quant->child->length;
  1036. if (c[1] == '?') {
  1037. quant->greedy = false;
  1038. ++c;
  1039. }
  1040. break;
  1041. }
  1042. }
  1043. default:
  1044. stack[0]->add_child(memnew(RegExNodeChar(c[0])));
  1045. break;
  1046. }
  1047. }
  1048. if (stack.size() > 1)
  1049. REGEX_COMPILE_FAIL("unclosed group '('");
  1050. return OK;
  1051. }
  1052. Ref<RegExMatch> RegEx::search(const String& p_text, int p_start, int p_end) const {
  1053. ERR_FAIL_COND_V(!is_valid(), NULL);
  1054. ERR_FAIL_COND_V(p_start < 0, NULL);
  1055. ERR_FAIL_COND_V(p_start >= p_text.length(), NULL);
  1056. ERR_FAIL_COND_V(p_end > p_text.length(), NULL);
  1057. ERR_FAIL_COND_V(p_end != -1 && p_end < p_start, NULL);
  1058. Ref<RegExMatch> res = memnew(RegExMatch());
  1059. for (int i = 0; i < group_names.size(); ++i) {
  1060. RegExMatch::Group group;
  1061. group.name = group_names[i];
  1062. res->captures.push_back(group);
  1063. }
  1064. res->string = p_text;
  1065. if (p_end == -1)
  1066. p_end = p_text.length();
  1067. RegExSearch s(res, p_end, lookahead_depth);
  1068. for (int i = p_start; i <= s.end; ++i) {
  1069. for (int c = 0; c < group_names.size(); ++c) {
  1070. res->captures[c].start = -1;
  1071. res->captures[c].length = 0;
  1072. }
  1073. if (root->test(s, i) >= 0)
  1074. break;
  1075. }
  1076. if (res->captures[0].start >= 0)
  1077. return res;
  1078. return NULL;
  1079. }
  1080. String RegEx::sub(const String& p_text, const String& p_replacement, bool p_all, int p_start, int p_end) const {
  1081. ERR_FAIL_COND_V(!is_valid(), p_text);
  1082. ERR_FAIL_COND_V(p_start < 0, p_text);
  1083. ERR_FAIL_COND_V(p_start >= p_text.length(), p_text);
  1084. ERR_FAIL_COND_V(p_end > p_text.length(), p_text);
  1085. ERR_FAIL_COND_V(p_end != -1 && p_end < p_start, p_text);
  1086. String text = p_text;
  1087. int start = p_start;
  1088. if (p_end == -1)
  1089. p_end = p_text.length();
  1090. while (start < text.length() && (p_all || start == p_start)) {
  1091. Ref<RegExMatch> m = search(text, start, p_end);
  1092. RegExMatch::Group& s = m->captures[0];
  1093. if (s.start < 0)
  1094. break;
  1095. String res = text.substr(0, s.start) + m->expand(p_replacement);
  1096. start = res.length();
  1097. if (s.length == 0)
  1098. ++start;
  1099. int sub_end = s.start + s.length;
  1100. if (sub_end < text.length())
  1101. res += text.substr(sub_end, text.length() - sub_end);
  1102. p_end += res.length() - text.length();
  1103. text = res;
  1104. }
  1105. return text;
  1106. }
  1107. void RegEx::clear() {
  1108. if (root)
  1109. memdelete(root);
  1110. root = NULL;
  1111. group_names.clear();
  1112. lookahead_depth = 0;
  1113. }
  1114. bool RegEx::is_valid() const {
  1115. return (root != NULL);
  1116. }
  1117. String RegEx::get_pattern() const {
  1118. return pattern;
  1119. }
  1120. int RegEx::get_group_count() const {
  1121. int count = 0;
  1122. for (int i = 1; i < group_names.size(); ++i)
  1123. if (group_names[i].get_type() == Variant::INT)
  1124. ++count;
  1125. return count;
  1126. }
  1127. Array RegEx::get_names() const {
  1128. Array res;
  1129. for (int i = 1; i < group_names.size(); ++i)
  1130. if (group_names[i].get_type() == Variant::STRING)
  1131. res.push_back(group_names[i]);
  1132. return res;
  1133. }
  1134. RegEx::RegEx() {
  1135. root = NULL;
  1136. lookahead_depth = 0;
  1137. }
  1138. RegEx::RegEx(const String& p_pattern) {
  1139. root = NULL;
  1140. compile(p_pattern);
  1141. }
  1142. RegEx::~RegEx() {
  1143. if (root)
  1144. memdelete(root);
  1145. }
  1146. void RegExMatch::_bind_methods() {
  1147. ObjectTypeDB::bind_method(_MD("expand","template"),&RegExMatch::expand);
  1148. ObjectTypeDB::bind_method(_MD("get_group_count"),&RegExMatch::get_group_count);
  1149. ObjectTypeDB::bind_method(_MD("get_group_array"),&RegExMatch::get_group_array);
  1150. ObjectTypeDB::bind_method(_MD("get_names"),&RegExMatch::get_names);
  1151. ObjectTypeDB::bind_method(_MD("get_name_dict"),&RegExMatch::get_name_dict);
  1152. ObjectTypeDB::bind_method(_MD("get_string","name"),&RegExMatch::get_string, DEFVAL(0));
  1153. ObjectTypeDB::bind_method(_MD("get_start","name"),&RegExMatch::get_start, DEFVAL(0));
  1154. ObjectTypeDB::bind_method(_MD("get_end","name"),&RegExMatch::get_end, DEFVAL(0));
  1155. }
  1156. void RegEx::_bind_methods() {
  1157. ObjectTypeDB::bind_method(_MD("clear"),&RegEx::clear);
  1158. ObjectTypeDB::bind_method(_MD("compile","pattern"),&RegEx::compile);
  1159. ObjectTypeDB::bind_method(_MD("search","text","start","end"),&RegEx::search, DEFVAL(0), DEFVAL(-1));
  1160. ObjectTypeDB::bind_method(_MD("sub","text","replacement","all","start","end"),&RegEx::sub, DEFVAL(false), DEFVAL(0), DEFVAL(-1));
  1161. ObjectTypeDB::bind_method(_MD("is_valid"),&RegEx::is_valid);
  1162. ObjectTypeDB::bind_method(_MD("get_pattern"),&RegEx::get_pattern);
  1163. ObjectTypeDB::bind_method(_MD("get_group_count"),&RegEx::get_group_count);
  1164. ObjectTypeDB::bind_method(_MD("get_names"),&RegEx::get_names);
  1165. ADD_PROPERTY(PropertyInfo(Variant::STRING, "pattern"), _SCS("compile"), _SCS("get_pattern"));
  1166. }