regex.cpp 32 KB

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