RegexParser.cpp 62 KB

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