RegexParser.cpp 61 KB

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