RegexParser.cpp 80 KB

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