RegexParser.cpp 99 KB

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