RegexParser.cpp 84 KB

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