RegexParser.cpp 80 KB

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