RegexParser.cpp 98 KB

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