Regex.cpp 47 KB

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