RegexParser.cpp 79 KB

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