regex.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502
  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. ERR_FAIL_COND_V(p_pattern.length() == 0, FAILED);
  754. if (pattern == p_pattern && root)
  755. return OK;
  756. clear();
  757. pattern = p_pattern;
  758. group_names.push_back(0);
  759. RegExNodeGroup* root_group = memnew(RegExNodeCapturing(0));
  760. root = root_group;
  761. Vector<RegExNodeGroup*> stack;
  762. stack.push_back(root_group);
  763. int lookahead_level = 0;
  764. int numeric_groups = 0;
  765. const int numeric_max = 9;
  766. for (const CharType* c = p_pattern.c_str(); *c != '\0'; ++c) {
  767. switch (c[0]) {
  768. case '(':
  769. if (c[1] == '?') {
  770. RegExNodeGroup* group = NULL;
  771. switch (c[2]) {
  772. case ':':
  773. c = &c[2];
  774. group = memnew(RegExNodeGroup());
  775. break;
  776. case '!':
  777. case '=':
  778. group = memnew(RegExNodeLookAhead((c[2] == '!'), lookahead_level++));
  779. if (lookahead_depth < lookahead_level)
  780. lookahead_depth = lookahead_level;
  781. c = &c[2];
  782. break;
  783. case '<':
  784. if (c[3] == '!' || c[3] == '=') {
  785. group = memnew(RegExNodeLookBehind((c[3] == '!'), lookahead_level++));
  786. c = &c[3];
  787. }
  788. break;
  789. case 'P':
  790. if (c[3] == '<') {
  791. const CharType* d = &c[3];
  792. Variant name = RegExNodeCapturing::parse_name(d, false);
  793. if (name == Variant(-1))
  794. REGEX_COMPILE_FAIL("unrecognised character for group name");
  795. group = memnew(RegExNodeCapturing(group_names.size()));
  796. group_names.push_back(name);
  797. c = d;
  798. }
  799. default:
  800. break;
  801. }
  802. if (!group)
  803. REGEX_COMPILE_FAIL("unrecognised qualifier for group");
  804. stack[0]->add_child(group);
  805. stack.insert(0, group);
  806. } else if (numeric_groups < numeric_max) {
  807. RegExNodeCapturing* group = memnew(RegExNodeCapturing(group_names.size()));
  808. group_names.push_back(++numeric_groups);
  809. stack[0]->add_child(group);
  810. stack.insert(0, group);
  811. } else {
  812. RegExNodeGroup* group = memnew(RegExNodeGroup());
  813. stack[0]->add_child(group);
  814. stack.insert(0, group);
  815. }
  816. break;
  817. case ')':
  818. if (stack.size() == 1)
  819. REGEX_COMPILE_FAIL("unexpected ')'");
  820. stack.remove(0);
  821. break;
  822. case '\\':
  823. if (('1' <= c[1] && c[1] <= '9') || (c[1] == 'g' && c[2] == '{')) {
  824. int ref = 0;
  825. bool unclosed = false;
  826. if (c[1] == 'g') {
  827. unclosed = true;
  828. c = &c[2];
  829. }
  830. while ('0' <= c[1] && c[1] <= '9') {
  831. ref = ref * 10 + int(c[1] - '0');
  832. ++c;
  833. }
  834. if (unclosed) {
  835. if (c[1] != '}')
  836. REGEX_COMPILE_FAIL("unclosed backreference '{'");
  837. ++c;
  838. }
  839. if (ref > numeric_groups || ref <= 0)
  840. REGEX_COMPILE_FAIL("backreference not found");
  841. for (int i = 0; i < stack.size(); ++i)
  842. if (dynamic_cast<RegExNodeLookBehind*>(stack[i]))
  843. REGEX_COMPILE_FAIL("backreferences inside lookbehind not supported");
  844. for (int i = 0; i < group_names.size(); ++i) {
  845. if (group_names[i].get_type() == Variant::INT && int(group_names[i]) == ref) {
  846. ref = group_names[i];
  847. break;
  848. }
  849. }
  850. stack[0]->add_child(memnew(RegExNodeBackReference(ref)));
  851. } if (c[1] =='g' && c[2] == '<') {
  852. const CharType* d = &c[2];
  853. Variant name = RegExNodeCapturing::parse_name(d, true);
  854. if (name == Variant(-1))
  855. REGEX_COMPILE_FAIL("unrecognised character for group name");
  856. c = d;
  857. for (int i = 0; i < stack.size(); ++i)
  858. if (dynamic_cast<RegExNodeLookBehind*>(stack[i]))
  859. REGEX_COMPILE_FAIL("backreferences inside lookbehind not supported");
  860. int ref = -1;
  861. for (int i = 0; i < group_names.size(); ++i) {
  862. if (group_names[i].get_type() == Variant::INT && int(group_names[i]) == ref) {
  863. ref = group_names[i];
  864. break;
  865. }
  866. }
  867. if (ref == -1)
  868. REGEX_COMPILE_FAIL("backreference not found");
  869. stack[0]->add_child(memnew(RegExNodeBackReference(ref)));
  870. } else if (c[1] == 'b' || c[1] == 'B') {
  871. stack[0]->add_child(memnew(RegExNodeWordBoundary(*(++c) == 'B')));
  872. } else if (RegEx_is_shorthand(c[1])) {
  873. stack[0]->add_child(memnew(RegExNodeShorthand(*(++c))));
  874. } else {
  875. const CharType* d = c;
  876. CharType ch = RegExNodeChar::parse_escape(d);
  877. if (c == d)
  878. REGEX_COMPILE_FAIL("invalid escape token");
  879. stack[0]->add_child(memnew(RegExNodeChar(ch)));
  880. c = d;
  881. }
  882. break;
  883. case '[':
  884. {
  885. RegExNodeBracket* bracket = memnew(RegExNodeBracket());
  886. stack[0]->add_child(bracket);
  887. if (c[1] == '^') {
  888. bracket->inverse = true;
  889. ++c;
  890. }
  891. bool first_child = true;
  892. CharType previous_child;
  893. bool previous_child_single = false;
  894. while (true) {
  895. ++c;
  896. if (!first_child && c[0] == ']') {
  897. break;
  898. } else if (c[0] == '\0') {
  899. REGEX_COMPILE_FAIL("unclosed bracket expression '['");
  900. } else if (c[0] == '\\') {
  901. if (RegEx_is_shorthand(c[1])) {
  902. bracket->add_child(memnew(RegExNodeShorthand(*(++c))));
  903. } else {
  904. const CharType* d = c;
  905. CharType ch = RegExNodeChar::parse_escape(d);
  906. if (c == d)
  907. REGEX_COMPILE_FAIL("invalid escape token");
  908. bracket->add_child(memnew(RegExNodeChar(ch)));
  909. c = d;
  910. previous_child = ch;
  911. previous_child_single = true;
  912. }
  913. } else if (c[0] == ']' && c[1] == ':') {
  914. const CharType* d = &c[2];
  915. RegExNodeClass::Type type = RegExNodeClass::parse_type(d);
  916. if (type != RegExNodeClass::Type_none) {
  917. c = d;
  918. previous_child_single = false;
  919. } else {
  920. bracket->add_child(memnew(RegExNodeChar('[')));
  921. previous_child = '[';
  922. previous_child_single = true;
  923. }
  924. } else if (previous_child_single && c[0] == '-') {
  925. if (c[1] != '\0' && c[1] != ']') {
  926. CharType next;
  927. if (c[1] == '\\') {
  928. const CharType* d = ++c;
  929. next = RegExNodeChar::parse_escape(d);
  930. if (c == d)
  931. REGEX_COMPILE_FAIL("invalid escape token");
  932. } else {
  933. next = *(++c);
  934. }
  935. if (next < previous_child)
  936. REGEX_COMPILE_FAIL("text range out of order");
  937. bracket->pop_back();
  938. bracket->add_child(memnew(RegExNodeRange(previous_child, next)));
  939. previous_child_single = false;
  940. } else {
  941. bracket->add_child(memnew(RegExNodeChar('-')));
  942. previous_child = '-';
  943. previous_child_single = true;
  944. }
  945. } else {
  946. bracket->add_child(memnew(RegExNodeChar(c[0])));
  947. previous_child = c[0];
  948. previous_child_single = true;
  949. }
  950. first_child = false;
  951. }
  952. }
  953. break;
  954. case '|':
  955. for (int i = 0; i < stack.size(); ++i)
  956. if (dynamic_cast<RegExNodeLookBehind*>(stack[i]))
  957. REGEX_COMPILE_FAIL("alternations inside lookbehind not supported");
  958. stack[0]->add_childset();
  959. break;
  960. case '^':
  961. stack[0]->add_child(memnew(RegExNodeAnchorStart()));
  962. break;
  963. case '$':
  964. stack[0]->add_child(memnew(RegExNodeAnchorEnd()));
  965. break;
  966. case '.':
  967. stack[0]->add_child(memnew(RegExNodeShorthand('.')));
  968. break;
  969. case '?':
  970. case '*':
  971. case '+':
  972. case '{':
  973. {
  974. int min_val = 0;
  975. int max_val = -1;
  976. bool valid = true;
  977. const CharType* d = c;
  978. bool max_set = true;
  979. switch (c[0]) {
  980. case '?':
  981. min_val = 0;
  982. max_val = 1;
  983. break;
  984. case '*':
  985. min_val = 0;
  986. max_val = -1;
  987. break;
  988. case '+':
  989. min_val = 1;
  990. max_val = -1;
  991. break;
  992. case '{':
  993. max_set = false;
  994. while (valid) {
  995. ++d;
  996. if (d[0] == '}') {
  997. break;
  998. } else if (d[0] == ',') {
  999. max_set = true;
  1000. } else if ('0' <= d[0] && d[0] <= '9') {
  1001. if (max_set) {
  1002. if (max_val < 0)
  1003. max_val = int(d[0] - '0');
  1004. else
  1005. max_val = max_val * 10 + int(d[0] - '0');
  1006. } else {
  1007. min_val = min_val * 10 + int(d[0] - '0');
  1008. }
  1009. } else {
  1010. valid = false;
  1011. }
  1012. }
  1013. break;
  1014. default:
  1015. break;
  1016. }
  1017. if (!max_set)
  1018. max_val = min_val;
  1019. if (valid) {
  1020. c = d;
  1021. if (stack[0]->back == NULL || !stack[0]->back->quantifiable)
  1022. REGEX_COMPILE_FAIL("element not quantifiable");
  1023. if (min_val != max_val)
  1024. for (int i = 0; i < stack.size(); ++i)
  1025. if (dynamic_cast<RegExNodeLookBehind*>(stack[i]))
  1026. REGEX_COMPILE_FAIL("variable length quantifiers inside lookbehind not supported");
  1027. RegExNodeQuantifier* quant = memnew(RegExNodeQuantifier(min_val, max_val));
  1028. quant->child = stack[0]->swap_back(quant);
  1029. quant->child->previous = NULL;
  1030. quant->child->parent = quant;
  1031. if (min_val == max_val && quant->child->length >= 0)
  1032. quant->length = max_val * quant->child->length;
  1033. if (c[1] == '?') {
  1034. quant->greedy = false;
  1035. ++c;
  1036. }
  1037. break;
  1038. }
  1039. }
  1040. default:
  1041. stack[0]->add_child(memnew(RegExNodeChar(c[0])));
  1042. break;
  1043. }
  1044. }
  1045. if (stack.size() > 1)
  1046. REGEX_COMPILE_FAIL("unclosed group '('");
  1047. return OK;
  1048. }
  1049. Ref<RegExMatch> RegEx::search(const String& p_text, int p_start, int p_end) const {
  1050. ERR_FAIL_COND_V(!is_valid(), NULL);
  1051. ERR_FAIL_COND_V(p_start < 0, NULL);
  1052. ERR_FAIL_COND_V(p_start >= p_text.length(), NULL);
  1053. ERR_FAIL_COND_V(p_end > p_text.length(), NULL);
  1054. ERR_FAIL_COND_V(p_end != -1 && p_end < p_start, NULL);
  1055. Ref<RegExMatch> res = memnew(RegExMatch());
  1056. for (int i = 0; i < group_names.size(); ++i) {
  1057. RegExMatch::Group group;
  1058. group.name = group_names[i];
  1059. res->captures.push_back(group);
  1060. }
  1061. res->string = p_text;
  1062. if (p_end == -1)
  1063. p_end = p_text.length();
  1064. RegExSearch s(res, p_end, lookahead_depth);
  1065. for (int i = p_start; i <= s.end; ++i) {
  1066. for (int c = 0; c < group_names.size(); ++c) {
  1067. res->captures[c].start = -1;
  1068. res->captures[c].length = 0;
  1069. }
  1070. if (root->test(s, i) >= 0)
  1071. break;
  1072. }
  1073. if (res->captures[0].start >= 0)
  1074. return res;
  1075. return NULL;
  1076. }
  1077. String RegEx::sub(const String& p_text, const String& p_replacement, bool p_all, int p_start, int p_end) const {
  1078. ERR_FAIL_COND_V(!is_valid(), p_text);
  1079. ERR_FAIL_COND_V(p_start < 0, p_text);
  1080. ERR_FAIL_COND_V(p_start >= p_text.length(), p_text);
  1081. ERR_FAIL_COND_V(p_end > p_text.length(), p_text);
  1082. ERR_FAIL_COND_V(p_end != -1 && p_end < p_start, p_text);
  1083. String text = p_text;
  1084. int start = p_start;
  1085. if (p_end == -1)
  1086. p_end = p_text.length();
  1087. while (start < text.length() && (p_all || start == p_start)) {
  1088. Ref<RegExMatch> m = search(text, start, p_end);
  1089. RegExMatch::Group& s = m->captures[0];
  1090. if (s.start < 0)
  1091. break;
  1092. String res = text.substr(0, s.start) + m->expand(p_replacement);
  1093. start = res.length();
  1094. if (s.length == 0)
  1095. ++start;
  1096. int sub_end = s.start + s.length;
  1097. if (sub_end < text.length())
  1098. res += text.substr(sub_end, text.length() - sub_end);
  1099. p_end += res.length() - text.length();
  1100. text = res;
  1101. }
  1102. return text;
  1103. }
  1104. void RegEx::clear() {
  1105. if (root)
  1106. memdelete(root);
  1107. root = NULL;
  1108. group_names.clear();
  1109. lookahead_depth = 0;
  1110. }
  1111. bool RegEx::is_valid() const {
  1112. return (root != NULL);
  1113. }
  1114. String RegEx::get_pattern() const {
  1115. return pattern;
  1116. }
  1117. int RegEx::get_group_count() const {
  1118. int count = 0;
  1119. for (int i = 1; i < group_names.size(); ++i)
  1120. if (group_names[i].get_type() == Variant::INT)
  1121. ++count;
  1122. return count;
  1123. }
  1124. Array RegEx::get_names() const {
  1125. Array res;
  1126. for (int i = 1; i < group_names.size(); ++i)
  1127. if (group_names[i].get_type() == Variant::STRING)
  1128. res.push_back(group_names[i]);
  1129. return res;
  1130. }
  1131. RegEx::RegEx() {
  1132. root = NULL;
  1133. lookahead_depth = 0;
  1134. }
  1135. RegEx::RegEx(const String& p_pattern) {
  1136. root = NULL;
  1137. compile(p_pattern);
  1138. }
  1139. RegEx::~RegEx() {
  1140. if (root)
  1141. memdelete(root);
  1142. }
  1143. void RegExMatch::_bind_methods() {
  1144. ObjectTypeDB::bind_method(_MD("expand","template"),&RegExMatch::expand);
  1145. ObjectTypeDB::bind_method(_MD("get_group_count"),&RegExMatch::get_group_count);
  1146. ObjectTypeDB::bind_method(_MD("get_group_array"),&RegExMatch::get_group_array);
  1147. ObjectTypeDB::bind_method(_MD("get_names"),&RegExMatch::get_names);
  1148. ObjectTypeDB::bind_method(_MD("get_name_dict"),&RegExMatch::get_name_dict);
  1149. ObjectTypeDB::bind_method(_MD("get_string","name"),&RegExMatch::get_string, DEFVAL(0));
  1150. ObjectTypeDB::bind_method(_MD("get_start","name"),&RegExMatch::get_start, DEFVAL(0));
  1151. ObjectTypeDB::bind_method(_MD("get_end","name"),&RegExMatch::get_end, DEFVAL(0));
  1152. }
  1153. void RegEx::_bind_methods() {
  1154. ObjectTypeDB::bind_method(_MD("clear"),&RegEx::clear);
  1155. ObjectTypeDB::bind_method(_MD("compile","pattern"),&RegEx::compile);
  1156. ObjectTypeDB::bind_method(_MD("search","text","start","end"),&RegEx::search, DEFVAL(0), DEFVAL(-1));
  1157. ObjectTypeDB::bind_method(_MD("sub","text","replacement","all","start","end"),&RegEx::sub, DEFVAL(false), DEFVAL(0), DEFVAL(-1));
  1158. ObjectTypeDB::bind_method(_MD("is_valid"),&RegEx::is_valid);
  1159. ObjectTypeDB::bind_method(_MD("get_pattern"),&RegEx::get_pattern);
  1160. ObjectTypeDB::bind_method(_MD("get_group_count"),&RegEx::get_group_count);
  1161. ObjectTypeDB::bind_method(_MD("get_names"),&RegEx::get_names);
  1162. ADD_PROPERTY(PropertyInfo(Variant::STRING, "pattern"), _SCS("compile"), _SCS("get_pattern"));
  1163. }