RegexParser.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762
  1. /*
  2. * Copyright (c) 2020, Emanuel Sprung <emanuel.sprung@gmail.com>
  3. * Copyright (c) 2020-2021, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "RegexParser.h"
  8. #include "RegexDebug.h"
  9. #include <AK/String.h>
  10. #include <AK/StringBuilder.h>
  11. #include <AK/StringUtils.h>
  12. namespace regex {
  13. ALWAYS_INLINE bool Parser::set_error(Error error)
  14. {
  15. if (m_parser_state.error == Error::NoError) {
  16. m_parser_state.error = error;
  17. m_parser_state.error_token = m_parser_state.current_token;
  18. }
  19. return false; // always return false, that eases the API usage (return set_error(...)) :^)
  20. }
  21. ALWAYS_INLINE bool Parser::done() const
  22. {
  23. return match(TokenType::Eof);
  24. }
  25. ALWAYS_INLINE bool Parser::match(TokenType type) const
  26. {
  27. return m_parser_state.current_token.type() == type;
  28. }
  29. ALWAYS_INLINE bool Parser::match(char ch) const
  30. {
  31. return m_parser_state.current_token.type() == TokenType::Char && m_parser_state.current_token.value().length() == 1 && m_parser_state.current_token.value()[0] == ch;
  32. }
  33. ALWAYS_INLINE Token Parser::consume()
  34. {
  35. auto old_token = m_parser_state.current_token;
  36. m_parser_state.current_token = m_parser_state.lexer.next();
  37. return old_token;
  38. }
  39. ALWAYS_INLINE Token Parser::consume(TokenType type, Error error)
  40. {
  41. if (m_parser_state.current_token.type() != type) {
  42. set_error(error);
  43. dbgln("[PARSER] Error: Unexpected token {}. Expected: {}", m_parser_state.current_token.name(), Token::name(type));
  44. }
  45. return consume();
  46. }
  47. ALWAYS_INLINE bool Parser::consume(const String& str)
  48. {
  49. size_t potentially_go_back { 1 };
  50. for (auto ch : str) {
  51. if (match(TokenType::Char)) {
  52. if (m_parser_state.current_token.value()[0] != ch) {
  53. m_parser_state.lexer.back(potentially_go_back);
  54. m_parser_state.current_token = m_parser_state.lexer.next();
  55. return false;
  56. }
  57. } else {
  58. m_parser_state.lexer.back(potentially_go_back);
  59. m_parser_state.current_token = m_parser_state.lexer.next();
  60. return false;
  61. }
  62. consume(TokenType::Char, Error::NoError);
  63. ++potentially_go_back;
  64. }
  65. return true;
  66. }
  67. ALWAYS_INLINE bool Parser::try_skip(StringView str)
  68. {
  69. if (str.starts_with(m_parser_state.current_token.value()))
  70. str = str.substring_view(m_parser_state.current_token.value().length(), str.length() - m_parser_state.current_token.value().length());
  71. else
  72. return false;
  73. size_t potentially_go_back { 0 };
  74. for (auto ch : str) {
  75. if (!m_parser_state.lexer.try_skip(ch)) {
  76. m_parser_state.lexer.back(potentially_go_back);
  77. return false;
  78. }
  79. ++potentially_go_back;
  80. }
  81. m_parser_state.current_token = m_parser_state.lexer.next();
  82. return true;
  83. }
  84. ALWAYS_INLINE bool Parser::lookahead_any(StringView str)
  85. {
  86. for (auto ch : str) {
  87. if (match(ch))
  88. return true;
  89. }
  90. return false;
  91. }
  92. ALWAYS_INLINE char Parser::skip()
  93. {
  94. char ch;
  95. if (m_parser_state.current_token.value().length() == 1) {
  96. ch = m_parser_state.current_token.value()[0];
  97. } else {
  98. m_parser_state.lexer.back(m_parser_state.current_token.value().length());
  99. ch = m_parser_state.lexer.skip();
  100. }
  101. m_parser_state.current_token = m_parser_state.lexer.next();
  102. return ch;
  103. }
  104. ALWAYS_INLINE void Parser::back(size_t count)
  105. {
  106. m_parser_state.lexer.back(count);
  107. m_parser_state.current_token = m_parser_state.lexer.next();
  108. }
  109. ALWAYS_INLINE void Parser::reset()
  110. {
  111. m_parser_state.bytecode.clear();
  112. m_parser_state.lexer.reset();
  113. m_parser_state.current_token = m_parser_state.lexer.next();
  114. m_parser_state.error = Error::NoError;
  115. m_parser_state.error_token = { TokenType::Eof, 0, StringView(nullptr) };
  116. m_parser_state.capture_group_minimum_lengths.clear();
  117. m_parser_state.capture_groups_count = 0;
  118. m_parser_state.named_capture_groups_count = 0;
  119. m_parser_state.named_capture_group_minimum_lengths.clear();
  120. m_parser_state.named_capture_groups.clear();
  121. }
  122. Parser::Result Parser::parse(Optional<AllOptions> regex_options)
  123. {
  124. reset();
  125. if (regex_options.has_value())
  126. m_parser_state.regex_options = regex_options.value();
  127. if (parse_internal(m_parser_state.bytecode, m_parser_state.match_length_minimum))
  128. consume(TokenType::Eof, Error::InvalidPattern);
  129. else
  130. set_error(Error::InvalidPattern);
  131. dbgln_if(REGEX_DEBUG, "[PARSER] Produced bytecode with {} entries (opcodes + arguments)", m_parser_state.bytecode.size());
  132. return {
  133. move(m_parser_state.bytecode),
  134. move(m_parser_state.capture_groups_count),
  135. move(m_parser_state.named_capture_groups_count),
  136. move(m_parser_state.match_length_minimum),
  137. move(m_parser_state.error),
  138. move(m_parser_state.error_token)
  139. };
  140. }
  141. ALWAYS_INLINE bool Parser::match_ordinary_characters()
  142. {
  143. // NOTE: This method must not be called during bracket and repetition parsing!
  144. // FIXME: Add assertion for that?
  145. auto type = m_parser_state.current_token.type();
  146. return (type == TokenType::Char
  147. || type == TokenType::Comma
  148. || type == TokenType::Slash
  149. || type == TokenType::EqualSign
  150. || type == TokenType::HyphenMinus
  151. || type == TokenType::Colon);
  152. }
  153. // =============================
  154. // PosixExtended Parser
  155. // =============================
  156. bool PosixExtendedParser::parse_internal(ByteCode& stack, size_t& match_length_minimum)
  157. {
  158. return parse_root(stack, match_length_minimum);
  159. }
  160. ALWAYS_INLINE bool PosixExtendedParser::match_repetition_symbol()
  161. {
  162. auto type = m_parser_state.current_token.type();
  163. return (type == TokenType::Asterisk
  164. || type == TokenType::Plus
  165. || type == TokenType::Questionmark
  166. || type == TokenType::LeftCurly);
  167. }
  168. ALWAYS_INLINE bool PosixExtendedParser::parse_repetition_symbol(ByteCode& bytecode_to_repeat, size_t& match_length_minimum)
  169. {
  170. if (match(TokenType::LeftCurly)) {
  171. consume();
  172. StringBuilder number_builder;
  173. while (match(TokenType::Char)) {
  174. number_builder.append(consume().value());
  175. }
  176. auto maybe_minimum = number_builder.build().to_uint();
  177. if (!maybe_minimum.has_value())
  178. return set_error(Error::InvalidBraceContent);
  179. auto minimum = maybe_minimum.value();
  180. match_length_minimum *= minimum;
  181. if (match(TokenType::Comma)) {
  182. consume();
  183. } else {
  184. ByteCode bytecode;
  185. bytecode.insert_bytecode_repetition_n(bytecode_to_repeat, minimum);
  186. bytecode_to_repeat = move(bytecode);
  187. consume(TokenType::RightCurly, Error::MismatchingBrace);
  188. return !has_error();
  189. }
  190. Optional<size_t> maybe_maximum {};
  191. number_builder.clear();
  192. while (match(TokenType::Char)) {
  193. number_builder.append(consume().value());
  194. }
  195. if (!number_builder.is_empty()) {
  196. auto value = number_builder.build().to_uint();
  197. if (!value.has_value() || minimum > value.value())
  198. return set_error(Error::InvalidBraceContent);
  199. maybe_maximum = value.value();
  200. }
  201. bytecode_to_repeat.insert_bytecode_repetition_min_max(bytecode_to_repeat, minimum, maybe_maximum);
  202. consume(TokenType::RightCurly, Error::MismatchingBrace);
  203. return !has_error();
  204. } else if (match(TokenType::Plus)) {
  205. consume();
  206. bool nongreedy = match(TokenType::Questionmark);
  207. if (nongreedy)
  208. consume();
  209. // Note: don't touch match_length_minimum, it's already correct
  210. bytecode_to_repeat.insert_bytecode_repetition_min_one(bytecode_to_repeat, !nongreedy);
  211. return !has_error();
  212. } else if (match(TokenType::Asterisk)) {
  213. consume();
  214. match_length_minimum = 0;
  215. bool nongreedy = match(TokenType::Questionmark);
  216. if (nongreedy)
  217. consume();
  218. bytecode_to_repeat.insert_bytecode_repetition_any(bytecode_to_repeat, !nongreedy);
  219. return !has_error();
  220. } else if (match(TokenType::Questionmark)) {
  221. consume();
  222. match_length_minimum = 0;
  223. bool nongreedy = match(TokenType::Questionmark);
  224. if (nongreedy)
  225. consume();
  226. bytecode_to_repeat.insert_bytecode_repetition_zero_or_one(bytecode_to_repeat, !nongreedy);
  227. return !has_error();
  228. }
  229. return false;
  230. }
  231. ALWAYS_INLINE bool PosixExtendedParser::parse_bracket_expression(ByteCode& stack, size_t& match_length_minimum)
  232. {
  233. Vector<CompareTypeAndValuePair> values;
  234. for (;;) {
  235. if (match(TokenType::HyphenMinus)) {
  236. consume();
  237. if (values.is_empty() || (values.size() == 1 && values.last().type == CharacterCompareType::Inverse)) {
  238. // first in the bracket expression
  239. values.append({ CharacterCompareType::Char, (ByteCodeValueType)'-' });
  240. } else if (match(TokenType::RightBracket)) {
  241. // Last in the bracket expression
  242. values.append({ CharacterCompareType::Char, (ByteCodeValueType)'-' });
  243. } else if (values.last().type == CharacterCompareType::Char) {
  244. values.append({ CharacterCompareType::RangeExpressionDummy, 0 });
  245. if (match(TokenType::HyphenMinus)) {
  246. consume();
  247. // Valid range, add ordinary character
  248. values.append({ CharacterCompareType::Char, (ByteCodeValueType)'-' });
  249. }
  250. } else {
  251. return set_error(Error::InvalidRange);
  252. }
  253. } else if (match(TokenType::Circumflex)) {
  254. auto t = consume();
  255. if (values.is_empty())
  256. values.append({ CharacterCompareType::Inverse, 0 });
  257. else
  258. values.append({ CharacterCompareType::Char, (ByteCodeValueType)*t.value().characters_without_null_termination() });
  259. } else if (match(TokenType::LeftBracket)) {
  260. consume();
  261. if (match(TokenType::Period)) {
  262. consume();
  263. // FIXME: Parse collating element, this is needed when we have locale support
  264. // This could have impact on length parameter, I guess.
  265. VERIFY_NOT_REACHED();
  266. consume(TokenType::Period, Error::InvalidCollationElement);
  267. consume(TokenType::RightBracket, Error::MismatchingBracket);
  268. } else if (match(TokenType::EqualSign)) {
  269. consume();
  270. // FIXME: Parse collating element, this is needed when we have locale support
  271. // This could have impact on length parameter, I guess.
  272. VERIFY_NOT_REACHED();
  273. consume(TokenType::EqualSign, Error::InvalidCollationElement);
  274. consume(TokenType::RightBracket, Error::MismatchingBracket);
  275. } else if (match(TokenType::Colon)) {
  276. consume();
  277. CharClass ch_class;
  278. // parse character class
  279. if (match(TokenType::Char)) {
  280. if (consume("alnum"))
  281. ch_class = CharClass::Alnum;
  282. else if (consume("alpha"))
  283. ch_class = CharClass::Alpha;
  284. else if (consume("blank"))
  285. ch_class = CharClass::Blank;
  286. else if (consume("cntrl"))
  287. ch_class = CharClass::Cntrl;
  288. else if (consume("digit"))
  289. ch_class = CharClass::Digit;
  290. else if (consume("graph"))
  291. ch_class = CharClass::Graph;
  292. else if (consume("lower"))
  293. ch_class = CharClass::Lower;
  294. else if (consume("print"))
  295. ch_class = CharClass::Print;
  296. else if (consume("punct"))
  297. ch_class = CharClass::Punct;
  298. else if (consume("space"))
  299. ch_class = CharClass::Space;
  300. else if (consume("upper"))
  301. ch_class = CharClass::Upper;
  302. else if (consume("xdigit"))
  303. ch_class = CharClass::Xdigit;
  304. else
  305. return set_error(Error::InvalidCharacterClass);
  306. values.append({ CharacterCompareType::CharClass, (ByteCodeValueType)ch_class });
  307. } else
  308. return set_error(Error::InvalidCharacterClass);
  309. // FIXME: we do not support locale specific character classes until locales are implemented
  310. consume(TokenType::Colon, Error::InvalidCharacterClass);
  311. consume(TokenType::RightBracket, Error::MismatchingBracket);
  312. } else {
  313. return set_error(Error::MismatchingBracket);
  314. }
  315. } else if (match(TokenType::RightBracket)) {
  316. if (values.is_empty() || (values.size() == 1 && values.last().type == CharacterCompareType::Inverse)) {
  317. // handle bracket as ordinary character
  318. values.append({ CharacterCompareType::Char, (ByteCodeValueType)*consume().value().characters_without_null_termination() });
  319. } else {
  320. // closing bracket expression
  321. break;
  322. }
  323. } else {
  324. values.append({ CharacterCompareType::Char, (ByteCodeValueType)skip() });
  325. }
  326. // check if range expression has to be completed...
  327. if (values.size() >= 3 && values.at(values.size() - 2).type == CharacterCompareType::RangeExpressionDummy) {
  328. if (values.last().type != CharacterCompareType::Char)
  329. return set_error(Error::InvalidRange);
  330. auto value2 = values.take_last();
  331. values.take_last(); // RangeExpressionDummy
  332. auto value1 = values.take_last();
  333. values.append({ CharacterCompareType::CharRange, static_cast<ByteCodeValueType>(CharRange { (u32)value1.value, (u32)value2.value }) });
  334. }
  335. }
  336. if (values.size())
  337. match_length_minimum = 1;
  338. if (values.first().type == CharacterCompareType::Inverse)
  339. match_length_minimum = 0;
  340. stack.insert_bytecode_compare_values(move(values));
  341. return !has_error();
  342. }
  343. ALWAYS_INLINE bool PosixExtendedParser::parse_sub_expression(ByteCode& stack, size_t& match_length_minimum)
  344. {
  345. ByteCode bytecode;
  346. size_t length = 0;
  347. bool should_parse_repetition_symbol { false };
  348. for (;;) {
  349. if (match_ordinary_characters()) {
  350. Token start_token = m_parser_state.current_token;
  351. Token last_token = m_parser_state.current_token;
  352. for (;;) {
  353. if (!match_ordinary_characters())
  354. break;
  355. ++length;
  356. last_token = consume();
  357. }
  358. if (length > 1) {
  359. // last character is inserted into 'bytecode' for duplication symbol handling
  360. auto new_length = length - ((match_repetition_symbol() && length > 1) ? 1 : 0);
  361. stack.insert_bytecode_compare_string({ start_token.value().characters_without_null_termination(), new_length });
  362. }
  363. if ((match_repetition_symbol() && length > 1) || length == 1) // Create own compare opcode for last character before duplication symbol
  364. bytecode.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)last_token.value().characters_without_null_termination()[0] } });
  365. should_parse_repetition_symbol = true;
  366. break;
  367. }
  368. if (match_repetition_symbol())
  369. return set_error(Error::InvalidRepetitionMarker);
  370. if (match(TokenType::Period)) {
  371. length = 1;
  372. consume();
  373. bytecode.insert_bytecode_compare_values({ { CharacterCompareType::AnyChar, 0 } });
  374. should_parse_repetition_symbol = true;
  375. break;
  376. }
  377. if (match(TokenType::EscapeSequence)) {
  378. length = 1;
  379. Token t = consume();
  380. dbgln_if(REGEX_DEBUG, "[PARSER] EscapeSequence with substring {}", t.value());
  381. bytecode.insert_bytecode_compare_values({ { CharacterCompareType::Char, (u32)t.value().characters_without_null_termination()[1] } });
  382. should_parse_repetition_symbol = true;
  383. break;
  384. }
  385. if (match(TokenType::LeftBracket)) {
  386. consume();
  387. ByteCode sub_ops;
  388. if (!parse_bracket_expression(sub_ops, length) || !sub_ops.size())
  389. return set_error(Error::InvalidBracketContent);
  390. bytecode.append(move(sub_ops));
  391. consume(TokenType::RightBracket, Error::MismatchingBracket);
  392. should_parse_repetition_symbol = true;
  393. break;
  394. }
  395. if (match(TokenType::RightBracket)) {
  396. return set_error(Error::MismatchingBracket);
  397. }
  398. if (match(TokenType::RightCurly)) {
  399. return set_error(Error::MismatchingBrace);
  400. }
  401. if (match(TokenType::Circumflex)) {
  402. consume();
  403. bytecode.empend((ByteCodeValueType)OpCodeId::CheckBegin);
  404. break;
  405. }
  406. if (match(TokenType::Dollar)) {
  407. consume();
  408. bytecode.empend((ByteCodeValueType)OpCodeId::CheckEnd);
  409. break;
  410. }
  411. if (match(TokenType::RightParen))
  412. return false;
  413. if (match(TokenType::LeftParen)) {
  414. consume();
  415. Optional<StringView> capture_group_name;
  416. bool prevent_capture_group = false;
  417. if (match(TokenType::Questionmark)) {
  418. consume();
  419. if (match(TokenType::Colon)) {
  420. consume();
  421. prevent_capture_group = true;
  422. } else if (consume("<")) { // named capturing group
  423. Token start_token = m_parser_state.current_token;
  424. Token last_token = m_parser_state.current_token;
  425. size_t capture_group_name_length = 0;
  426. for (;;) {
  427. if (!match_ordinary_characters())
  428. return set_error(Error::InvalidNameForCaptureGroup);
  429. if (match(TokenType::Char) && m_parser_state.current_token.value()[0] == '>') {
  430. consume();
  431. break;
  432. }
  433. ++capture_group_name_length;
  434. last_token = consume();
  435. }
  436. capture_group_name = StringView(start_token.value().characters_without_null_termination(), capture_group_name_length);
  437. } else if (match(TokenType::EqualSign)) { // positive lookahead
  438. consume();
  439. VERIFY_NOT_REACHED();
  440. } else if (consume("!")) { // negative lookahead
  441. VERIFY_NOT_REACHED();
  442. } else if (consume("<")) {
  443. if (match(TokenType::EqualSign)) { // positive lookbehind
  444. consume();
  445. VERIFY_NOT_REACHED();
  446. }
  447. if (consume("!")) // negative lookbehind
  448. VERIFY_NOT_REACHED();
  449. } else {
  450. return set_error(Error::InvalidRepetitionMarker);
  451. }
  452. }
  453. if (!(m_parser_state.regex_options & AllFlags::SkipSubExprResults || prevent_capture_group)) {
  454. if (capture_group_name.has_value())
  455. bytecode.insert_bytecode_group_capture_left(capture_group_name.value());
  456. else
  457. bytecode.insert_bytecode_group_capture_left(m_parser_state.capture_groups_count);
  458. }
  459. ByteCode capture_group_bytecode;
  460. if (!parse_root(capture_group_bytecode, length))
  461. return set_error(Error::InvalidPattern);
  462. bytecode.append(move(capture_group_bytecode));
  463. consume(TokenType::RightParen, Error::MismatchingParen);
  464. if (!(m_parser_state.regex_options & AllFlags::SkipSubExprResults || prevent_capture_group)) {
  465. if (capture_group_name.has_value()) {
  466. bytecode.insert_bytecode_group_capture_right(capture_group_name.value());
  467. ++m_parser_state.named_capture_groups_count;
  468. } else {
  469. bytecode.insert_bytecode_group_capture_right(m_parser_state.capture_groups_count);
  470. ++m_parser_state.capture_groups_count;
  471. }
  472. }
  473. should_parse_repetition_symbol = true;
  474. break;
  475. }
  476. return false;
  477. }
  478. if (match_repetition_symbol()) {
  479. if (should_parse_repetition_symbol)
  480. parse_repetition_symbol(bytecode, length);
  481. else
  482. return set_error(Error::InvalidRepetitionMarker);
  483. }
  484. stack.append(move(bytecode));
  485. match_length_minimum += length;
  486. return true;
  487. }
  488. bool PosixExtendedParser::parse_root(ByteCode& stack, size_t& match_length_minimum)
  489. {
  490. ByteCode bytecode_left;
  491. size_t match_length_minimum_left { 0 };
  492. if (match_repetition_symbol())
  493. return set_error(Error::InvalidRepetitionMarker);
  494. for (;;) {
  495. if (!parse_sub_expression(bytecode_left, match_length_minimum_left))
  496. break;
  497. if (match(TokenType::Pipe)) {
  498. consume();
  499. ByteCode bytecode_right;
  500. size_t match_length_minimum_right { 0 };
  501. if (!parse_root(bytecode_right, match_length_minimum_right) || bytecode_right.is_empty())
  502. return set_error(Error::InvalidPattern);
  503. ByteCode new_bytecode;
  504. new_bytecode.insert_bytecode_alternation(move(bytecode_left), move(bytecode_right));
  505. bytecode_left = move(new_bytecode);
  506. match_length_minimum_left = min(match_length_minimum_right, match_length_minimum_left);
  507. }
  508. }
  509. if (bytecode_left.is_empty())
  510. set_error(Error::EmptySubExpression);
  511. stack.append(move(bytecode_left));
  512. match_length_minimum = match_length_minimum_left;
  513. return !has_error();
  514. }
  515. // =============================
  516. // ECMA262 Parser
  517. // =============================
  518. bool ECMA262Parser::parse_internal(ByteCode& stack, size_t& match_length_minimum)
  519. {
  520. if (m_parser_state.regex_options.has_flag_set(AllFlags::Unicode)) {
  521. return parse_pattern(stack, match_length_minimum, true, true);
  522. } else {
  523. ByteCode new_stack;
  524. size_t new_match_length = 0;
  525. auto res = parse_pattern(new_stack, new_match_length, false, false);
  526. if (m_parser_state.named_capture_groups_count > 0) {
  527. reset();
  528. return parse_pattern(stack, match_length_minimum, false, true);
  529. }
  530. if (!res)
  531. return false;
  532. stack.append(new_stack);
  533. match_length_minimum = new_match_length;
  534. return res;
  535. }
  536. }
  537. bool ECMA262Parser::parse_pattern(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  538. {
  539. return parse_disjunction(stack, match_length_minimum, unicode, named);
  540. }
  541. bool ECMA262Parser::parse_disjunction(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  542. {
  543. ByteCode left_alternative_stack;
  544. size_t left_alternative_min_length = 0;
  545. auto alt_ok = parse_alternative(left_alternative_stack, left_alternative_min_length, unicode, named);
  546. if (!alt_ok)
  547. return false;
  548. if (!match(TokenType::Pipe)) {
  549. stack.append(left_alternative_stack);
  550. match_length_minimum = left_alternative_min_length;
  551. return alt_ok;
  552. }
  553. consume();
  554. ByteCode right_alternative_stack;
  555. size_t right_alternative_min_length = 0;
  556. auto continuation_ok = parse_disjunction(right_alternative_stack, right_alternative_min_length, unicode, named);
  557. if (!continuation_ok)
  558. return false;
  559. stack.insert_bytecode_alternation(move(left_alternative_stack), move(right_alternative_stack));
  560. match_length_minimum = min(left_alternative_min_length, right_alternative_min_length);
  561. return continuation_ok;
  562. }
  563. bool ECMA262Parser::parse_alternative(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  564. {
  565. for (;;) {
  566. if (match(TokenType::Eof))
  567. return true;
  568. if (parse_term(stack, match_length_minimum, unicode, named))
  569. continue;
  570. return !has_error();
  571. }
  572. }
  573. bool ECMA262Parser::parse_term(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  574. {
  575. if (parse_assertion(stack, match_length_minimum, unicode, named))
  576. return true;
  577. ByteCode atom_stack;
  578. size_t minimum_atom_length = 0;
  579. auto parse_with_quantifier = [&] {
  580. bool did_parse_one = false;
  581. if (m_should_use_browser_extended_grammar)
  582. did_parse_one = parse_extended_atom(atom_stack, minimum_atom_length, named);
  583. if (!did_parse_one)
  584. did_parse_one = parse_atom(atom_stack, minimum_atom_length, unicode, named);
  585. if (!did_parse_one)
  586. return false;
  587. VERIFY(did_parse_one);
  588. if (!parse_quantifier(atom_stack, minimum_atom_length, unicode, named))
  589. return false;
  590. return true;
  591. };
  592. if (!parse_with_quantifier())
  593. return false;
  594. stack.append(move(atom_stack));
  595. match_length_minimum += minimum_atom_length;
  596. return true;
  597. }
  598. bool ECMA262Parser::parse_assertion(ByteCode& stack, [[maybe_unused]] size_t& match_length_minimum, bool unicode, bool named)
  599. {
  600. if (match(TokenType::Circumflex)) {
  601. consume();
  602. stack.empend((ByteCodeValueType)OpCodeId::CheckBegin);
  603. return true;
  604. }
  605. if (match(TokenType::Dollar)) {
  606. consume();
  607. stack.empend((ByteCodeValueType)OpCodeId::CheckEnd);
  608. return true;
  609. }
  610. if (try_skip("\\b")) {
  611. stack.insert_bytecode_check_boundary(BoundaryCheckType::Word);
  612. return true;
  613. }
  614. if (try_skip("\\B")) {
  615. stack.insert_bytecode_check_boundary(BoundaryCheckType::NonWord);
  616. return true;
  617. }
  618. if (match(TokenType::LeftParen)) {
  619. if (!try_skip("(?"))
  620. return false;
  621. if (done()) {
  622. set_error(Error::InvalidCaptureGroup);
  623. return false;
  624. }
  625. ByteCode assertion_stack;
  626. size_t length_dummy = 0;
  627. bool should_parse_forward_assertion = m_should_use_browser_extended_grammar ? unicode : true;
  628. if (should_parse_forward_assertion && try_skip("=")) {
  629. if (!parse_inner_disjunction(assertion_stack, length_dummy, unicode, named))
  630. return false;
  631. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::LookAhead);
  632. return true;
  633. }
  634. if (should_parse_forward_assertion && try_skip("!")) {
  635. if (!parse_inner_disjunction(assertion_stack, length_dummy, unicode, named))
  636. return false;
  637. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::NegatedLookAhead);
  638. return true;
  639. }
  640. if (m_should_use_browser_extended_grammar) {
  641. if (!unicode) {
  642. if (parse_quantifiable_assertion(assertion_stack, match_length_minimum, named)) {
  643. stack.append(move(assertion_stack));
  644. return true;
  645. }
  646. }
  647. }
  648. if (try_skip("<=")) {
  649. if (!parse_inner_disjunction(assertion_stack, length_dummy, unicode, named))
  650. return false;
  651. // FIXME: Somehow ensure that this assertion regexp has a fixed length.
  652. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::LookBehind, length_dummy);
  653. return true;
  654. }
  655. if (try_skip("<!")) {
  656. if (!parse_inner_disjunction(assertion_stack, length_dummy, unicode, named))
  657. return false;
  658. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::NegatedLookBehind, length_dummy);
  659. return true;
  660. }
  661. // If none of these matched, put the '(?' back.
  662. m_parser_state.lexer.back(3);
  663. m_parser_state.current_token = m_parser_state.lexer.next();
  664. return false;
  665. }
  666. return false;
  667. }
  668. bool ECMA262Parser::parse_inner_disjunction(ByteCode& bytecode_stack, size_t& length, bool unicode, bool named)
  669. {
  670. auto disjunction_ok = parse_disjunction(bytecode_stack, length, unicode, named);
  671. if (!disjunction_ok)
  672. return false;
  673. consume(TokenType::RightParen, Error::MismatchingParen);
  674. return true;
  675. }
  676. bool ECMA262Parser::parse_quantifiable_assertion(ByteCode& stack, size_t&, bool named)
  677. {
  678. VERIFY(m_should_use_browser_extended_grammar);
  679. ByteCode assertion_stack;
  680. size_t match_length_minimum = 0;
  681. if (try_skip("=")) {
  682. if (!parse_inner_disjunction(assertion_stack, match_length_minimum, false, named))
  683. return false;
  684. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::LookAhead);
  685. return true;
  686. }
  687. if (try_skip("!")) {
  688. if (!parse_inner_disjunction(assertion_stack, match_length_minimum, false, named))
  689. return false;
  690. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::NegatedLookAhead);
  691. return true;
  692. }
  693. return false;
  694. }
  695. StringView ECMA262Parser::read_digits_as_string(ReadDigitsInitialZeroState initial_zero, bool hex, int max_count)
  696. {
  697. if (!match(TokenType::Char))
  698. return {};
  699. if (initial_zero == ReadDigitsInitialZeroState::Disallow && m_parser_state.current_token.value() == "0")
  700. return {};
  701. int count = 0;
  702. size_t offset = 0;
  703. auto start_token = m_parser_state.current_token;
  704. while (match(TokenType::Char)) {
  705. auto& c = m_parser_state.current_token.value();
  706. if (max_count > 0 && count >= max_count)
  707. break;
  708. if (hex && !AK::StringUtils::convert_to_uint_from_hex(c).has_value())
  709. break;
  710. if (!hex && !c.to_uint().has_value())
  711. break;
  712. offset += consume().value().length();
  713. ++count;
  714. }
  715. return StringView { start_token.value().characters_without_null_termination(), offset };
  716. }
  717. Optional<unsigned> ECMA262Parser::read_digits(ECMA262Parser::ReadDigitsInitialZeroState initial_zero, bool hex, int max_count)
  718. {
  719. auto str = read_digits_as_string(initial_zero, hex, max_count);
  720. if (str.is_empty())
  721. return {};
  722. if (hex)
  723. return AK::StringUtils::convert_to_uint_from_hex(str);
  724. return str.to_uint();
  725. }
  726. bool ECMA262Parser::parse_quantifier(ByteCode& stack, size_t& match_length_minimum, bool, bool)
  727. {
  728. enum class Repetition {
  729. OneOrMore,
  730. ZeroOrMore,
  731. Optional,
  732. Explicit,
  733. None,
  734. } repetition_mark { Repetition::None };
  735. bool ungreedy = false;
  736. Optional<size_t> repeat_min, repeat_max;
  737. if (match(TokenType::Asterisk)) {
  738. consume();
  739. repetition_mark = Repetition::ZeroOrMore;
  740. } else if (match(TokenType::Plus)) {
  741. consume();
  742. repetition_mark = Repetition::OneOrMore;
  743. } else if (match(TokenType::Questionmark)) {
  744. consume();
  745. repetition_mark = Repetition::Optional;
  746. } else if (match(TokenType::LeftCurly)) {
  747. consume();
  748. auto chars_consumed = 1;
  749. repetition_mark = Repetition::Explicit;
  750. auto low_bound_string = read_digits_as_string();
  751. chars_consumed += low_bound_string.length();
  752. auto low_bound = low_bound_string.to_uint();
  753. if (!low_bound.has_value()) {
  754. back(chars_consumed + 1);
  755. return true;
  756. }
  757. repeat_min = low_bound.value();
  758. if (match(TokenType::Comma)) {
  759. consume();
  760. ++chars_consumed;
  761. auto high_bound_string = read_digits_as_string();
  762. auto high_bound = high_bound_string.to_uint();
  763. if (high_bound.has_value()) {
  764. repeat_max = high_bound.value();
  765. chars_consumed += high_bound_string.length();
  766. }
  767. } else {
  768. repeat_max = repeat_min;
  769. }
  770. if (!match(TokenType::RightCurly)) {
  771. back(chars_consumed + 1);
  772. return true;
  773. }
  774. consume();
  775. ++chars_consumed;
  776. if (repeat_max.has_value()) {
  777. if (repeat_min.value() > repeat_max.value())
  778. set_error(Error::InvalidBraceContent);
  779. }
  780. } else {
  781. return true;
  782. }
  783. if (match(TokenType::Questionmark)) {
  784. consume();
  785. ungreedy = true;
  786. }
  787. ByteCode new_bytecode;
  788. switch (repetition_mark) {
  789. case Repetition::OneOrMore:
  790. new_bytecode.insert_bytecode_repetition_min_one(stack, !ungreedy);
  791. break;
  792. case Repetition::ZeroOrMore:
  793. new_bytecode.insert_bytecode_repetition_any(stack, !ungreedy);
  794. match_length_minimum = 0;
  795. break;
  796. case Repetition::Optional:
  797. new_bytecode.insert_bytecode_repetition_zero_or_one(stack, !ungreedy);
  798. match_length_minimum = 0;
  799. break;
  800. case Repetition::Explicit:
  801. new_bytecode.insert_bytecode_repetition_min_max(stack, repeat_min.value(), repeat_max, !ungreedy);
  802. match_length_minimum *= repeat_min.value();
  803. break;
  804. case Repetition::None:
  805. VERIFY_NOT_REACHED();
  806. }
  807. return true;
  808. }
  809. bool ECMA262Parser::parse_atom(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  810. {
  811. if (match(TokenType::EscapeSequence)) {
  812. // Also part of AtomEscape.
  813. auto token = consume();
  814. match_length_minimum += 1;
  815. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)token.value()[1] } });
  816. return true;
  817. }
  818. if (try_skip("\\")) {
  819. // AtomEscape.
  820. return parse_atom_escape(stack, match_length_minimum, unicode, named);
  821. }
  822. if (match(TokenType::LeftBracket)) {
  823. // Character class.
  824. return parse_character_class(stack, match_length_minimum, unicode && !m_should_use_browser_extended_grammar, named);
  825. }
  826. if (match(TokenType::LeftParen)) {
  827. // Non-capturing group, or a capture group.
  828. return parse_capture_group(stack, match_length_minimum, unicode && !m_should_use_browser_extended_grammar, named);
  829. }
  830. if (match(TokenType::Period)) {
  831. consume();
  832. match_length_minimum += 1;
  833. stack.insert_bytecode_compare_values({ { CharacterCompareType::AnyChar, 0 } });
  834. return true;
  835. }
  836. if (match(TokenType::Circumflex) || match(TokenType::Dollar) || match(TokenType::RightParen)
  837. || match(TokenType::Pipe) || match(TokenType::Plus) || match(TokenType::Asterisk)
  838. || match(TokenType::Questionmark)) {
  839. return false;
  840. }
  841. if (match(TokenType::RightBracket) || match(TokenType::RightCurly) || match(TokenType::LeftCurly)) {
  842. if (m_should_use_browser_extended_grammar) {
  843. auto token = consume();
  844. match_length_minimum += 1;
  845. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)token.value()[0] } });
  846. return true;
  847. } else {
  848. return false;
  849. }
  850. }
  851. if (match_ordinary_characters()) {
  852. auto token = consume().value();
  853. match_length_minimum += 1;
  854. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)token[0] } });
  855. return true;
  856. }
  857. set_error(Error::InvalidPattern);
  858. return false;
  859. }
  860. bool ECMA262Parser::parse_extended_atom(ByteCode&, size_t&, bool)
  861. {
  862. // Note: This includes only rules *not* present in parse_atom()
  863. VERIFY(m_should_use_browser_extended_grammar);
  864. if (parse_invalid_braced_quantifier())
  865. return true; // FAIL FAIL FAIL
  866. return false;
  867. }
  868. bool ECMA262Parser::parse_invalid_braced_quantifier()
  869. {
  870. if (!match(TokenType::LeftCurly))
  871. return false;
  872. consume();
  873. size_t chars_consumed = 1;
  874. auto low_bound = read_digits_as_string();
  875. StringView high_bound;
  876. if (low_bound.is_empty()) {
  877. back(chars_consumed + 1);
  878. return false;
  879. }
  880. chars_consumed += low_bound.length();
  881. if (match(TokenType::Comma)) {
  882. consume();
  883. ++chars_consumed;
  884. high_bound = read_digits_as_string();
  885. chars_consumed += high_bound.length();
  886. }
  887. if (!match(TokenType::RightCurly)) {
  888. back(chars_consumed + 1);
  889. return false;
  890. }
  891. consume();
  892. set_error(Error::InvalidPattern);
  893. return true;
  894. }
  895. bool ECMA262Parser::parse_atom_escape(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  896. {
  897. if (auto escape_str = read_digits_as_string(ReadDigitsInitialZeroState::Disallow); !escape_str.is_empty()) {
  898. if (auto escape = escape_str.to_uint(); escape.has_value()) {
  899. // See if this is a "back"-reference (we've already parsed the group it refers to)
  900. auto maybe_length = m_parser_state.capture_group_minimum_lengths.get(escape.value());
  901. if (maybe_length.has_value()) {
  902. match_length_minimum += maybe_length.value();
  903. stack.insert_bytecode_compare_values({ { CharacterCompareType::Reference, (ByteCodeValueType)escape.value() } });
  904. return true;
  905. }
  906. // It's not a pattern seen before, so we have to see if it's a valid reference to a future group.
  907. if (escape.value() <= ensure_total_number_of_capturing_parenthesis()) {
  908. // This refers to a future group, and it will _always_ be matching an empty string
  909. // So just match nothing and move on.
  910. return true;
  911. }
  912. if (!m_should_use_browser_extended_grammar) {
  913. set_error(Error::InvalidNumber);
  914. return false;
  915. }
  916. }
  917. // If not, put the characters back.
  918. back(escape_str.length());
  919. }
  920. // CharacterEscape > ControlEscape
  921. if (try_skip("f")) {
  922. match_length_minimum += 1;
  923. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\f' } });
  924. return true;
  925. }
  926. if (try_skip("n")) {
  927. match_length_minimum += 1;
  928. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\n' } });
  929. return true;
  930. }
  931. if (try_skip("r")) {
  932. match_length_minimum += 1;
  933. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\r' } });
  934. return true;
  935. }
  936. if (try_skip("t")) {
  937. match_length_minimum += 1;
  938. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\t' } });
  939. return true;
  940. }
  941. if (try_skip("v")) {
  942. match_length_minimum += 1;
  943. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\v' } });
  944. return true;
  945. }
  946. // CharacterEscape > ControlLetter
  947. if (try_skip("c")) {
  948. for (auto c = 'A'; c <= 'z'; ++c) {
  949. if (try_skip({ &c, 1 })) {
  950. match_length_minimum += 1;
  951. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)(c % 32) } });
  952. return true;
  953. }
  954. }
  955. if (m_should_use_browser_extended_grammar) {
  956. back(2);
  957. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\\' } });
  958. match_length_minimum += 1;
  959. return true;
  960. }
  961. if (unicode) {
  962. set_error(Error::InvalidPattern);
  963. return false;
  964. }
  965. // Allow '\c' in non-unicode mode, just matches 'c'.
  966. match_length_minimum += 1;
  967. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'c' } });
  968. return true;
  969. }
  970. // LegacyOctalEscapeSequence
  971. if (m_should_use_browser_extended_grammar) {
  972. if (!unicode) {
  973. if (auto escape = parse_legacy_octal_escape(); escape.has_value()) {
  974. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)escape.value() } });
  975. match_length_minimum += 1;
  976. return true;
  977. }
  978. }
  979. }
  980. // '\0'
  981. if (try_skip("0")) {
  982. match_length_minimum += 1;
  983. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)0 } });
  984. return true;
  985. }
  986. // HexEscape
  987. if (try_skip("x")) {
  988. if (auto hex_escape = read_digits(ReadDigitsInitialZeroState::Allow, true, 2); hex_escape.has_value()) {
  989. match_length_minimum += 1;
  990. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)hex_escape.value() } });
  991. return true;
  992. } else if (!unicode) {
  993. // '\x' is allowed in non-unicode mode, just matches 'x'.
  994. match_length_minimum += 1;
  995. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'x' } });
  996. return true;
  997. } else {
  998. set_error(Error::InvalidPattern);
  999. return false;
  1000. }
  1001. }
  1002. if (try_skip("u")) {
  1003. if (auto code_point = read_digits(ReadDigitsInitialZeroState::Allow, true, 4); code_point.has_value()) {
  1004. // FIXME: The minimum length depends on the mode - should be utf8-length in u8 mode.
  1005. match_length_minimum += 1;
  1006. StringBuilder builder;
  1007. builder.append_code_point(code_point.value());
  1008. // FIXME: This isn't actually correct for ECMAScript.
  1009. auto u8_encoded = builder.string_view();
  1010. stack.insert_bytecode_compare_string(u8_encoded);
  1011. return true;
  1012. } else if (!unicode) {
  1013. // '\u' is allowed in non-unicode mode, just matches 'u'.
  1014. match_length_minimum += 1;
  1015. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'u' } });
  1016. return true;
  1017. } else {
  1018. set_error(Error::InvalidPattern);
  1019. return false;
  1020. }
  1021. }
  1022. // IdentityEscape
  1023. auto source_characters = m_should_use_browser_extended_grammar ? "^$\\.*+?()[|"sv : "^$\\.*+?()[]{}|"sv;
  1024. for (auto ch : source_characters) {
  1025. if (try_skip({ &ch, 1 })) {
  1026. match_length_minimum += 1;
  1027. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)ch } });
  1028. return true;
  1029. }
  1030. }
  1031. if (unicode) {
  1032. if (try_skip("/")) {
  1033. match_length_minimum += 1;
  1034. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'/' } });
  1035. return true;
  1036. }
  1037. }
  1038. if (named && try_skip("k")) {
  1039. auto name = read_capture_group_specifier(true);
  1040. if (name.is_empty()) {
  1041. set_error(Error::InvalidNameForCaptureGroup);
  1042. return false;
  1043. }
  1044. auto maybe_length = m_parser_state.named_capture_group_minimum_lengths.get(name);
  1045. if (!maybe_length.has_value()) {
  1046. set_error(Error::InvalidNameForCaptureGroup);
  1047. return false;
  1048. }
  1049. match_length_minimum += maybe_length.value();
  1050. stack.insert_bytecode_compare_named_reference(name);
  1051. return true;
  1052. }
  1053. if (unicode) {
  1054. if (try_skip("p{")) {
  1055. // FIXME: Implement this path, Unicode property match.
  1056. TODO();
  1057. }
  1058. if (try_skip("P{")) {
  1059. // FIXME: Implement this path, Unicode property match.
  1060. TODO();
  1061. }
  1062. }
  1063. if (done())
  1064. return set_error(Error::InvalidTrailingEscape);
  1065. bool negate = false;
  1066. auto ch = parse_character_class_escape(negate);
  1067. if (!ch.has_value()) {
  1068. if (!unicode) {
  1069. // Allow all SourceCharacter's as escapes here.
  1070. auto token = consume();
  1071. match_length_minimum += 1;
  1072. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)token.value()[0] } });
  1073. return true;
  1074. }
  1075. set_error(Error::InvalidCharacterClass);
  1076. return false;
  1077. }
  1078. Vector<CompareTypeAndValuePair> compares;
  1079. if (negate)
  1080. compares.empend(CompareTypeAndValuePair { CharacterCompareType::Inverse, 0 });
  1081. compares.empend(CompareTypeAndValuePair { CharacterCompareType::CharClass, (ByteCodeValueType)ch.value() });
  1082. match_length_minimum += 1;
  1083. stack.insert_bytecode_compare_values(move(compares));
  1084. return true;
  1085. }
  1086. Optional<u8> ECMA262Parser::parse_legacy_octal_escape()
  1087. {
  1088. constexpr auto all_octal_digits = "01234567";
  1089. auto read_octal_digit = [&](auto start, auto end, bool should_ensure_no_following_octal_digit) -> Optional<u8> {
  1090. for (char c = '0' + start; c <= '0' + end; ++c) {
  1091. if (try_skip({ &c, 1 })) {
  1092. if (!should_ensure_no_following_octal_digit || !lookahead_any(all_octal_digits))
  1093. return c - '0';
  1094. back(2);
  1095. return {};
  1096. }
  1097. }
  1098. return {};
  1099. };
  1100. // OctalDigit(1)
  1101. if (auto digit = read_octal_digit(0, 7, true); digit.has_value()) {
  1102. return digit.value();
  1103. }
  1104. // OctalDigit(2)
  1105. if (auto left_digit = read_octal_digit(0, 3, false); left_digit.has_value()) {
  1106. if (auto right_digit = read_octal_digit(0, 7, true); right_digit.has_value()) {
  1107. return left_digit.value() * 8 + right_digit.value();
  1108. }
  1109. back(2);
  1110. }
  1111. // OctalDigit(2)
  1112. if (auto left_digit = read_octal_digit(4, 7, false); left_digit.has_value()) {
  1113. if (auto right_digit = read_octal_digit(0, 7, false); right_digit.has_value()) {
  1114. return left_digit.value() * 8 + right_digit.value();
  1115. }
  1116. back(2);
  1117. }
  1118. // OctalDigit(3)
  1119. if (auto left_digit = read_octal_digit(0, 3, false); left_digit.has_value()) {
  1120. size_t chars_consumed = 1;
  1121. if (auto mid_digit = read_octal_digit(0, 7, false); mid_digit.has_value()) {
  1122. ++chars_consumed;
  1123. if (auto right_digit = read_octal_digit(0, 7, false); right_digit.has_value()) {
  1124. return left_digit.value() * 64 + mid_digit.value() * 8 + right_digit.value();
  1125. }
  1126. }
  1127. back(chars_consumed);
  1128. }
  1129. return {};
  1130. }
  1131. Optional<CharClass> ECMA262Parser::parse_character_class_escape(bool& negate, bool expect_backslash)
  1132. {
  1133. if (expect_backslash && !try_skip("\\"))
  1134. return {};
  1135. // CharacterClassEscape
  1136. CharClass ch_class;
  1137. if (try_skip("d")) {
  1138. ch_class = CharClass::Digit;
  1139. } else if (try_skip("D")) {
  1140. ch_class = CharClass::Digit;
  1141. negate = true;
  1142. } else if (try_skip("s")) {
  1143. ch_class = CharClass::Space;
  1144. } else if (try_skip("S")) {
  1145. ch_class = CharClass::Space;
  1146. negate = true;
  1147. } else if (try_skip("w")) {
  1148. ch_class = CharClass::Word;
  1149. } else if (try_skip("W")) {
  1150. ch_class = CharClass::Word;
  1151. negate = true;
  1152. } else {
  1153. return {};
  1154. }
  1155. return ch_class;
  1156. }
  1157. bool ECMA262Parser::parse_character_class(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool)
  1158. {
  1159. consume(TokenType::LeftBracket, Error::InvalidPattern);
  1160. Vector<CompareTypeAndValuePair> compares;
  1161. if (match(TokenType::Circumflex)) {
  1162. // Negated charclass
  1163. consume();
  1164. compares.empend(CompareTypeAndValuePair { CharacterCompareType::Inverse, 0 });
  1165. }
  1166. if (match(TokenType::RightBracket)) {
  1167. consume();
  1168. // Should only have at most an 'Inverse'
  1169. VERIFY(compares.size() <= 1);
  1170. stack.insert_bytecode_compare_values(move(compares));
  1171. return true;
  1172. }
  1173. if (!parse_nonempty_class_ranges(compares, unicode))
  1174. return false;
  1175. match_length_minimum += 1;
  1176. stack.insert_bytecode_compare_values(move(compares));
  1177. return true;
  1178. }
  1179. struct CharClassRangeElement {
  1180. union {
  1181. CharClass character_class;
  1182. u32 code_point { 0 };
  1183. };
  1184. bool is_negated { false };
  1185. bool is_character_class { false };
  1186. };
  1187. bool ECMA262Parser::parse_nonempty_class_ranges(Vector<CompareTypeAndValuePair>& ranges, bool unicode)
  1188. {
  1189. auto read_class_atom_no_dash = [&]() -> Optional<CharClassRangeElement> {
  1190. if (match(TokenType::EscapeSequence)) {
  1191. auto token = consume().value();
  1192. return { { .code_point = (u32)token[1], .is_character_class = false } };
  1193. }
  1194. if (try_skip("\\")) {
  1195. if (done()) {
  1196. set_error(Error::InvalidTrailingEscape);
  1197. return {};
  1198. }
  1199. if (try_skip("f"))
  1200. return { { .code_point = '\f', .is_character_class = false } };
  1201. if (try_skip("n"))
  1202. return { { .code_point = '\n', .is_character_class = false } };
  1203. if (try_skip("r"))
  1204. return { { .code_point = '\r', .is_character_class = false } };
  1205. if (try_skip("t"))
  1206. return { { .code_point = '\t', .is_character_class = false } };
  1207. if (try_skip("v"))
  1208. return { { .code_point = '\v', .is_character_class = false } };
  1209. if (try_skip("b"))
  1210. return { { .code_point = '\b', .is_character_class = false } };
  1211. if (try_skip("/"))
  1212. return { { .code_point = '/', .is_character_class = false } };
  1213. // CharacterEscape > ControlLetter
  1214. if (try_skip("c")) {
  1215. for (auto c = 'A'; c <= 'z'; ++c) {
  1216. if (try_skip({ &c, 1 }))
  1217. return { { .code_point = (u32)(c % 32), .is_character_class = false } };
  1218. }
  1219. if (m_should_use_browser_extended_grammar) {
  1220. for (auto c = '0'; c <= '9'; ++c) {
  1221. if (try_skip({ &c, 1 }))
  1222. return { { .code_point = (u32)(c % 32), .is_character_class = false } };
  1223. }
  1224. if (try_skip("_"))
  1225. return { { .code_point = (u32)('_' % 32), .is_character_class = false } };
  1226. back(2);
  1227. return { { .code_point = '\\', .is_character_class = false } };
  1228. }
  1229. }
  1230. // '\0'
  1231. if (try_skip("0"))
  1232. return { { .code_point = 0, .is_character_class = false } };
  1233. // HexEscape
  1234. if (try_skip("x")) {
  1235. if (auto hex_escape = read_digits(ReadDigitsInitialZeroState::Allow, true, 2); hex_escape.has_value()) {
  1236. return { { .code_point = hex_escape.value(), .is_character_class = false } };
  1237. } else if (!unicode) {
  1238. // '\x' is allowed in non-unicode mode, just matches 'x'.
  1239. return { { .code_point = 'x', .is_character_class = false } };
  1240. } else {
  1241. set_error(Error::InvalidPattern);
  1242. return {};
  1243. }
  1244. }
  1245. if (try_skip("u")) {
  1246. if (auto code_point = read_digits(ReadDigitsInitialZeroState::Allow, true, 4); code_point.has_value()) {
  1247. // FIXME: While codepoint ranges are supported, codepoint matches as "Char" are not!
  1248. return { { .code_point = code_point.value(), .is_character_class = false } };
  1249. } else if (!unicode) {
  1250. // '\u' is allowed in non-unicode mode, just matches 'u'.
  1251. return { { .code_point = 'u', .is_character_class = false } };
  1252. } else {
  1253. set_error(Error::InvalidPattern);
  1254. return {};
  1255. }
  1256. }
  1257. if (unicode) {
  1258. if (try_skip("-"))
  1259. return { { .code_point = '-', .is_character_class = false } };
  1260. }
  1261. if (try_skip("p{") || try_skip("P{")) {
  1262. // FIXME: Implement these; unicode properties.
  1263. TODO();
  1264. }
  1265. if (try_skip("d"))
  1266. return { { .character_class = CharClass::Digit, .is_character_class = true } };
  1267. if (try_skip("s"))
  1268. return { { .character_class = CharClass::Space, .is_character_class = true } };
  1269. if (try_skip("w"))
  1270. return { { .character_class = CharClass::Word, .is_character_class = true } };
  1271. if (try_skip("D"))
  1272. return { { .character_class = CharClass::Digit, .is_negated = true, .is_character_class = true } };
  1273. if (try_skip("S"))
  1274. return { { .character_class = CharClass::Space, .is_negated = true, .is_character_class = true } };
  1275. if (try_skip("W"))
  1276. return { { .character_class = CharClass::Word, .is_negated = true, .is_character_class = true } };
  1277. if (!unicode) {
  1278. // Any unrecognised escape is allowed in non-unicode mode.
  1279. return { { .code_point = (u32)skip(), .is_character_class = false } };
  1280. }
  1281. }
  1282. if (match(TokenType::RightBracket) || match(TokenType::HyphenMinus))
  1283. return {};
  1284. // Allow any (other) SourceCharacter.
  1285. return { { .code_point = (u32)skip(), .is_character_class = false } };
  1286. };
  1287. auto read_class_atom = [&]() -> Optional<CharClassRangeElement> {
  1288. if (match(TokenType::HyphenMinus)) {
  1289. consume();
  1290. return { { .code_point = '-', .is_character_class = false } };
  1291. }
  1292. return read_class_atom_no_dash();
  1293. };
  1294. while (!match(TokenType::RightBracket)) {
  1295. if (match(TokenType::Eof)) {
  1296. set_error(Error::MismatchingBracket);
  1297. return false;
  1298. }
  1299. auto first_atom = read_class_atom();
  1300. if (!first_atom.has_value())
  1301. return false;
  1302. if (match(TokenType::HyphenMinus)) {
  1303. consume();
  1304. if (match(TokenType::RightBracket)) {
  1305. // Allow '-' as the last element in a charclass, even after an atom.
  1306. m_parser_state.lexer.back(2); // -]
  1307. m_parser_state.current_token = m_parser_state.lexer.next();
  1308. goto read_as_single_atom;
  1309. }
  1310. auto second_atom = read_class_atom();
  1311. if (!second_atom.has_value())
  1312. return false;
  1313. if (first_atom.value().is_character_class || second_atom.value().is_character_class) {
  1314. if (m_should_use_browser_extended_grammar) {
  1315. if (unicode) {
  1316. set_error(Error::InvalidRange);
  1317. return false;
  1318. }
  1319. // CharacterRangeOrUnion > !Unicode > CharClass
  1320. if (first_atom->is_character_class)
  1321. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::CharClass, (ByteCodeValueType)first_atom->character_class });
  1322. else
  1323. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::Char, (ByteCodeValueType)first_atom->code_point });
  1324. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::Char, (ByteCodeValueType)'-' });
  1325. if (second_atom->is_character_class)
  1326. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::CharClass, (ByteCodeValueType)second_atom->character_class });
  1327. else
  1328. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::Char, (ByteCodeValueType)second_atom->code_point });
  1329. continue;
  1330. } else {
  1331. set_error(Error::InvalidRange);
  1332. return false;
  1333. }
  1334. }
  1335. if (first_atom.value().code_point > second_atom.value().code_point) {
  1336. set_error(Error::InvalidRange);
  1337. return false;
  1338. }
  1339. VERIFY(!first_atom.value().is_negated);
  1340. VERIFY(!second_atom.value().is_negated);
  1341. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::CharRange, CharRange { first_atom.value().code_point, second_atom.value().code_point } });
  1342. continue;
  1343. }
  1344. read_as_single_atom:;
  1345. auto atom = first_atom.value();
  1346. if (atom.is_character_class) {
  1347. if (atom.is_negated)
  1348. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::TemporaryInverse, 0 });
  1349. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::CharClass, (ByteCodeValueType)first_atom.value().character_class });
  1350. } else {
  1351. VERIFY(!atom.is_negated);
  1352. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::Char, first_atom.value().code_point });
  1353. }
  1354. }
  1355. consume(TokenType::RightBracket, Error::MismatchingBracket);
  1356. return true;
  1357. }
  1358. StringView ECMA262Parser::read_capture_group_specifier(bool take_starting_angle_bracket)
  1359. {
  1360. if (take_starting_angle_bracket && !consume("<"))
  1361. return {};
  1362. auto start_token = m_parser_state.current_token;
  1363. size_t offset = 0;
  1364. while (match(TokenType::Char)) {
  1365. auto c = m_parser_state.current_token.value();
  1366. if (c == ">")
  1367. break;
  1368. offset += consume().value().length();
  1369. }
  1370. StringView name { start_token.value().characters_without_null_termination(), offset };
  1371. if (!consume(">") || name.is_empty())
  1372. set_error(Error::InvalidNameForCaptureGroup);
  1373. return name;
  1374. }
  1375. bool ECMA262Parser::parse_capture_group(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  1376. {
  1377. consume(TokenType::LeftParen, Error::InvalidPattern);
  1378. if (match(TokenType::Questionmark)) {
  1379. // Non-capturing group or group with specifier.
  1380. consume();
  1381. if (match(TokenType::Colon)) {
  1382. consume();
  1383. ByteCode noncapture_group_bytecode;
  1384. size_t length = 0;
  1385. if (!parse_disjunction(noncapture_group_bytecode, length, unicode, named))
  1386. return set_error(Error::InvalidPattern);
  1387. consume(TokenType::RightParen, Error::MismatchingParen);
  1388. stack.append(move(noncapture_group_bytecode));
  1389. match_length_minimum += length;
  1390. return true;
  1391. }
  1392. if (consume("<")) {
  1393. ++m_parser_state.named_capture_groups_count;
  1394. auto group_index = ++m_parser_state.capture_groups_count; // Named capture groups count as normal capture groups too.
  1395. auto name = read_capture_group_specifier();
  1396. if (name.is_empty()) {
  1397. set_error(Error::InvalidNameForCaptureGroup);
  1398. return false;
  1399. }
  1400. ByteCode capture_group_bytecode;
  1401. size_t length = 0;
  1402. if (!parse_disjunction(capture_group_bytecode, length, unicode, named))
  1403. return set_error(Error::InvalidPattern);
  1404. consume(TokenType::RightParen, Error::MismatchingParen);
  1405. stack.insert_bytecode_group_capture_left(name);
  1406. stack.insert_bytecode_group_capture_left(group_index);
  1407. stack.append(move(capture_group_bytecode));
  1408. stack.insert_bytecode_group_capture_right(name);
  1409. stack.insert_bytecode_group_capture_right(group_index);
  1410. match_length_minimum += length;
  1411. m_parser_state.named_capture_group_minimum_lengths.set(name, length);
  1412. m_parser_state.capture_group_minimum_lengths.set(group_index, length);
  1413. return true;
  1414. }
  1415. set_error(Error::InvalidCaptureGroup);
  1416. return false;
  1417. }
  1418. auto group_index = ++m_parser_state.capture_groups_count;
  1419. stack.insert_bytecode_group_capture_left(group_index);
  1420. ByteCode capture_group_bytecode;
  1421. size_t length = 0;
  1422. if (!parse_disjunction(capture_group_bytecode, length, unicode, named))
  1423. return set_error(Error::InvalidPattern);
  1424. stack.append(move(capture_group_bytecode));
  1425. m_parser_state.capture_group_minimum_lengths.set(group_index, length);
  1426. consume(TokenType::RightParen, Error::MismatchingParen);
  1427. stack.insert_bytecode_group_capture_right(group_index);
  1428. match_length_minimum += length;
  1429. return true;
  1430. }
  1431. size_t ECMA262Parser::ensure_total_number_of_capturing_parenthesis()
  1432. {
  1433. if (m_total_number_of_capturing_parenthesis.has_value())
  1434. return m_total_number_of_capturing_parenthesis.value();
  1435. GenericLexer lexer { m_parser_state.lexer.source() };
  1436. size_t count = 0;
  1437. while (!lexer.is_eof()) {
  1438. switch (lexer.peek()) {
  1439. case '\\':
  1440. lexer.consume(2);
  1441. continue;
  1442. case '[':
  1443. while (!lexer.is_eof()) {
  1444. if (lexer.consume_specific('\\'))
  1445. lexer.consume();
  1446. else if (lexer.consume_specific(']'))
  1447. break;
  1448. lexer.consume();
  1449. }
  1450. break;
  1451. case '(':
  1452. if (lexer.consume_specific('?')) {
  1453. // non-capturing group '(?:', lookaround '(?<='/'(?<!', or named capture '(?<'
  1454. if (!lexer.consume_specific('<'))
  1455. break;
  1456. if (lexer.next_is(is_any_of("=!")))
  1457. break;
  1458. ++count;
  1459. } else {
  1460. ++count;
  1461. }
  1462. break;
  1463. }
  1464. lexer.consume();
  1465. }
  1466. m_total_number_of_capturing_parenthesis = count;
  1467. return count;
  1468. }
  1469. }