Regex.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. /*
  2. * Copyright (c) 2020, Emanuel Sprung <emanuel.sprung@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "LibRegex/RegexMatcher.h"
  7. #include <LibTest/TestCase.h> // import first, to prevent warning of VERIFY* redefinition
  8. #include <AK/StringBuilder.h>
  9. #include <AK/Tuple.h>
  10. #include <LibRegex/Regex.h>
  11. #include <LibRegex/RegexDebug.h>
  12. #include <stdio.h>
  13. static ECMAScriptOptions match_test_api_options(const ECMAScriptOptions options)
  14. {
  15. return options;
  16. }
  17. static PosixOptions match_test_api_options(const PosixOptions options)
  18. {
  19. return options;
  20. }
  21. template<typename... Flags>
  22. static constexpr ECMAScriptFlags combine_flags(Flags&&... flags) requires((IsSame<Flags, ECMAScriptFlags> && ...))
  23. {
  24. return static_cast<ECMAScriptFlags>((static_cast<regex::FlagsUnderlyingType>(flags) | ...));
  25. }
  26. TEST_CASE(regex_options_ecmascript)
  27. {
  28. ECMAScriptOptions eo;
  29. eo |= ECMAScriptFlags::Global;
  30. EXPECT(eo & ECMAScriptFlags::Global);
  31. EXPECT(!(eo & ECMAScriptFlags::Insensitive));
  32. eo = match_test_api_options(ECMAScriptFlags::Global | ECMAScriptFlags::Insensitive | ECMAScriptFlags::Sticky);
  33. EXPECT(eo & ECMAScriptFlags::Global);
  34. EXPECT(eo & ECMAScriptFlags::Insensitive);
  35. EXPECT(eo & ECMAScriptFlags::Sticky);
  36. EXPECT(!(eo & ECMAScriptFlags::Unicode));
  37. EXPECT(!(eo & ECMAScriptFlags::Multiline));
  38. EXPECT(!(eo & ECMAScriptFlags::SingleLine));
  39. eo &= ECMAScriptFlags::Insensitive;
  40. EXPECT(!(eo & ECMAScriptFlags::Global));
  41. EXPECT(eo & ECMAScriptFlags::Insensitive);
  42. EXPECT(!(eo & ECMAScriptFlags::Multiline));
  43. eo &= ECMAScriptFlags::Sticky;
  44. EXPECT(!(eo & ECMAScriptFlags::Global));
  45. EXPECT(!(eo & ECMAScriptFlags::Insensitive));
  46. EXPECT(!(eo & ECMAScriptFlags::Multiline));
  47. EXPECT(!(eo & ECMAScriptFlags::Sticky));
  48. eo = ~ECMAScriptFlags::Insensitive;
  49. EXPECT(eo & ECMAScriptFlags::Global);
  50. EXPECT(!(eo & ECMAScriptFlags::Insensitive));
  51. EXPECT(eo & ECMAScriptFlags::Multiline);
  52. EXPECT(eo & ECMAScriptFlags::Sticky);
  53. }
  54. TEST_CASE(regex_options_posix)
  55. {
  56. PosixOptions eo;
  57. eo |= PosixFlags::Global;
  58. EXPECT(eo & PosixFlags::Global);
  59. EXPECT(!(eo & PosixFlags::Insensitive));
  60. eo = match_test_api_options(PosixFlags::Global | PosixFlags::Insensitive | PosixFlags::MatchNotBeginOfLine);
  61. EXPECT(eo & PosixFlags::Global);
  62. EXPECT(eo & PosixFlags::Insensitive);
  63. EXPECT(eo & PosixFlags::MatchNotBeginOfLine);
  64. EXPECT(!(eo & PosixFlags::Unicode));
  65. EXPECT(!(eo & PosixFlags::Multiline));
  66. eo &= PosixFlags::Insensitive;
  67. EXPECT(!(eo & PosixFlags::Global));
  68. EXPECT(eo & PosixFlags::Insensitive);
  69. EXPECT(!(eo & PosixFlags::Multiline));
  70. eo &= PosixFlags::MatchNotBeginOfLine;
  71. EXPECT(!(eo & PosixFlags::Global));
  72. EXPECT(!(eo & PosixFlags::Insensitive));
  73. EXPECT(!(eo & PosixFlags::Multiline));
  74. eo = ~PosixFlags::Insensitive;
  75. EXPECT(eo & PosixFlags::Global);
  76. EXPECT(!(eo & PosixFlags::Insensitive));
  77. EXPECT(eo & PosixFlags::Multiline);
  78. }
  79. TEST_CASE(regex_lexer)
  80. {
  81. Lexer l("/[.*+?^${}()|[\\]\\\\]/g"sv);
  82. EXPECT(l.next().type() == regex::TokenType::Slash);
  83. EXPECT(l.next().type() == regex::TokenType::LeftBracket);
  84. EXPECT(l.next().type() == regex::TokenType::Period);
  85. EXPECT(l.next().type() == regex::TokenType::Asterisk);
  86. EXPECT(l.next().type() == regex::TokenType::Plus);
  87. EXPECT(l.next().type() == regex::TokenType::Questionmark);
  88. EXPECT(l.next().type() == regex::TokenType::Circumflex);
  89. EXPECT(l.next().type() == regex::TokenType::Dollar);
  90. EXPECT(l.next().type() == regex::TokenType::LeftCurly);
  91. EXPECT(l.next().type() == regex::TokenType::RightCurly);
  92. EXPECT(l.next().type() == regex::TokenType::LeftParen);
  93. EXPECT(l.next().type() == regex::TokenType::RightParen);
  94. EXPECT(l.next().type() == regex::TokenType::Pipe);
  95. EXPECT(l.next().type() == regex::TokenType::LeftBracket);
  96. EXPECT(l.next().type() == regex::TokenType::EscapeSequence);
  97. EXPECT(l.next().type() == regex::TokenType::EscapeSequence);
  98. EXPECT(l.next().type() == regex::TokenType::RightBracket);
  99. EXPECT(l.next().type() == regex::TokenType::Slash);
  100. EXPECT(l.next().type() == regex::TokenType::Char);
  101. }
  102. TEST_CASE(parser_error_parens)
  103. {
  104. String pattern = "test()test";
  105. Lexer l(pattern);
  106. PosixExtendedParser p(l);
  107. p.parse();
  108. EXPECT(p.has_error());
  109. EXPECT(p.error() == regex::Error::EmptySubExpression);
  110. }
  111. TEST_CASE(parser_error_special_characters_used_at_wrong_place)
  112. {
  113. String pattern;
  114. Vector<char, 5> chars = { '*', '+', '?', '{' };
  115. StringBuilder b;
  116. Lexer l;
  117. PosixExtended p(l);
  118. for (auto& ch : chars) {
  119. // First in ere
  120. b.clear();
  121. b.append(ch);
  122. pattern = b.build();
  123. l.set_source(pattern);
  124. p.parse();
  125. EXPECT(p.has_error());
  126. EXPECT(p.error() == regex::Error::InvalidRepetitionMarker);
  127. // After vertical line
  128. b.clear();
  129. b.append("a|"sv);
  130. b.append(ch);
  131. pattern = b.build();
  132. l.set_source(pattern);
  133. p.parse();
  134. EXPECT(p.has_error());
  135. EXPECT(p.error() == regex::Error::InvalidRepetitionMarker);
  136. // After circumflex
  137. b.clear();
  138. b.append('^');
  139. b.append(ch);
  140. pattern = b.build();
  141. l.set_source(pattern);
  142. p.parse();
  143. EXPECT(p.has_error());
  144. EXPECT(p.error() == regex::Error::InvalidRepetitionMarker);
  145. // After dollar
  146. b.clear();
  147. b.append('$');
  148. b.append(ch);
  149. pattern = b.build();
  150. l.set_source(pattern);
  151. p.parse();
  152. EXPECT(p.has_error());
  153. EXPECT(p.error() == regex::Error::InvalidRepetitionMarker);
  154. // After left parens
  155. b.clear();
  156. b.append('(');
  157. b.append(ch);
  158. b.append(')');
  159. pattern = b.build();
  160. l.set_source(pattern);
  161. p.parse();
  162. EXPECT(p.has_error());
  163. EXPECT(p.error() == regex::Error::InvalidRepetitionMarker);
  164. }
  165. }
  166. TEST_CASE(parser_error_vertical_line_used_at_wrong_place)
  167. {
  168. Lexer l;
  169. PosixExtended p(l);
  170. // First in ere
  171. l.set_source("|asdf"sv);
  172. p.parse();
  173. EXPECT(p.has_error());
  174. EXPECT(p.error() == regex::Error::EmptySubExpression);
  175. // Last in ere
  176. l.set_source("asdf|"sv);
  177. p.parse();
  178. EXPECT(p.has_error());
  179. EXPECT(p.error() == regex::Error::EmptySubExpression);
  180. // After left parens
  181. l.set_source("(|asdf)"sv);
  182. p.parse();
  183. EXPECT(p.has_error());
  184. EXPECT(p.error() == regex::Error::EmptySubExpression);
  185. // Proceed right parens
  186. l.set_source("(asdf)|"sv);
  187. p.parse();
  188. EXPECT(p.has_error());
  189. EXPECT(p.error() == regex::Error::EmptySubExpression);
  190. }
  191. TEST_CASE(catch_all_first)
  192. {
  193. Regex<PosixExtended> re("^.*$");
  194. RegexResult m;
  195. re.match("Hello World"sv, m);
  196. EXPECT(m.count == 1);
  197. EXPECT(re.match("Hello World"sv, m));
  198. }
  199. TEST_CASE(catch_all)
  200. {
  201. Regex<PosixExtended> re("^.*$", PosixFlags::Global);
  202. EXPECT(re.has_match("Hello World"sv));
  203. EXPECT(re.match("Hello World"sv).success);
  204. EXPECT(re.match("Hello World"sv).count == 1);
  205. EXPECT(has_match("Hello World"sv, re));
  206. auto res = match("Hello World"sv, re);
  207. EXPECT(res.success);
  208. EXPECT(res.count == 1);
  209. EXPECT(res.matches.size() == 1);
  210. EXPECT(res.matches.first().view == "Hello World");
  211. }
  212. TEST_CASE(catch_all_again)
  213. {
  214. Regex<PosixExtended> re("^.*$", PosixFlags::Extra);
  215. EXPECT_EQ(has_match("Hello World"sv, re), true);
  216. }
  217. TEST_CASE(char_utf8)
  218. {
  219. Regex<PosixExtended> re("😀");
  220. RegexResult result;
  221. EXPECT_EQ((result = match(Utf8View { "Привет, мир! 😀 γειά σου κόσμος 😀 こんにちは世界"sv }, re, PosixFlags::Global)).success, true);
  222. EXPECT_EQ(result.count, 2u);
  223. }
  224. TEST_CASE(catch_all_newline)
  225. {
  226. Regex<PosixExtended> re("^.*$", PosixFlags::Multiline | PosixFlags::StringCopyMatches);
  227. RegexResult result;
  228. auto lambda = [&result, &re]() {
  229. String aaa = "Hello World\nTest\n1234\n";
  230. result = match(aaa, re);
  231. EXPECT_EQ(result.success, true);
  232. };
  233. lambda();
  234. EXPECT_EQ(result.count, 3u);
  235. EXPECT_EQ(result.matches.at(0).view, "Hello World");
  236. EXPECT_EQ(result.matches.at(1).view, "Test");
  237. EXPECT_EQ(result.matches.at(2).view, "1234");
  238. }
  239. TEST_CASE(catch_all_newline_view)
  240. {
  241. Regex<PosixExtended> re("^.*$", PosixFlags::Multiline);
  242. RegexResult result;
  243. String aaa = "Hello World\nTest\n1234\n";
  244. result = match(aaa, re);
  245. EXPECT_EQ(result.success, true);
  246. EXPECT_EQ(result.count, 3u);
  247. String str = "Hello World";
  248. EXPECT_EQ(result.matches.at(0).view, str.view());
  249. EXPECT_EQ(result.matches.at(1).view, "Test");
  250. EXPECT_EQ(result.matches.at(2).view, "1234");
  251. }
  252. TEST_CASE(catch_all_newline_2)
  253. {
  254. Regex<PosixExtended> re("^.*$");
  255. RegexResult result;
  256. result = match("Hello World\nTest\n1234\n"sv, re, PosixFlags::Multiline | PosixFlags::StringCopyMatches);
  257. EXPECT_EQ(result.success, true);
  258. EXPECT_EQ(result.count, 3u);
  259. EXPECT_EQ(result.matches.at(0).view, "Hello World");
  260. EXPECT_EQ(result.matches.at(1).view, "Test");
  261. EXPECT_EQ(result.matches.at(2).view, "1234");
  262. result = match("Hello World\nTest\n1234\n"sv, re);
  263. EXPECT_EQ(result.success, true);
  264. EXPECT_EQ(result.count, 1u);
  265. EXPECT_EQ(result.matches.at(0).view, "Hello World\nTest\n1234\n");
  266. }
  267. TEST_CASE(match_all_character_class)
  268. {
  269. Regex<PosixExtended> re("[[:alpha:]]");
  270. String str = "[Window]\nOpacity=255\nAudibleBeep=0\n";
  271. RegexResult result = match(str, re, PosixFlags::Global | PosixFlags::StringCopyMatches);
  272. EXPECT_EQ(result.success, true);
  273. EXPECT_EQ(result.count, 24u);
  274. EXPECT_EQ(result.matches.at(0).view, "W");
  275. EXPECT_EQ(result.matches.at(1).view, "i");
  276. EXPECT_EQ(result.matches.at(2).view, "n");
  277. }
  278. TEST_CASE(match_character_class_with_assertion)
  279. {
  280. Regex<PosixExtended> re("[[:alpha:]]+$");
  281. String str = "abcdef";
  282. RegexResult result = match(str, re);
  283. EXPECT_EQ(result.success, true);
  284. EXPECT_EQ(result.count, 1u);
  285. }
  286. TEST_CASE(example_for_git_commit)
  287. {
  288. Regex<PosixExtended> re("^.*$");
  289. auto result = re.match("Well, hello friends!\nHello World!"sv);
  290. EXPECT(result.success);
  291. EXPECT(result.count == 1);
  292. EXPECT(result.matches.at(0).view.starts_with("Well"sv));
  293. EXPECT(result.matches.at(0).view.length() == 33);
  294. EXPECT(re.has_match("Well,...."sv));
  295. result = re.match("Well, hello friends!\nHello World!"sv, PosixFlags::Multiline);
  296. EXPECT(result.success);
  297. EXPECT(result.count == 2);
  298. EXPECT(result.matches.at(0).view == "Well, hello friends!");
  299. EXPECT(result.matches.at(1).view == "Hello World!");
  300. }
  301. TEST_CASE(email_address)
  302. {
  303. Regex<PosixExtended> re("^[A-Z0-9a-z._%+-]{1,64}@([A-Za-z0-9-]{1,63}\\.){1,125}[A-Za-z]{2,63}$");
  304. EXPECT(re.has_match("hello.world@domain.tld"sv));
  305. EXPECT(re.has_match("this.is.a.very_long_email_address@world.wide.web"sv));
  306. }
  307. TEST_CASE(ini_file_entries)
  308. {
  309. Regex<PosixExtended> re("[[:alpha:]]*=([[:digit:]]*)|\\[(.*)\\]");
  310. RegexResult result;
  311. if constexpr (REGEX_DEBUG) {
  312. RegexDebug regex_dbg(stderr);
  313. regex_dbg.print_raw_bytecode(re);
  314. regex_dbg.print_header();
  315. regex_dbg.print_bytecode(re);
  316. }
  317. String haystack = "[Window]\nOpacity=255\nAudibleBeep=0\n";
  318. EXPECT_EQ(re.search(haystack.view(), result, PosixFlags::Multiline), true);
  319. EXPECT_EQ(result.count, 3u);
  320. if constexpr (REGEX_DEBUG) {
  321. for (auto& v : result.matches)
  322. fprintf(stderr, "%s\n", v.view.to_string().characters());
  323. }
  324. EXPECT_EQ(result.matches.at(0).view, "[Window]");
  325. EXPECT_EQ(result.capture_group_matches.at(0).at(0).view, "Window");
  326. EXPECT_EQ(result.matches.at(1).view, "Opacity=255");
  327. EXPECT_EQ(result.matches.at(1).line, 1u);
  328. EXPECT_EQ(result.matches.at(1).column, 0u);
  329. EXPECT_EQ(result.capture_group_matches.at(1).at(0).view, "255");
  330. EXPECT_EQ(result.capture_group_matches.at(1).at(0).line, 1u);
  331. EXPECT_EQ(result.capture_group_matches.at(1).at(0).column, 8u);
  332. EXPECT_EQ(result.matches.at(2).view, "AudibleBeep=0");
  333. EXPECT_EQ(result.capture_group_matches.at(2).at(0).view, "0");
  334. EXPECT_EQ(result.capture_group_matches.at(2).at(0).line, 2u);
  335. EXPECT_EQ(result.capture_group_matches.at(2).at(0).column, 12u);
  336. }
  337. TEST_CASE(ini_file_entries2)
  338. {
  339. Regex<PosixExtended> re("[[:alpha:]]*=([[:digit:]]*)");
  340. RegexResult result;
  341. String haystack = "ViewMode=Icon";
  342. EXPECT_EQ(re.match(haystack.view(), result), false);
  343. EXPECT_EQ(result.count, 0u);
  344. EXPECT_EQ(re.search(haystack.view(), result), true);
  345. EXPECT_EQ(result.count, 1u);
  346. }
  347. TEST_CASE(named_capture_group)
  348. {
  349. Regex<PosixExtended> re("[[:alpha:]]*=(?<Test>[[:digit:]]*)");
  350. RegexResult result;
  351. if constexpr (REGEX_DEBUG) {
  352. RegexDebug regex_dbg(stderr);
  353. regex_dbg.print_raw_bytecode(re);
  354. regex_dbg.print_header();
  355. regex_dbg.print_bytecode(re);
  356. }
  357. String haystack = "[Window]\nOpacity=255\nAudibleBeep=0\n";
  358. EXPECT_EQ(re.search(haystack, result, PosixFlags::Multiline), true);
  359. EXPECT_EQ(result.count, 2u);
  360. EXPECT_EQ(result.matches.at(0).view, "Opacity=255");
  361. EXPECT_EQ(result.capture_group_matches.at(0).at(0).view, "255");
  362. EXPECT_EQ(result.capture_group_matches.at(0).at(0).capture_group_name, "Test");
  363. EXPECT_EQ(result.matches.at(1).view, "AudibleBeep=0");
  364. EXPECT_EQ(result.capture_group_matches.at(1).at(0).view, "0");
  365. EXPECT_EQ(result.capture_group_matches.at(1).at(0).capture_group_name, "Test");
  366. }
  367. TEST_CASE(ecma262_named_capture_group_with_dollar_sign)
  368. {
  369. Regex<ECMA262> re("[a-zA-Z]*=(?<$Test$>[0-9]*)");
  370. RegexResult result;
  371. if constexpr (REGEX_DEBUG) {
  372. RegexDebug regex_dbg(stderr);
  373. regex_dbg.print_raw_bytecode(re);
  374. regex_dbg.print_header();
  375. regex_dbg.print_bytecode(re);
  376. }
  377. String haystack = "[Window]\nOpacity=255\nAudibleBeep=0\n";
  378. EXPECT_EQ(re.search(haystack, result, ECMAScriptFlags::Multiline), true);
  379. EXPECT_EQ(result.count, 2u);
  380. EXPECT_EQ(result.matches.at(0).view, "Opacity=255");
  381. EXPECT_EQ(result.capture_group_matches.at(0).at(0).view, "255");
  382. EXPECT_EQ(result.capture_group_matches.at(0).at(0).capture_group_name, "$Test$");
  383. EXPECT_EQ(result.matches.at(1).view, "AudibleBeep=0");
  384. EXPECT_EQ(result.capture_group_matches.at(1).at(0).view, "0");
  385. EXPECT_EQ(result.capture_group_matches.at(1).at(0).capture_group_name, "$Test$");
  386. }
  387. TEST_CASE(a_star)
  388. {
  389. Regex<PosixExtended> re("a*");
  390. RegexResult result;
  391. if constexpr (REGEX_DEBUG) {
  392. RegexDebug regex_dbg(stderr);
  393. regex_dbg.print_raw_bytecode(re);
  394. regex_dbg.print_header();
  395. regex_dbg.print_bytecode(re);
  396. }
  397. String haystack = "[Window]\nOpacity=255\nAudibleBeep=0\n";
  398. EXPECT_EQ(re.search(haystack.view(), result, PosixFlags::Multiline), true);
  399. EXPECT_EQ(result.count, 32u);
  400. if (result.count == 32u) {
  401. EXPECT_EQ(result.matches.at(0).view.length(), 0u);
  402. EXPECT_EQ(result.matches.at(10).view.length(), 1u);
  403. EXPECT_EQ(result.matches.at(10).view, "a");
  404. EXPECT_EQ(result.matches.at(31).view.length(), 0u);
  405. }
  406. }
  407. TEST_CASE(simple_period_end_benchmark)
  408. {
  409. Regex<PosixExtended> re("hello.$");
  410. RegexResult m;
  411. EXPECT_EQ(re.search("Hello1"sv, m), false);
  412. EXPECT_EQ(re.search("hello1hello1"sv, m), true);
  413. EXPECT_EQ(re.search("hello2hell"sv, m), false);
  414. EXPECT_EQ(re.search("hello?"sv, m), true);
  415. }
  416. TEST_CASE(posix_extended_nested_capture_group)
  417. {
  418. Regex<PosixExtended> re("(h(e(?<llo>llo)))"); // group 0 -> "hello", group 1 -> "ello", group 2/"llo" -> "llo"
  419. auto result = re.match("hello"sv);
  420. EXPECT(result.success);
  421. EXPECT_EQ(result.capture_group_matches.size(), 1u);
  422. EXPECT_EQ(result.capture_group_matches[0].size(), 3u);
  423. EXPECT_EQ(result.capture_group_matches[0][0].view, "hello"sv);
  424. EXPECT_EQ(result.capture_group_matches[0][1].view, "ello"sv);
  425. EXPECT_EQ(result.capture_group_matches[0][2].view, "llo"sv);
  426. }
  427. auto parse_test_case_long_disjunction_chain = String::repeated("a|"sv, 100000);
  428. TEST_CASE(ECMA262_parse)
  429. {
  430. struct _test {
  431. StringView pattern;
  432. regex::Error expected_error { regex::Error::NoError };
  433. regex::ECMAScriptFlags flags {};
  434. };
  435. _test const tests[] {
  436. { "^hello.$"sv },
  437. { "^(hello.)$"sv },
  438. { "^h{0,1}ello.$"sv },
  439. { "^hello\\W$"sv },
  440. { "^hell\\w.$"sv },
  441. { "^hell\\x6f1$"sv }, // ^hello1$
  442. { "^hel(?:l\\w).$"sv },
  443. { "^hel(?<LO>l\\w).$"sv },
  444. { "^[-a-zA-Z\\w\\s]+$"sv },
  445. { "\\bhello\\B"sv },
  446. { "^[\\w+/_-]+[=]{0,2}$"sv }, // #4189
  447. { "^(?:[^<]*(<[\\w\\W]+>)[^>]*$|#([\\w\\-]*)$)"sv }, // #4189
  448. { "\\/"sv }, // #4189
  449. { ",/=-:"sv }, // #4243
  450. { "\\x"sv }, // Even invalid escapes are allowed if ~unicode.
  451. { "\\x1"sv }, // Even invalid escapes are allowed if ~unicode.
  452. { "\\x1"sv, regex::Error::InvalidPattern, regex::ECMAScriptFlags::Unicode },
  453. { "\\x11"sv },
  454. { "\\x11"sv, regex::Error::NoError, regex::ECMAScriptFlags::Unicode },
  455. { "\\"sv, regex::Error::InvalidTrailingEscape },
  456. { "(?"sv, regex::Error::InvalidCaptureGroup },
  457. { "\\u1234"sv, regex::Error::NoError, regex::ECMAScriptFlags::Unicode },
  458. { "[\\u1234]"sv, regex::Error::NoError, regex::ECMAScriptFlags::Unicode },
  459. { "\\u1"sv, regex::Error::InvalidPattern, regex::ECMAScriptFlags::Unicode },
  460. { "[\\u1]"sv, regex::Error::InvalidPattern, regex::ECMAScriptFlags::Unicode },
  461. { ",(?"sv, regex::Error::InvalidCaptureGroup }, // #4583
  462. { "{1}"sv, regex::Error::InvalidPattern },
  463. { "{1,2}"sv, regex::Error::InvalidPattern },
  464. { "\\uxxxx"sv, regex::Error::NoError },
  465. { "\\uxxxx"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  466. { "\\ud83d"sv, regex::Error::NoError, ECMAScriptFlags::Unicode },
  467. { "\\ud83d\\uxxxx"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  468. { "\\u{0}"sv },
  469. { "\\u{0}"sv, regex::Error::NoError, ECMAScriptFlags::Unicode },
  470. { "\\u{10ffff}"sv, regex::Error::NoError, ECMAScriptFlags::Unicode },
  471. { "\\u{10ffff"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  472. { "\\u{10ffffx"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  473. { "\\u{110000}"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  474. { "\\p"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  475. { "\\p{"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  476. { "\\p{}"sv, regex::Error::InvalidNameForProperty, ECMAScriptFlags::Unicode },
  477. { "\\p{AsCiI}"sv, regex::Error::InvalidNameForProperty, ECMAScriptFlags::Unicode },
  478. { "\\p{hello friends}"sv, regex::Error::InvalidNameForProperty, ECMAScriptFlags::Unicode },
  479. { "\\p{Prepended_Concatenation_Mark}"sv, regex::Error::InvalidNameForProperty, ECMAScriptFlags::Unicode },
  480. { "\\p{ASCII}"sv, regex::Error::NoError, ECMAScriptFlags::Unicode },
  481. { "\\\\p{1}"sv, regex::Error::NoError, ECMAScriptFlags::Unicode },
  482. { "\\\\p{AsCiI}"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  483. { "\\\\p{ASCII}"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  484. { "\\c"sv, regex::Error::NoError, ECMAScriptFlags::BrowserExtended },
  485. { "\\c"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  486. { "[\\c]"sv, regex::Error::NoError, ECMAScriptFlags::BrowserExtended },
  487. { "[\\c]"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  488. { "\\c`"sv, regex::Error::NoError, ECMAScriptFlags::BrowserExtended },
  489. { "\\c`"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  490. { "[\\c`]"sv, regex::Error::NoError, ECMAScriptFlags::BrowserExtended },
  491. { "[\\c`]"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  492. { "\\A"sv, regex::Error::NoError, ECMAScriptFlags::BrowserExtended },
  493. { "\\A"sv, regex::Error::InvalidCharacterClass, ECMAScriptFlags::Unicode },
  494. { "[\\A]"sv, regex::Error::NoError, ECMAScriptFlags::BrowserExtended },
  495. { "[\\A]"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  496. { "\\0"sv, regex::Error::NoError, ECMAScriptFlags::BrowserExtended },
  497. { "\\0"sv, regex::Error::NoError, combine_flags(ECMAScriptFlags::Unicode, ECMAScriptFlags::BrowserExtended) },
  498. { "\\00"sv, regex::Error::NoError, ECMAScriptFlags::BrowserExtended },
  499. { "\\00"sv, regex::Error::InvalidCharacterClass, combine_flags(ECMAScriptFlags::Unicode, ECMAScriptFlags::BrowserExtended) },
  500. { "[\\0]"sv, regex::Error::NoError, ECMAScriptFlags::BrowserExtended },
  501. { "[\\0]"sv, regex::Error::NoError, combine_flags(ECMAScriptFlags::Unicode, ECMAScriptFlags::BrowserExtended) },
  502. { "[\\00]"sv, regex::Error::NoError, ECMAScriptFlags::BrowserExtended },
  503. { "[\\00]"sv, regex::Error::InvalidPattern, combine_flags(ECMAScriptFlags::Unicode, ECMAScriptFlags::BrowserExtended) },
  504. { "\\^\\$\\\\\\.\\*\\+\\?\\(\\)\\[\\]\\{\\}\\|\\/"sv, regex::Error::NoError, ECMAScriptFlags::Unicode },
  505. { "[\\^\\$\\\\\\.\\*\\+\\?\\(\\)\\[\\]\\{\\}\\|\\/]"sv, regex::Error::NoError, ECMAScriptFlags::Unicode },
  506. { "]"sv, regex::Error::NoError, ECMAScriptFlags::BrowserExtended },
  507. { "]"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  508. { "\\]"sv, regex::Error::NoError, ECMAScriptFlags::Unicode },
  509. { "}"sv, regex::Error::NoError, ECMAScriptFlags::BrowserExtended },
  510. { "}"sv, regex::Error::InvalidPattern, ECMAScriptFlags::Unicode },
  511. { "\\}"sv, regex::Error::NoError, ECMAScriptFlags::Unicode },
  512. { "a{9007199254740991}"sv }, // 2^53 - 1
  513. { "a{9007199254740991,}"sv },
  514. { "a{9007199254740991,9007199254740991}"sv },
  515. { "a{9007199254740992}"sv, regex::Error::InvalidBraceContent },
  516. { "a{9007199254740992,}"sv, regex::Error::InvalidBraceContent },
  517. { "a{9007199254740991,9007199254740992}"sv, regex::Error::InvalidBraceContent },
  518. { "a{9007199254740992,9007199254740991}"sv, regex::Error::InvalidBraceContent },
  519. { "a{9007199254740992,9007199254740992}"sv, regex::Error::InvalidBraceContent },
  520. { "(?<a>a)(?<a>b)"sv, regex::Error::DuplicateNamedCapture },
  521. { "(?<a>a)(?<b>b)(?<a>c)"sv, regex::Error::DuplicateNamedCapture },
  522. { "(?<1a>a)"sv, regex::Error::InvalidNameForCaptureGroup },
  523. { "(?<\\a>a)"sv, regex::Error::InvalidNameForCaptureGroup },
  524. { "(?<\ta>a)"sv, regex::Error::InvalidNameForCaptureGroup },
  525. { "(?<$$_$$>a)"sv },
  526. { "(?<ÿ>a)"sv },
  527. { "(?<𝓑𝓻𝓸𝔀𝓷>a)"sv },
  528. { "((?=lg)?[vl]k\\-?\\d{3}) bui| 3\\.[-\\w; ]{10}lg?-([06cv9]{3,4})"sv, regex::Error::NoError, ECMAScriptFlags::BrowserExtended }, // #12373, quantifiable assertions.
  529. { parse_test_case_long_disjunction_chain.view() }, // A whole lot of disjunctions, should not overflow the stack.
  530. { "(\"|')(?:(?!\\2)[^\\\\\\r\\n]|\\\\.)*\\2"sv, regex::Error::NoError, ECMAScriptFlags::BrowserExtended }, // LegacyOctalEscapeSequence should not consume too many chars (and should not crash)
  531. };
  532. for (auto& test : tests) {
  533. Regex<ECMA262> re(test.pattern, test.flags);
  534. EXPECT_EQ(re.parser_result.error, test.expected_error);
  535. if constexpr (REGEX_DEBUG) {
  536. dbgln("\n");
  537. RegexDebug regex_dbg(stderr);
  538. regex_dbg.print_raw_bytecode(re);
  539. regex_dbg.print_header();
  540. regex_dbg.print_bytecode(re);
  541. dbgln("\n");
  542. }
  543. }
  544. }
  545. TEST_CASE(ECMA262_match)
  546. {
  547. struct _test {
  548. StringView pattern;
  549. StringView subject;
  550. bool matches { true };
  551. ECMAScriptFlags options {};
  552. };
  553. // clang-format off
  554. constexpr _test tests[] {
  555. { "^hello.$"sv, "hello1"sv },
  556. { "^(hello.)$"sv, "hello1"sv },
  557. { "^h{0,1}ello.$"sv, "ello1"sv },
  558. { "^hello\\W$"sv, "hello!"sv },
  559. { "^hell\\w.$"sv, "hellx!"sv },
  560. { "^hell\\x6f1$"sv, "hello1"sv },
  561. { "^hel(?<LO>l.)1$"sv, "hello1"sv },
  562. { "^hel(?<LO>l.)1*\\k<LO>.$"sv, "hello1lo1"sv },
  563. { "^[-a-z1-3\\s]+$"sv, "hell2 o1"sv },
  564. { "^[\\0-\\x1f]$"sv, "\n"sv },
  565. { .pattern = "\\bhello\\B"sv, .subject = "hello1"sv, .options = ECMAScriptFlags::Global },
  566. { "\\b.*\\b"sv, "hello1"sv },
  567. { "[^\\D\\S]{2}"sv, "1 "sv },
  568. { "bar(?=f.)foo"sv, "barfoo"sv },
  569. { "bar(?=foo)bar"sv, "barbar"sv, false },
  570. { "bar(?!foo)bar"sv, "barbar"sv, true },
  571. { "bar(?!bar)bar"sv, "barbar"sv, false },
  572. { "bar.*(?<=foo)"sv, "barbar"sv, false },
  573. { "bar.*(?<!foo)"sv, "barbar"sv, true },
  574. { "((...)X)+"sv, "fooXbarXbazX"sv, true },
  575. { "(?:)"sv, ""sv, true },
  576. { "\\^"sv, "^"sv },
  577. { "\\^\\$\\\\\\.\\*\\+\\?\\(\\)\\[\\]\\{\\}\\|\\/"sv, "^$\\.*+?()[]{}|/"sv, true, ECMAScriptFlags::Unicode },
  578. { "[\\^\\$\\\\\\.\\*\\+\\?\\(\\)\\[\\]\\{\\}\\|\\/]{15}"sv, "^$\\.*+?()[]{}|/"sv, true, ECMAScriptFlags::Unicode },
  579. { "(a{2}){3}"sv, "aaaaaa"sv },
  580. { "(a{2}){3}"sv, "aaaabaa"sv, false },
  581. { "(a{2}){4}"sv, "aaaaaaaa"sv },
  582. { "(a{2}){4}"sv, "aaaaaabaa"sv, false },
  583. { "(a{3}){2}"sv, "aaaaaa"sv },
  584. { "(a{3}){2}"sv, "aaaabaa"sv, false },
  585. { "(a{4}){2}"sv, "aaaaaaaa"sv },
  586. { "(a{4}){2}"sv, "aaaaaabaa"sv, false },
  587. { "\\u{4}"sv, "uuuu"sv },
  588. { "(?<=.{3})f"sv, "abcdef"sv, true, (ECMAScriptFlags)regex::AllFlags::Global },
  589. { "(?<=.{3})f"sv, "abc😀ef"sv, true, (ECMAScriptFlags)regex::AllFlags::Global },
  590. // ECMA262, B.1.4. Regular Expression Pattern extensions for browsers
  591. { "{"sv, "{"sv, true, ECMAScriptFlags::BrowserExtended },
  592. { "\\5"sv, "\5"sv, true, ECMAScriptFlags::BrowserExtended },
  593. { "\\05"sv, "\5"sv, true, ECMAScriptFlags::BrowserExtended },
  594. { "\\455"sv, "\45""5"sv, true, ECMAScriptFlags::BrowserExtended },
  595. { "\\314"sv, "\314"sv, true, ECMAScriptFlags::BrowserExtended },
  596. { "\\c"sv, "\\c"sv, true, ECMAScriptFlags::BrowserExtended },
  597. { "\\cf"sv, "\06"sv, true, ECMAScriptFlags::BrowserExtended },
  598. { "\\c1"sv, "\\c1"sv, true, ECMAScriptFlags::BrowserExtended },
  599. { "[\\c1]"sv, "\x11"sv, true, ECMAScriptFlags::BrowserExtended },
  600. { "[\\w-\\d]"sv, "-"sv, true, ECMAScriptFlags::BrowserExtended },
  601. { "^(?:^^\\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|,|-=|->|\\/|\\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\\^=|\\^\\^|\\^\\^=|{|\\||\\|=|\\|\\||\\|\\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*(\\/(?=[^*/])(?:[^/[\\\\]|\\\\[\\S\\s]|\\[(?:[^\\\\\\]]|\\\\[\\S\\s])*(?:]|$))+\\/)"sv,
  602. "return /xx/"sv, true, ECMAScriptFlags::BrowserExtended
  603. }, // #5517, appears to be matching JS expressions that involve regular expressions...
  604. { "a{2,}"sv, "aaaa"sv }, // #5518
  605. { "\\0"sv, "\0"sv, true, ECMAScriptFlags::BrowserExtended },
  606. { "\\0"sv, "\0"sv, true, combine_flags(ECMAScriptFlags::Unicode, ECMAScriptFlags::BrowserExtended) },
  607. { "\\01"sv, "\1"sv, true, ECMAScriptFlags::BrowserExtended },
  608. { "[\\0]"sv, "\0"sv, true, ECMAScriptFlags::BrowserExtended },
  609. { "[\\0]"sv, "\0"sv, true, combine_flags(ECMAScriptFlags::Unicode, ECMAScriptFlags::BrowserExtended) },
  610. { "[\\01]"sv, "\1"sv, true, ECMAScriptFlags::BrowserExtended },
  611. { "(\0|a)"sv, "a"sv, true }, // #9686, Should allow null bytes in pattern
  612. { "(.*?)a(?!(a+)b\\2c)\\2(.*)"sv, "baaabaac"sv, true }, // #6042, Groups inside lookarounds may be referenced outside, but their contents appear empty if the pattern in the lookaround fails.
  613. { "a|$"sv, "x"sv, true, (ECMAScriptFlags)regex::AllFlags::Global }, // #11940, Global (not the 'g' flag) regexps should attempt to match the zero-length end of the string too.
  614. { "foo\nbar"sv, "foo\nbar"sv, true }, // #12126, ECMA262 regexp should match literal newlines without the 's' flag.
  615. { "foo[^]bar"sv, "foo\nbar"sv, true }, // #12126, ECMA262 regexp should match newline with [^].
  616. { "^[_A-Z]+$"sv, "_aA"sv, true, ECMAScriptFlags::Insensitive }, // Insensitive lookup table: characters in a range do not necessarily lie in the same range after being converted to lowercase.
  617. { "^[a-sy-z]$"sv, "b"sv, true, ECMAScriptFlags::Insensitive },
  618. { "^[a-sy-z]$"sv, "y"sv, true, ECMAScriptFlags::Insensitive },
  619. { "^[a-sy-z]$"sv, "u"sv, false, ECMAScriptFlags::Insensitive },
  620. };
  621. // clang-format on
  622. for (auto& test : tests) {
  623. Regex<ECMA262> re(test.pattern, test.options);
  624. if constexpr (REGEX_DEBUG) {
  625. dbgln("\n");
  626. RegexDebug regex_dbg(stderr);
  627. regex_dbg.print_raw_bytecode(re);
  628. regex_dbg.print_header();
  629. regex_dbg.print_bytecode(re);
  630. dbgln("\n");
  631. }
  632. EXPECT_EQ(re.parser_result.error, regex::Error::NoError);
  633. EXPECT_EQ(re.match(test.subject).success, test.matches);
  634. }
  635. }
  636. TEST_CASE(ECMA262_unicode_match)
  637. {
  638. constexpr auto space_and_line_terminator_code_points = Array { 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x0020, 0x00A0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000, 0xFEFF };
  639. StringBuilder builder;
  640. for (u32 code_point : space_and_line_terminator_code_points)
  641. builder.append_code_point(code_point);
  642. auto space_and_line_terminators = builder.build();
  643. struct _test {
  644. StringView pattern;
  645. StringView subject;
  646. bool matches { true };
  647. ECMAScriptFlags options {};
  648. };
  649. _test tests[] {
  650. { "\xf0\x9d\x8c\x86"sv, "abcdef"sv, false, ECMAScriptFlags::Unicode },
  651. { "[\xf0\x9d\x8c\x86]"sv, "abcdef"sv, false, ECMAScriptFlags::Unicode },
  652. { "\\ud83d"sv, "😀"sv, true },
  653. { "\\ud83d"sv, "😀"sv, false, ECMAScriptFlags::Unicode },
  654. { "\\ude00"sv, "😀"sv, true },
  655. { "\\ude00"sv, "😀"sv, false, ECMAScriptFlags::Unicode },
  656. { "\\ud83d\\ude00"sv, "😀"sv, true },
  657. { "\\ud83d\\ude00"sv, "😀"sv, true, ECMAScriptFlags::Unicode },
  658. { "\\u{1f600}"sv, "😀"sv, true, ECMAScriptFlags::Unicode },
  659. { "\\ud83d\\ud83d"sv, "\xed\xa0\xbd\xed\xa0\xbd"sv, true },
  660. { "\\ud83d\\ud83d"sv, "\xed\xa0\xbd\xed\xa0\xbd"sv, true, ECMAScriptFlags::Unicode },
  661. { "(?<=.{3})f"sv, "abcdef"sv, true, ECMAScriptFlags::Unicode },
  662. { "(?<=.{3})f"sv, "abc😀ef"sv, true, ECMAScriptFlags::Unicode },
  663. { "(?<𝓑𝓻𝓸𝔀𝓷>brown)"sv, "brown"sv, true, ECMAScriptFlags::Unicode },
  664. { "(?<\\u{1d4d1}\\u{1d4fb}\\u{1d4f8}\\u{1d500}\\u{1d4f7}>brown)"sv, "brown"sv, true, ECMAScriptFlags::Unicode },
  665. { "(?<\\ud835\\udcd1\\ud835\\udcfb\\ud835\\udcf8\\ud835\\udd00\\ud835\\udcf7>brown)"sv, "brown"sv, true, ECMAScriptFlags::Unicode },
  666. { "^\\s+$"sv, space_and_line_terminators },
  667. { "^\\s+$"sv, space_and_line_terminators, true, ECMAScriptFlags::Unicode },
  668. };
  669. for (auto& test : tests) {
  670. Regex<ECMA262> re(test.pattern, (ECMAScriptFlags)regex::AllFlags::Global | test.options);
  671. auto subject = AK::utf8_to_utf16(test.subject);
  672. Utf16View view { subject };
  673. if constexpr (REGEX_DEBUG) {
  674. dbgln("\n");
  675. RegexDebug regex_dbg(stderr);
  676. regex_dbg.print_raw_bytecode(re);
  677. regex_dbg.print_header();
  678. regex_dbg.print_bytecode(re);
  679. dbgln("\n");
  680. }
  681. EXPECT_EQ(re.parser_result.error, regex::Error::NoError);
  682. EXPECT_EQ(re.match(view).success, test.matches);
  683. }
  684. }
  685. TEST_CASE(ECMA262_unicode_sets_match)
  686. {
  687. struct _test {
  688. StringView pattern;
  689. StringView subject;
  690. bool matches { true };
  691. ECMAScriptFlags options {};
  692. };
  693. constexpr _test tests[] {
  694. { "[\\w--x]"sv, "x"sv, false },
  695. { "[\\w&&x]"sv, "y"sv, false },
  696. { "[\\w--x]"sv, "y"sv, true },
  697. { "[\\w&&x]"sv, "x"sv, true },
  698. { "[[0-9\\w]--x--6]"sv, "6"sv, false },
  699. { "[[0-9\\w]--x--6]"sv, "x"sv, false },
  700. { "[[0-9\\w]--x--6]"sv, "y"sv, true },
  701. { "[[0-9\\w]--x--6]"sv, "9"sv, true },
  702. { "[\\w&&\\d]"sv, "a"sv, false },
  703. { "[\\w&&\\d]"sv, "4"sv, true },
  704. };
  705. for (auto& test : tests) {
  706. Regex<ECMA262> re(test.pattern, (ECMAScriptFlags)regex::AllFlags::UnicodeSets | test.options);
  707. if constexpr (REGEX_DEBUG) {
  708. dbgln("\n");
  709. RegexDebug regex_dbg(stderr);
  710. regex_dbg.print_raw_bytecode(re);
  711. regex_dbg.print_header();
  712. regex_dbg.print_bytecode(re);
  713. dbgln("\n");
  714. }
  715. EXPECT_EQ(re.parser_result.error, regex::Error::NoError);
  716. auto result = re.match(test.subject).success;
  717. EXPECT_EQ(result, test.matches);
  718. }
  719. }
  720. TEST_CASE(ECMA262_property_match)
  721. {
  722. struct _test {
  723. StringView pattern;
  724. StringView subject;
  725. bool matches { true };
  726. ECMAScriptFlags options {};
  727. };
  728. constexpr _test tests[] {
  729. { "\\p{ASCII}"sv, "a"sv, false },
  730. { "\\p{ASCII}"sv, "p{ASCII}"sv, true },
  731. { "\\p{ASCII}"sv, "a"sv, true, ECMAScriptFlags::Unicode },
  732. { "\\p{ASCII}"sv, "😀"sv, false, ECMAScriptFlags::Unicode },
  733. { "\\P{ASCII}"sv, "a"sv, false, ECMAScriptFlags::Unicode },
  734. { "\\P{ASCII}"sv, "😀"sv, true, ECMAScriptFlags::Unicode },
  735. { "\\p{ASCII_Hex_Digit}"sv, "1"sv, true, ECMAScriptFlags::Unicode },
  736. { "\\p{ASCII_Hex_Digit}"sv, "a"sv, true, ECMAScriptFlags::Unicode },
  737. { "\\p{ASCII_Hex_Digit}"sv, "x"sv, false, ECMAScriptFlags::Unicode },
  738. { "\\P{ASCII_Hex_Digit}"sv, "1"sv, false, ECMAScriptFlags::Unicode },
  739. { "\\P{ASCII_Hex_Digit}"sv, "a"sv, false, ECMAScriptFlags::Unicode },
  740. { "\\P{ASCII_Hex_Digit}"sv, "x"sv, true, ECMAScriptFlags::Unicode },
  741. { "\\p{Any}"sv, "\xcd\xb8"sv, true, ECMAScriptFlags::Unicode }, // U+0378, which is an unassigned code point.
  742. { "\\P{Any}"sv, "\xcd\xb8"sv, false, ECMAScriptFlags::Unicode }, // U+0378, which is an unassigned code point.
  743. { "\\p{Assigned}"sv, "\xcd\xb8"sv, false, ECMAScriptFlags::Unicode }, // U+0378, which is an unassigned code point.
  744. { "\\P{Assigned}"sv, "\xcd\xb8"sv, true, ECMAScriptFlags::Unicode }, // U+0378, which is an unassigned code point.
  745. { "\\p{Lu}"sv, "a"sv, false, ECMAScriptFlags::Unicode },
  746. { "\\p{Lu}"sv, "A"sv, true, ECMAScriptFlags::Unicode },
  747. { "\\p{Lu}"sv, "9"sv, false, ECMAScriptFlags::Unicode },
  748. { "\\p{Cased_Letter}"sv, "a"sv, true, ECMAScriptFlags::Unicode },
  749. { "\\p{Cased_Letter}"sv, "A"sv, true, ECMAScriptFlags::Unicode },
  750. { "\\p{Cased_Letter}"sv, "9"sv, false, ECMAScriptFlags::Unicode },
  751. { "\\P{Cased_Letter}"sv, "a"sv, false, ECMAScriptFlags::Unicode },
  752. { "\\P{Cased_Letter}"sv, "A"sv, false, ECMAScriptFlags::Unicode },
  753. { "\\P{Cased_Letter}"sv, "9"sv, true, ECMAScriptFlags::Unicode },
  754. { "\\p{General_Category=Cased_Letter}"sv, "a"sv, true, ECMAScriptFlags::Unicode },
  755. { "\\p{General_Category=Cased_Letter}"sv, "A"sv, true, ECMAScriptFlags::Unicode },
  756. { "\\p{General_Category=Cased_Letter}"sv, "9"sv, false, ECMAScriptFlags::Unicode },
  757. { "\\p{gc=Cased_Letter}"sv, "a"sv, true, ECMAScriptFlags::Unicode },
  758. { "\\p{gc=Cased_Letter}"sv, "A"sv, true, ECMAScriptFlags::Unicode },
  759. { "\\p{gc=Cased_Letter}"sv, "9"sv, false, ECMAScriptFlags::Unicode },
  760. { "\\p{Script=Latin}"sv, "a"sv, true, ECMAScriptFlags::Unicode },
  761. { "\\p{Script=Latin}"sv, "A"sv, true, ECMAScriptFlags::Unicode },
  762. { "\\p{Script=Latin}"sv, "9"sv, false, ECMAScriptFlags::Unicode },
  763. { "\\p{sc=Latin}"sv, "a"sv, true, ECMAScriptFlags::Unicode },
  764. { "\\p{sc=Latin}"sv, "A"sv, true, ECMAScriptFlags::Unicode },
  765. { "\\p{sc=Latin}"sv, "9"sv, false, ECMAScriptFlags::Unicode },
  766. { "\\p{Script_Extensions=Deva}"sv, "a"sv, false, ECMAScriptFlags::Unicode },
  767. { "\\p{Script_Extensions=Beng}"sv, "\xe1\xb3\x95"sv, true, ECMAScriptFlags::Unicode }, // U+01CD5
  768. { "\\p{Script_Extensions=Deva}"sv, "\xe1\xb3\x95"sv, true, ECMAScriptFlags::Unicode }, // U+01CD5
  769. { "\\p{scx=Deva}"sv, "a"sv, false, ECMAScriptFlags::Unicode },
  770. { "\\p{scx=Beng}"sv, "\xe1\xb3\x95"sv, true, ECMAScriptFlags::Unicode }, // U+01CD5
  771. { "\\p{scx=Deva}"sv, "\xe1\xb3\x95"sv, true, ECMAScriptFlags::Unicode }, // U+01CD5
  772. };
  773. for (auto& test : tests) {
  774. Regex<ECMA262> re(test.pattern, (ECMAScriptFlags)regex::AllFlags::Global | regex::ECMAScriptFlags::BrowserExtended | test.options);
  775. auto subject = AK::utf8_to_utf16(test.subject);
  776. Utf16View view { subject };
  777. if constexpr (REGEX_DEBUG) {
  778. dbgln("\n");
  779. RegexDebug regex_dbg(stderr);
  780. regex_dbg.print_raw_bytecode(re);
  781. regex_dbg.print_header();
  782. regex_dbg.print_bytecode(re);
  783. dbgln("\n");
  784. }
  785. EXPECT_EQ(re.parser_result.error, regex::Error::NoError);
  786. EXPECT_EQ(re.match(view).success, test.matches);
  787. }
  788. }
  789. TEST_CASE(replace)
  790. {
  791. struct _test {
  792. StringView pattern;
  793. StringView replacement;
  794. StringView subject;
  795. StringView expected;
  796. ECMAScriptFlags options {};
  797. };
  798. constexpr _test tests[] {
  799. { "foo(.+)"sv, "aaa"sv, "test"sv, "test"sv },
  800. { "foo(.+)"sv, "test\\1"sv, "foobar"sv, "testbar"sv },
  801. { "foo(.+)"sv, "\\2\\1"sv, "foobar"sv, "\\2bar"sv },
  802. { "foo(.+)"sv, "\\\\\\1"sv, "foobar"sv, "\\bar"sv },
  803. { "foo(.)"sv, "a\\1"sv, "fooxfooy"sv, "axay"sv, ECMAScriptFlags::Multiline },
  804. };
  805. for (auto& test : tests) {
  806. Regex<ECMA262> re(test.pattern, test.options);
  807. if constexpr (REGEX_DEBUG) {
  808. dbgln("\n");
  809. RegexDebug regex_dbg(stderr);
  810. regex_dbg.print_raw_bytecode(re);
  811. regex_dbg.print_header();
  812. regex_dbg.print_bytecode(re);
  813. dbgln("\n");
  814. }
  815. EXPECT_EQ(re.parser_result.error, regex::Error::NoError);
  816. EXPECT_EQ(re.replace(test.subject, test.replacement), test.expected);
  817. }
  818. }
  819. TEST_CASE(case_insensitive_match)
  820. {
  821. Regex<PosixExtended> re("cd", PosixFlags::Insensitive | PosixFlags::Global);
  822. auto result = re.match("AEKFCD"sv);
  823. EXPECT_EQ(result.success, true);
  824. if (result.success) {
  825. EXPECT_EQ(result.matches.at(0).column, 4ul);
  826. }
  827. }
  828. TEST_CASE(extremely_long_fork_chain)
  829. {
  830. Regex<ECMA262> re("(?:aa)*");
  831. auto result = re.match(String::repeated('a', 1000));
  832. EXPECT_EQ(result.success, true);
  833. }
  834. TEST_CASE(theoretically_infinite_loop)
  835. {
  836. Array patterns {
  837. "(a*)*"sv, // Infinitely matching empty substrings, the outer loop should short-circuit.
  838. "(a*?)*"sv, // Infinitely matching empty substrings, the outer loop should short-circuit.
  839. "(a*)*?"sv, // Should match exactly nothing.
  840. "(?:)*?"sv, // Should not generate an infinite fork loop.
  841. };
  842. for (auto& pattern : patterns) {
  843. Regex<ECMA262> re(pattern);
  844. auto result = re.match(""sv);
  845. EXPECT_EQ(result.success, true);
  846. }
  847. }
  848. static auto g_lots_of_a_s = String::repeated('a', 10'000'000);
  849. BENCHMARK_CASE(fork_performance)
  850. {
  851. Regex<ECMA262> re("(?:aa)*");
  852. auto result = re.match(g_lots_of_a_s);
  853. EXPECT_EQ(result.success, true);
  854. }
  855. TEST_CASE(optimizer_atomic_groups)
  856. {
  857. Array tests {
  858. // Fork -> ForkReplace
  859. Tuple { "a*b"sv, "aaaaa"sv, false },
  860. Tuple { "a+b"sv, "aaaaa"sv, false },
  861. Tuple { "\\\\(\\d+)"sv, "\\\\"sv, false }, // Rewrite bug turning a+ to a*, see #10952.
  862. Tuple { "[a-z.]+\\."sv, "..."sv, true }, // Rewrite bug, incorrect interpretation of Compare.
  863. Tuple { "[.-]+\\."sv, ".-."sv, true },
  864. // Alternative fuse
  865. Tuple { "(abcfoo|abcbar|abcbaz).*x"sv, "abcbarx"sv, true },
  866. Tuple { "(a|a)"sv, "a"sv, true },
  867. Tuple { "(a|)"sv, ""sv, true }, // Ensure that empty alternatives are not outright removed
  868. Tuple { "a{2,3}|a{5,8}"sv, "abc"sv, false }, // Optimizer should not mess up the instruction stream by ignoring inter-insn dependencies, see #11247.
  869. Tuple { "^(a{2,3}|a{5,8})$"sv, "aaaa"sv, false }, // Optimizer should not mess up the instruction stream by ignoring inter-insn dependencies, see #11247.
  870. // Optimizer should not chop off *half* of an instruction when fusing instructions.
  871. Tuple { "cubic-bezier\\(\\s*(-?\\d+\\.?\\d*|-?\\.\\d+)\\s*,\\s*(-?\\d+\\.?\\d*|-?\\.\\d+)\\s*,\\s*(-?\\d+\\.?\\d*|-?\\.\\d+)\\s*,\\s*(-?\\d+\\.?\\d*|-?\\.\\d+)\\s*\\)"sv, "cubic-bezier(.05, 0, 0, 1)"sv, true },
  872. // ForkReplace shouldn't be applied where it would change the semantics
  873. Tuple { "(1+)\\1"sv, "11"sv, true },
  874. Tuple { "(1+)1"sv, "11"sv, true },
  875. Tuple { "(1+)0"sv, "10"sv, true },
  876. // Rewrite should not skip over first required iteration of <x>+.
  877. Tuple { "a+"sv, ""sv, false },
  878. };
  879. for (auto& test : tests) {
  880. Regex<ECMA262> re(test.get<0>());
  881. auto result = re.match(test.get<1>());
  882. EXPECT_EQ(result.success, test.get<2>());
  883. }
  884. }
  885. TEST_CASE(optimizer_char_class_lut)
  886. {
  887. Regex<ECMA262> re(R"([\f\n\r\t\v\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+$)");
  888. if constexpr (REGEX_DEBUG) {
  889. dbgln("\n");
  890. RegexDebug regex_dbg(stderr);
  891. regex_dbg.print_raw_bytecode(re);
  892. regex_dbg.print_header();
  893. regex_dbg.print_bytecode(re);
  894. dbgln("\n");
  895. }
  896. // This will go through _all_ alternatives in the character class, and then fail.
  897. for (size_t i = 0; i < 1'000'000; ++i)
  898. EXPECT_EQ(re.match("1635488940000"sv).success, false);
  899. }
  900. TEST_CASE(optimizer_alternation)
  901. {
  902. Array tests {
  903. // Pattern, Subject, Expected length
  904. Tuple { "a|"sv, "a"sv, 1u },
  905. };
  906. for (auto& test : tests) {
  907. Regex<ECMA262> re(test.get<0>());
  908. auto result = re.match(test.get<1>());
  909. EXPECT(result.success);
  910. EXPECT_EQ(result.matches.first().view.length(), test.get<2>());
  911. }
  912. }
  913. TEST_CASE(posix_basic_dollar_is_end_anchor)
  914. {
  915. // Ensure that a dollar sign at the end only matches the end of the line.
  916. {
  917. Regex<PosixBasic> re("abc$");
  918. EXPECT_EQ(re.match("123abcdef"sv, PosixFlags::Global).success, false);
  919. EXPECT_EQ(re.match("123abc"sv, PosixFlags::Global).success, true);
  920. EXPECT_EQ(re.match("123abc$def"sv, PosixFlags::Global).success, false);
  921. EXPECT_EQ(re.match("123abc$"sv, PosixFlags::Global).success, false);
  922. }
  923. }
  924. TEST_CASE(posix_basic_dollar_is_literal)
  925. {
  926. // Ensure that a dollar sign in the middle is treated as a literal.
  927. {
  928. Regex<PosixBasic> re("abc$d");
  929. EXPECT_EQ(re.match("123abcdef"sv, PosixFlags::Global).success, false);
  930. EXPECT_EQ(re.match("123abc"sv, PosixFlags::Global).success, false);
  931. EXPECT_EQ(re.match("123abc$def"sv, PosixFlags::Global).success, true);
  932. EXPECT_EQ(re.match("123abc$"sv, PosixFlags::Global).success, false);
  933. }
  934. // Ensure that a dollar sign is always treated as a literal if escaped, even if at the end of the pattern.
  935. {
  936. Regex<PosixBasic> re("abc\\$");
  937. EXPECT_EQ(re.match("123abcdef"sv, PosixFlags::Global).success, false);
  938. EXPECT_EQ(re.match("123abc"sv, PosixFlags::Global).success, false);
  939. EXPECT_EQ(re.match("123abc$def"sv, PosixFlags::Global).success, true);
  940. EXPECT_EQ(re.match("123abc$"sv, PosixFlags::Global).success, true);
  941. }
  942. }
  943. TEST_CASE(negative_lookahead)
  944. {
  945. {
  946. // Negative lookahead with more than 2 forks difference between lookahead init and finish.
  947. auto options = ECMAScriptOptions { ECMAScriptFlags::Global };
  948. options.reset_flag((ECMAScriptFlags)regex::AllFlags::Internal_Stateful);
  949. Regex<ECMA262> re(":(?!\\^\\)|1)", options);
  950. EXPECT_EQ(re.match(":^)"sv).success, false);
  951. EXPECT_EQ(re.match(":1"sv).success, false);
  952. EXPECT_EQ(re.match(":foobar"sv).success, true);
  953. }
  954. {
  955. // Correctly count forks with nested groups and optimised loops
  956. Regex<ECMA262> re("^((?:[^\\n]|\\n(?! *\\n))+)(?:\\n *)+\\n");
  957. EXPECT_EQ(re.match("foo\n\n"sv).success, true);
  958. EXPECT_EQ(re.match("foo\n"sv).success, false);
  959. }
  960. }
  961. TEST_CASE(single_match_flag)
  962. {
  963. {
  964. // Ensure that only a single match is produced and nothing past that.
  965. Regex<ECMA262> re("[\\u0008-\\uffff]"sv, ECMAScriptFlags::Global | (ECMAScriptFlags)regex::AllFlags::SingleMatch);
  966. auto result = re.match("ABC"sv);
  967. EXPECT_EQ(result.success, true);
  968. EXPECT_EQ(result.matches.size(), 1u);
  969. EXPECT_EQ(result.matches.first().view.to_string(), "A"sv);
  970. }
  971. }
  972. TEST_CASE(inversion_state_in_char_class)
  973. {
  974. {
  975. // #13755, /[\S\s]/.exec("hello") should be [ "h" ], not null.
  976. Regex<ECMA262> re("[\\S\\s]", ECMAScriptFlags::Global | (ECMAScriptFlags)regex::AllFlags::SingleMatch);
  977. auto result = re.match("hello"sv);
  978. EXPECT_EQ(result.success, true);
  979. EXPECT_EQ(result.matches.size(), 1u);
  980. EXPECT_EQ(result.matches.first().view.to_string(), "h"sv);
  981. }
  982. {
  983. Regex<ECMA262> re("^(?:([^\\s!\"#%-,\\./;->@\\[-\\^`\\{-~]+(?=([=~}\\s/.)|]))))"sv, ECMAScriptFlags::Global);
  984. auto result = re.match("slideNumbers}}"sv);
  985. EXPECT_EQ(result.success, true);
  986. EXPECT_EQ(result.matches.size(), 1u);
  987. EXPECT_EQ(result.matches.first().view.to_string(), "slideNumbers"sv);
  988. EXPECT_EQ(result.capture_group_matches.first()[0].view.to_string(), "slideNumbers"sv);
  989. EXPECT_EQ(result.capture_group_matches.first()[1].view.to_string(), "}"sv);
  990. }
  991. }