RegexParser.cpp 97 KB

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