RegexParser.cpp 81 KB

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