RegexParser.cpp 80 KB

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