RegexParser.cpp 73 KB

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