RegexParser.cpp 68 KB

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