RegexParser.cpp 97 KB

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