RegexParser.cpp 99 KB

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