RegexParser.cpp 74 KB

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