RegexParser.cpp 72 KB

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