RegexParser.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  1. /*
  2. * Copyright (c) 2020, Emanuel Sprung <emanuel.sprung@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "RegexParser.h"
  27. #include "RegexDebug.h"
  28. #include <AK/String.h>
  29. #include <AK/StringBuilder.h>
  30. #include <AK/StringUtils.h>
  31. namespace regex {
  32. ALWAYS_INLINE bool Parser::set_error(Error error)
  33. {
  34. if (m_parser_state.error == Error::NoError) {
  35. m_parser_state.error = error;
  36. m_parser_state.error_token = m_parser_state.current_token;
  37. }
  38. return false; // always return false, that eases the API usage (return set_error(...)) :^)
  39. }
  40. ALWAYS_INLINE bool Parser::done() const
  41. {
  42. return match(TokenType::Eof);
  43. }
  44. ALWAYS_INLINE bool Parser::match(TokenType type) const
  45. {
  46. return m_parser_state.current_token.type() == type;
  47. }
  48. ALWAYS_INLINE Token Parser::consume()
  49. {
  50. auto old_token = m_parser_state.current_token;
  51. m_parser_state.current_token = m_parser_state.lexer.next();
  52. return old_token;
  53. }
  54. ALWAYS_INLINE Token Parser::consume(TokenType type, Error error)
  55. {
  56. if (m_parser_state.current_token.type() != type) {
  57. set_error(error);
  58. dbg() << "[PARSER] Error: Unexpected token " << m_parser_state.current_token.name() << ". Expected: " << Token::name(type);
  59. }
  60. return consume();
  61. }
  62. ALWAYS_INLINE bool Parser::consume(const String& str)
  63. {
  64. size_t potentially_go_back { 1 };
  65. for (auto ch : str) {
  66. if (match(TokenType::Char)) {
  67. if (m_parser_state.current_token.value()[0] != ch) {
  68. m_parser_state.lexer.back(potentially_go_back);
  69. m_parser_state.current_token = m_parser_state.lexer.next();
  70. return false;
  71. }
  72. } else {
  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. consume(TokenType::Char, Error::NoError);
  78. ++potentially_go_back;
  79. }
  80. return true;
  81. }
  82. ALWAYS_INLINE bool Parser::try_skip(StringView str)
  83. {
  84. if (str.starts_with(m_parser_state.current_token.value()))
  85. str = str.substring_view(m_parser_state.current_token.value().length(), str.length() - m_parser_state.current_token.value().length());
  86. else
  87. return false;
  88. size_t potentially_go_back { 0 };
  89. for (auto ch : str) {
  90. if (!m_parser_state.lexer.try_skip(ch)) {
  91. m_parser_state.lexer.back(potentially_go_back);
  92. return false;
  93. }
  94. ++potentially_go_back;
  95. }
  96. m_parser_state.current_token = m_parser_state.lexer.next();
  97. return true;
  98. }
  99. ALWAYS_INLINE char Parser::skip()
  100. {
  101. char ch;
  102. if (m_parser_state.current_token.value().length() == 1) {
  103. ch = m_parser_state.current_token.value()[0];
  104. } else {
  105. m_parser_state.lexer.back(m_parser_state.current_token.value().length());
  106. ch = m_parser_state.lexer.skip();
  107. }
  108. m_parser_state.current_token = m_parser_state.lexer.next();
  109. return ch;
  110. }
  111. ALWAYS_INLINE void Parser::reset()
  112. {
  113. m_parser_state.bytecode.clear();
  114. m_parser_state.lexer.reset();
  115. m_parser_state.current_token = m_parser_state.lexer.next();
  116. m_parser_state.error = Error::NoError;
  117. m_parser_state.error_token = { TokenType::Eof, 0, StringView(nullptr) };
  118. }
  119. Parser::Result Parser::parse(Optional<AllOptions> regex_options)
  120. {
  121. reset();
  122. if (regex_options.has_value())
  123. m_parser_state.regex_options = regex_options.value();
  124. if (parse_internal(m_parser_state.bytecode, m_parser_state.match_length_minimum))
  125. consume(TokenType::Eof, Error::InvalidPattern);
  126. else
  127. set_error(Error::InvalidPattern);
  128. #ifdef REGEX_DEBUG
  129. fprintf(stderr, "[PARSER] Produced bytecode with %lu entries (opcodes + arguments)\n", m_parser_state.bytecode.size());
  130. #endif
  131. return {
  132. move(m_parser_state.bytecode),
  133. move(m_parser_state.capture_groups_count),
  134. move(m_parser_state.named_capture_groups_count),
  135. move(m_parser_state.match_length_minimum),
  136. move(m_parser_state.error),
  137. move(m_parser_state.error_token)
  138. };
  139. }
  140. // =============================
  141. // PosixExtended Parser
  142. // =============================
  143. bool PosixExtendedParser::parse_internal(ByteCode& stack, size_t& match_length_minimum)
  144. {
  145. return parse_root(stack, match_length_minimum);
  146. }
  147. ALWAYS_INLINE bool PosixExtendedParser::match_repetition_symbol()
  148. {
  149. auto type = m_parser_state.current_token.type();
  150. return (type == TokenType::Asterisk
  151. || type == TokenType::Plus
  152. || type == TokenType::Questionmark
  153. || type == TokenType::LeftCurly);
  154. }
  155. ALWAYS_INLINE bool PosixExtendedParser::match_ordinary_characters()
  156. {
  157. // NOTE: This method must not be called during bracket and repetition parsing!
  158. // FIXME: Add assertion for that?
  159. auto type = m_parser_state.current_token.type();
  160. return (type == TokenType::Char
  161. || type == TokenType::Comma
  162. || type == TokenType::Slash
  163. || type == TokenType::EqualSign
  164. || type == TokenType::HyphenMinus
  165. || type == TokenType::Colon);
  166. }
  167. ALWAYS_INLINE bool PosixExtendedParser::parse_repetition_symbol(ByteCode& bytecode_to_repeat, size_t& match_length_minimum)
  168. {
  169. if (match(TokenType::LeftCurly)) {
  170. consume();
  171. StringBuilder number_builder;
  172. while (match(TokenType::Char)) {
  173. number_builder.append(consume().value());
  174. }
  175. auto maybe_minimum = number_builder.build().to_uint();
  176. if (!maybe_minimum.has_value())
  177. return set_error(Error::InvalidBraceContent);
  178. auto minimum = maybe_minimum.value();
  179. match_length_minimum *= minimum;
  180. if (match(TokenType::Comma)) {
  181. consume();
  182. } else {
  183. ByteCode bytecode;
  184. bytecode.insert_bytecode_repetition_n(bytecode_to_repeat, minimum);
  185. bytecode_to_repeat = move(bytecode);
  186. consume(TokenType::RightCurly, Error::MismatchingBrace);
  187. return !has_error();
  188. }
  189. Optional<size_t> maybe_maximum {};
  190. number_builder.clear();
  191. while (match(TokenType::Char)) {
  192. number_builder.append(consume().value());
  193. }
  194. if (!number_builder.is_empty()) {
  195. auto value = number_builder.build().to_uint();
  196. if (!value.has_value() || minimum > value.value())
  197. return set_error(Error::InvalidBraceContent);
  198. maybe_maximum = value.value();
  199. }
  200. bytecode_to_repeat.insert_bytecode_repetition_min_max(bytecode_to_repeat, minimum, maybe_maximum);
  201. consume(TokenType::RightCurly, Error::MismatchingBrace);
  202. return !has_error();
  203. } else if (match(TokenType::Plus)) {
  204. consume();
  205. bool nongreedy = match(TokenType::Questionmark);
  206. if (nongreedy)
  207. consume();
  208. // Note: dont touch match_length_minimum, it's already correct
  209. bytecode_to_repeat.insert_bytecode_repetition_min_one(bytecode_to_repeat, !nongreedy);
  210. return !has_error();
  211. } else if (match(TokenType::Asterisk)) {
  212. consume();
  213. match_length_minimum = 0;
  214. bool nongreedy = match(TokenType::Questionmark);
  215. if (nongreedy)
  216. consume();
  217. bytecode_to_repeat.insert_bytecode_repetition_any(bytecode_to_repeat, !nongreedy);
  218. return !has_error();
  219. } else if (match(TokenType::Questionmark)) {
  220. consume();
  221. match_length_minimum = 0;
  222. bool nongreedy = match(TokenType::Questionmark);
  223. if (nongreedy)
  224. consume();
  225. bytecode_to_repeat.insert_bytecode_repetition_zero_or_one(bytecode_to_repeat, !nongreedy);
  226. return !has_error();
  227. }
  228. return false;
  229. }
  230. ALWAYS_INLINE bool PosixExtendedParser::parse_bracket_expression(ByteCode& stack, size_t& match_length_minimum)
  231. {
  232. Vector<CompareTypeAndValuePair> values;
  233. for (;;) {
  234. if (match(TokenType::HyphenMinus)) {
  235. consume();
  236. if (values.is_empty() || (values.size() == 1 && values.last().type == CharacterCompareType::Inverse)) {
  237. // first in the bracket expression
  238. values.append({ CharacterCompareType::Char, (ByteCodeValueType)'-' });
  239. } else if (match(TokenType::RightBracket)) {
  240. // Last in the bracket expression
  241. values.append({ CharacterCompareType::Char, (ByteCodeValueType)'-' });
  242. } else if (values.last().type == CharacterCompareType::Char) {
  243. values.append({ CharacterCompareType::RangeExpressionDummy, 0 });
  244. if (match(TokenType::HyphenMinus)) {
  245. consume();
  246. // Valid range, add ordinary character
  247. values.append({ CharacterCompareType::Char, (ByteCodeValueType)'-' });
  248. }
  249. } else {
  250. return set_error(Error::InvalidRange);
  251. }
  252. } else if (match(TokenType::Char) || match(TokenType::Period) || match(TokenType::Asterisk) || match(TokenType::EscapeSequence) || match(TokenType::Plus)) {
  253. values.append({ CharacterCompareType::Char, (ByteCodeValueType)*consume().value().characters_without_null_termination() });
  254. } else if (match(TokenType::Circumflex)) {
  255. auto t = consume();
  256. if (values.is_empty())
  257. values.append({ CharacterCompareType::Inverse, 0 });
  258. else
  259. values.append({ CharacterCompareType::Char, (ByteCodeValueType)*t.value().characters_without_null_termination() });
  260. } else if (match(TokenType::LeftBracket)) {
  261. consume();
  262. if (match(TokenType::Period)) {
  263. consume();
  264. // FIXME: Parse collating element, this is needed when we have locale support
  265. // This could have impact on length parameter, I guess.
  266. ASSERT_NOT_REACHED();
  267. consume(TokenType::Period, Error::InvalidCollationElement);
  268. consume(TokenType::RightBracket, Error::MismatchingBracket);
  269. } else if (match(TokenType::EqualSign)) {
  270. consume();
  271. // FIXME: Parse collating element, this is needed when we have locale support
  272. // This could have impact on length parameter, I guess.
  273. ASSERT_NOT_REACHED();
  274. consume(TokenType::EqualSign, Error::InvalidCollationElement);
  275. consume(TokenType::RightBracket, Error::MismatchingBracket);
  276. } else if (match(TokenType::Colon)) {
  277. consume();
  278. CharClass ch_class;
  279. // parse character class
  280. if (match(TokenType::Char)) {
  281. if (consume("alnum"))
  282. ch_class = CharClass::Alnum;
  283. else if (consume("alpha"))
  284. ch_class = CharClass::Alpha;
  285. else if (consume("blank"))
  286. ch_class = CharClass::Blank;
  287. else if (consume("cntrl"))
  288. ch_class = CharClass::Cntrl;
  289. else if (consume("digit"))
  290. ch_class = CharClass::Digit;
  291. else if (consume("graph"))
  292. ch_class = CharClass::Graph;
  293. else if (consume("lower"))
  294. ch_class = CharClass::Lower;
  295. else if (consume("print"))
  296. ch_class = CharClass::Print;
  297. else if (consume("punct"))
  298. ch_class = CharClass::Punct;
  299. else if (consume("space"))
  300. ch_class = CharClass::Space;
  301. else if (consume("upper"))
  302. ch_class = CharClass::Upper;
  303. else if (consume("xdigit"))
  304. ch_class = CharClass::Xdigit;
  305. else
  306. return set_error(Error::InvalidCharacterClass);
  307. values.append({ CharacterCompareType::CharClass, (ByteCodeValueType)ch_class });
  308. } else
  309. return set_error(Error::InvalidCharacterClass);
  310. // FIXME: we do not support locale specific character classes until locales are implemented
  311. consume(TokenType::Colon, Error::InvalidCharacterClass);
  312. consume(TokenType::RightBracket, Error::MismatchingBracket);
  313. } else {
  314. return set_error(Error::MismatchingBracket);
  315. }
  316. } else if (match(TokenType::RightBracket)) {
  317. if (values.is_empty() || (values.size() == 1 && values.last().type == CharacterCompareType::Inverse)) {
  318. // handle bracket as ordinary character
  319. values.append({ CharacterCompareType::Char, (ByteCodeValueType)*consume().value().characters_without_null_termination() });
  320. } else {
  321. // closing bracket expression
  322. break;
  323. }
  324. } else
  325. // nothing matched, this is a failure, as at least the closing bracket must match...
  326. return set_error(Error::MismatchingBracket);
  327. // check if range expression has to be completed...
  328. if (values.size() >= 3 && values.at(values.size() - 2).type == CharacterCompareType::RangeExpressionDummy) {
  329. if (values.last().type != CharacterCompareType::Char)
  330. return set_error(Error::InvalidRange);
  331. auto value2 = values.take_last();
  332. values.take_last(); // RangeExpressionDummy
  333. auto value1 = values.take_last();
  334. values.append({ CharacterCompareType::CharRange, static_cast<ByteCodeValueType>(CharRange { (u32)value1.value, (u32)value2.value }) });
  335. }
  336. }
  337. if (values.size())
  338. match_length_minimum = 1;
  339. if (values.first().type == CharacterCompareType::Inverse)
  340. match_length_minimum = 0;
  341. stack.insert_bytecode_compare_values(move(values));
  342. return !has_error();
  343. }
  344. ALWAYS_INLINE bool PosixExtendedParser::parse_sub_expression(ByteCode& stack, size_t& match_length_minimum)
  345. {
  346. ByteCode bytecode;
  347. size_t length = 0;
  348. bool should_parse_repetition_symbol { false };
  349. for (;;) {
  350. if (match_ordinary_characters()) {
  351. Token start_token = m_parser_state.current_token;
  352. Token last_token = m_parser_state.current_token;
  353. for (;;) {
  354. if (!match_ordinary_characters())
  355. break;
  356. ++length;
  357. last_token = consume();
  358. }
  359. if (length > 1) {
  360. // last character is inserted into 'bytecode' for duplication symbol handling
  361. auto new_length = length - ((match_repetition_symbol() && length > 1) ? 1 : 0);
  362. stack.insert_bytecode_compare_string(start_token.value(), new_length);
  363. }
  364. if ((match_repetition_symbol() && length > 1) || length == 1) // Create own compare opcode for last character before duplication symbol
  365. bytecode.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)last_token.value().characters_without_null_termination()[0] } });
  366. should_parse_repetition_symbol = true;
  367. break;
  368. }
  369. if (match_repetition_symbol())
  370. return set_error(Error::InvalidRepetitionMarker);
  371. if (match(TokenType::Period)) {
  372. length = 1;
  373. consume();
  374. bytecode.insert_bytecode_compare_values({ { CharacterCompareType::AnyChar, 0 } });
  375. should_parse_repetition_symbol = true;
  376. break;
  377. }
  378. if (match(TokenType::EscapeSequence)) {
  379. length = 1;
  380. Token t = consume();
  381. #ifdef REGEX_DEBUG
  382. printf("[PARSER] EscapeSequence with substring %s\n", String(t.value()).characters());
  383. #endif
  384. bytecode.insert_bytecode_compare_values({ { CharacterCompareType::Char, (u32)t.value().characters_without_null_termination()[1] } });
  385. should_parse_repetition_symbol = true;
  386. break;
  387. }
  388. if (match(TokenType::LeftBracket)) {
  389. consume();
  390. ByteCode sub_ops;
  391. if (!parse_bracket_expression(sub_ops, length) || !sub_ops.size())
  392. return set_error(Error::InvalidBracketContent);
  393. bytecode.append(move(sub_ops));
  394. consume(TokenType::RightBracket, Error::MismatchingBracket);
  395. should_parse_repetition_symbol = true;
  396. break;
  397. }
  398. if (match(TokenType::RightBracket)) {
  399. return set_error(Error::MismatchingBracket);
  400. }
  401. if (match(TokenType::RightCurly)) {
  402. return set_error(Error::MismatchingBrace);
  403. }
  404. if (match(TokenType::Circumflex)) {
  405. consume();
  406. bytecode.empend((ByteCodeValueType)OpCodeId::CheckBegin);
  407. break;
  408. }
  409. if (match(TokenType::Dollar)) {
  410. consume();
  411. bytecode.empend((ByteCodeValueType)OpCodeId::CheckEnd);
  412. break;
  413. }
  414. if (match(TokenType::RightParen))
  415. return false;
  416. if (match(TokenType::LeftParen)) {
  417. consume();
  418. Optional<StringView> capture_group_name;
  419. bool prevent_capture_group = false;
  420. if (match(TokenType::Questionmark)) {
  421. consume();
  422. if (match(TokenType::Colon)) {
  423. consume();
  424. prevent_capture_group = true;
  425. } else if (consume("<")) { // named capturing group
  426. Token start_token = m_parser_state.current_token;
  427. Token last_token = m_parser_state.current_token;
  428. size_t capture_group_name_length = 0;
  429. for (;;) {
  430. if (!match_ordinary_characters())
  431. return set_error(Error::InvalidNameForCaptureGroup);
  432. if (match(TokenType::Char) && m_parser_state.current_token.value()[0] == '>') {
  433. consume();
  434. break;
  435. }
  436. ++capture_group_name_length;
  437. last_token = consume();
  438. }
  439. capture_group_name = StringView(start_token.value().characters_without_null_termination(), capture_group_name_length);
  440. } else if (match(TokenType::EqualSign)) { // positive lookahead
  441. consume();
  442. ASSERT_NOT_REACHED();
  443. } else if (consume("!")) { // negative lookahead
  444. ASSERT_NOT_REACHED();
  445. } else if (consume("<")) {
  446. if (match(TokenType::EqualSign)) { // positive lookbehind
  447. consume();
  448. ASSERT_NOT_REACHED();
  449. }
  450. if (consume("!")) // negative lookbehind
  451. ASSERT_NOT_REACHED();
  452. } else {
  453. return set_error(Error::InvalidRepetitionMarker);
  454. }
  455. }
  456. if (!(m_parser_state.regex_options & AllFlags::SkipSubExprResults || prevent_capture_group)) {
  457. if (capture_group_name.has_value())
  458. bytecode.insert_bytecode_group_capture_left(capture_group_name.value());
  459. else
  460. bytecode.insert_bytecode_group_capture_left(m_parser_state.capture_groups_count);
  461. }
  462. ByteCode capture_group_bytecode;
  463. if (!parse_root(capture_group_bytecode, length))
  464. return set_error(Error::InvalidPattern);
  465. bytecode.append(move(capture_group_bytecode));
  466. consume(TokenType::RightParen, Error::MismatchingParen);
  467. if (!(m_parser_state.regex_options & AllFlags::SkipSubExprResults || prevent_capture_group)) {
  468. if (capture_group_name.has_value()) {
  469. bytecode.insert_bytecode_group_capture_right(capture_group_name.value());
  470. ++m_parser_state.named_capture_groups_count;
  471. } else {
  472. bytecode.insert_bytecode_group_capture_right(m_parser_state.capture_groups_count);
  473. ++m_parser_state.capture_groups_count;
  474. }
  475. }
  476. should_parse_repetition_symbol = true;
  477. break;
  478. }
  479. return false;
  480. }
  481. if (match_repetition_symbol()) {
  482. if (should_parse_repetition_symbol)
  483. parse_repetition_symbol(bytecode, length);
  484. else
  485. return set_error(Error::InvalidRepetitionMarker);
  486. }
  487. stack.append(move(bytecode));
  488. match_length_minimum += length;
  489. return true;
  490. }
  491. bool PosixExtendedParser::parse_root(ByteCode& stack, size_t& match_length_minimum)
  492. {
  493. ByteCode bytecode_left;
  494. size_t match_length_minimum_left { 0 };
  495. if (match_repetition_symbol())
  496. return set_error(Error::InvalidRepetitionMarker);
  497. for (;;) {
  498. if (!parse_sub_expression(bytecode_left, match_length_minimum_left))
  499. break;
  500. if (match(TokenType::Pipe)) {
  501. consume();
  502. ByteCode bytecode_right;
  503. size_t match_length_minimum_right { 0 };
  504. if (!parse_root(bytecode_right, match_length_minimum_right) || bytecode_right.is_empty())
  505. return set_error(Error::InvalidPattern);
  506. ByteCode new_bytecode;
  507. new_bytecode.insert_bytecode_alternation(move(bytecode_left), move(bytecode_right));
  508. bytecode_left = move(new_bytecode);
  509. match_length_minimum_left = min(match_length_minimum_right, match_length_minimum_left);
  510. }
  511. }
  512. if (bytecode_left.is_empty())
  513. set_error(Error::EmptySubExpression);
  514. stack.append(move(bytecode_left));
  515. match_length_minimum = match_length_minimum_left;
  516. return !has_error();
  517. }
  518. // =============================
  519. // ECMA262 Parser
  520. // =============================
  521. bool ECMA262Parser::parse_internal(ByteCode& stack, size_t& match_length_minimum)
  522. {
  523. if (m_parser_state.regex_options.has_flag_set(AllFlags::Unicode)) {
  524. return parse_pattern(stack, match_length_minimum, true, true);
  525. } else {
  526. ByteCode new_stack;
  527. size_t new_match_length = 0;
  528. auto res = parse_pattern(new_stack, new_match_length, false, false);
  529. if (m_parser_state.named_capture_groups_count > 0) {
  530. reset();
  531. return parse_pattern(stack, match_length_minimum, false, true);
  532. }
  533. if (!res)
  534. return false;
  535. stack.append(new_stack);
  536. match_length_minimum = new_match_length;
  537. return res;
  538. }
  539. }
  540. bool ECMA262Parser::parse_pattern(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  541. {
  542. return parse_disjunction(stack, match_length_minimum, unicode, named);
  543. }
  544. bool ECMA262Parser::parse_disjunction(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  545. {
  546. ByteCode left_alternative_stack;
  547. size_t left_alternative_min_length = 0;
  548. auto alt_ok = parse_alternative(left_alternative_stack, left_alternative_min_length, unicode, named);
  549. if (!alt_ok)
  550. return false;
  551. if (!match(TokenType::Pipe)) {
  552. stack.append(left_alternative_stack);
  553. match_length_minimum = left_alternative_min_length;
  554. return alt_ok;
  555. }
  556. consume();
  557. ByteCode right_alternative_stack;
  558. size_t right_alternative_min_length = 0;
  559. auto continuation_ok = parse_disjunction(right_alternative_stack, right_alternative_min_length, unicode, named);
  560. if (!continuation_ok)
  561. return false;
  562. stack.insert_bytecode_alternation(move(left_alternative_stack), move(right_alternative_stack));
  563. match_length_minimum = min(left_alternative_min_length, right_alternative_min_length);
  564. return continuation_ok;
  565. }
  566. bool ECMA262Parser::parse_alternative(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  567. {
  568. for (;;) {
  569. if (match(TokenType::Eof))
  570. return true;
  571. if (parse_term(stack, match_length_minimum, unicode, named))
  572. continue;
  573. return !has_error();
  574. }
  575. }
  576. bool ECMA262Parser::parse_term(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  577. {
  578. if (parse_assertion(stack, match_length_minimum, unicode, named))
  579. return true;
  580. ByteCode atom_stack;
  581. size_t minimum_atom_length = 0;
  582. if (!parse_atom(atom_stack, minimum_atom_length, unicode, named))
  583. return false;
  584. if (!parse_quantifier(atom_stack, minimum_atom_length, unicode, named))
  585. return false;
  586. stack.append(move(atom_stack));
  587. match_length_minimum += minimum_atom_length;
  588. return true;
  589. }
  590. bool ECMA262Parser::parse_assertion(ByteCode& stack, [[maybe_unused]] size_t& match_length_minimum, bool unicode, bool named)
  591. {
  592. if (match(TokenType::Circumflex)) {
  593. consume();
  594. stack.empend((ByteCodeValueType)OpCodeId::CheckBegin);
  595. return true;
  596. }
  597. if (match(TokenType::Dollar)) {
  598. consume();
  599. stack.empend((ByteCodeValueType)OpCodeId::CheckEnd);
  600. return true;
  601. }
  602. if (try_skip("\\b")) {
  603. stack.insert_bytecode_check_boundary(BoundaryCheckType::Word);
  604. return true;
  605. }
  606. if (try_skip("\\B")) {
  607. stack.insert_bytecode_check_boundary(BoundaryCheckType::NonWord);
  608. return true;
  609. }
  610. if (match(TokenType::LeftParen)) {
  611. if (!try_skip("(?"))
  612. return false;
  613. ByteCode assertion_stack;
  614. size_t length_dummy = 0;
  615. auto parse_inner_disjunction = [&] {
  616. auto disjunction_ok = parse_disjunction(assertion_stack, length_dummy, unicode, named);
  617. if (!disjunction_ok)
  618. return false;
  619. consume(TokenType::RightParen, Error::MismatchingParen);
  620. return true;
  621. };
  622. if (try_skip("=")) {
  623. if (!parse_inner_disjunction())
  624. return false;
  625. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::LookAhead);
  626. return true;
  627. }
  628. if (try_skip("!")) {
  629. if (!parse_inner_disjunction())
  630. return false;
  631. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::NegatedLookAhead);
  632. return true;
  633. }
  634. if (try_skip("<=")) {
  635. if (!parse_inner_disjunction())
  636. return false;
  637. // FIXME: Somehow ensure that this assertion regexp has a fixed length.
  638. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::LookBehind, length_dummy);
  639. return true;
  640. }
  641. if (try_skip("<!")) {
  642. if (!parse_inner_disjunction())
  643. return false;
  644. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::NegatedLookBehind, length_dummy);
  645. return true;
  646. }
  647. // If none of these matched, put the '(?' back.
  648. m_parser_state.lexer.back(3);
  649. m_parser_state.current_token = m_parser_state.lexer.next();
  650. return false;
  651. }
  652. return false;
  653. }
  654. Optional<unsigned> ECMA262Parser::read_digits(ECMA262Parser::ReadDigitsInitialZeroState initial_zero, ECMA262Parser::ReadDigitFollowPolicy follow_policy, bool hex, int max_count)
  655. {
  656. if (!match(TokenType::Char))
  657. return {};
  658. if (initial_zero != ReadDigitsInitialZeroState::Allow) {
  659. auto has_initial_zero = m_parser_state.current_token.value() == "0";
  660. if (initial_zero == ReadDigitsInitialZeroState::Disallow && has_initial_zero)
  661. return {};
  662. if (initial_zero == ReadDigitsInitialZeroState::Require && !has_initial_zero)
  663. return {};
  664. }
  665. int count = 0;
  666. size_t offset = 0;
  667. while (match(TokenType::Char)) {
  668. auto c = m_parser_state.current_token.value();
  669. if (follow_policy == ReadDigitFollowPolicy::DisallowDigit) {
  670. if (hex && AK::StringUtils::convert_to_uint_from_hex(c).has_value())
  671. break;
  672. if (!hex && c.to_uint().has_value())
  673. break;
  674. }
  675. if (follow_policy == ReadDigitFollowPolicy::DisallowNonDigit) {
  676. if (hex && !AK::StringUtils::convert_to_uint_from_hex(c).has_value())
  677. break;
  678. if (!hex && !c.to_uint().has_value())
  679. break;
  680. }
  681. if (max_count > 0 && count >= max_count)
  682. break;
  683. offset += consume().value().length();
  684. ++count;
  685. }
  686. auto str = m_parser_state.lexer.slice_back(offset);
  687. if (hex)
  688. return AK::StringUtils::convert_to_uint_from_hex(str);
  689. return str.to_uint();
  690. }
  691. bool ECMA262Parser::parse_quantifier(ByteCode& stack, size_t& match_length_minimum, bool, bool)
  692. {
  693. enum class Repetition {
  694. OneOrMore,
  695. ZeroOrMore,
  696. Optional,
  697. Explicit,
  698. None,
  699. } repetition_mark { Repetition::None };
  700. bool ungreedy = false;
  701. Optional<size_t> repeat_min, repeat_max;
  702. if (match(TokenType::Asterisk)) {
  703. consume();
  704. repetition_mark = Repetition::ZeroOrMore;
  705. } else if (match(TokenType::Plus)) {
  706. consume();
  707. repetition_mark = Repetition::OneOrMore;
  708. } else if (match(TokenType::Questionmark)) {
  709. consume();
  710. repetition_mark = Repetition::Optional;
  711. } else if (match(TokenType::LeftCurly)) {
  712. consume();
  713. repetition_mark = Repetition::Explicit;
  714. auto low_bound = read_digits();
  715. if (!low_bound.has_value()) {
  716. set_error(Error::InvalidBraceContent);
  717. return false;
  718. }
  719. repeat_min = low_bound.value();
  720. if (match(TokenType::Comma)) {
  721. consume();
  722. auto high_bound = read_digits();
  723. if (!high_bound.has_value()) {
  724. set_error(Error::InvalidBraceContent);
  725. return false;
  726. }
  727. repeat_max = high_bound.value();
  728. }
  729. if (!match(TokenType::RightCurly)) {
  730. set_error(Error::MismatchingBrace);
  731. return false;
  732. }
  733. consume();
  734. if (repeat_max.has_value()) {
  735. if (repeat_min.value() > repeat_max.value())
  736. set_error(Error::InvalidBraceContent);
  737. }
  738. } else {
  739. return true;
  740. }
  741. if (match(TokenType::Questionmark)) {
  742. if (repetition_mark == Repetition::Explicit) {
  743. set_error(Error::InvalidRepetitionMarker);
  744. return false;
  745. }
  746. consume();
  747. ungreedy = true;
  748. }
  749. ByteCode new_bytecode;
  750. switch (repetition_mark) {
  751. case Repetition::OneOrMore:
  752. new_bytecode.insert_bytecode_repetition_min_one(stack, !ungreedy);
  753. break;
  754. case Repetition::ZeroOrMore:
  755. new_bytecode.insert_bytecode_repetition_any(stack, !ungreedy);
  756. match_length_minimum = 0;
  757. break;
  758. case Repetition::Optional:
  759. new_bytecode.insert_bytecode_repetition_zero_or_one(stack, !ungreedy);
  760. match_length_minimum = 0;
  761. break;
  762. case Repetition::Explicit:
  763. new_bytecode.insert_bytecode_repetition_min_max(stack, repeat_min.value(), repeat_max);
  764. match_length_minimum *= repeat_min.value();
  765. break;
  766. case Repetition::None:
  767. ASSERT_NOT_REACHED();
  768. }
  769. return true;
  770. }
  771. bool ECMA262Parser::parse_atom(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  772. {
  773. if (match(TokenType::EscapeSequence)) {
  774. // Also part of AtomEscape.
  775. auto token = consume();
  776. match_length_minimum += 1;
  777. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)token.value()[0] } });
  778. return true;
  779. }
  780. if (try_skip("\\")) {
  781. // AtomEscape.
  782. return parse_atom_escape(stack, match_length_minimum, unicode, named);
  783. }
  784. if (match(TokenType::LeftBracket)) {
  785. // Character class.
  786. return parse_character_class(stack, match_length_minimum, unicode, named);
  787. }
  788. if (match(TokenType::LeftParen)) {
  789. // Non-capturing group, or a capture group.
  790. return parse_capture_group(stack, match_length_minimum, unicode, named);
  791. }
  792. if (match(TokenType::Period)) {
  793. consume();
  794. match_length_minimum += 1;
  795. stack.insert_bytecode_compare_values({ { CharacterCompareType::AnyChar, 0 } });
  796. return true;
  797. }
  798. if (match(TokenType::Circumflex) || match(TokenType::Dollar) || match(TokenType::RightBracket)
  799. || match(TokenType::RightCurly) || match(TokenType::RightParen) || match(TokenType::Pipe)
  800. || match(TokenType::Plus) || match(TokenType::Asterisk) || match(TokenType::Questionmark)) {
  801. return false;
  802. }
  803. if (match(TokenType::Char)) {
  804. auto token = consume().value();
  805. match_length_minimum += 1;
  806. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)token[0] } });
  807. return true;
  808. }
  809. set_error(Error::InvalidPattern);
  810. return false;
  811. }
  812. bool ECMA262Parser::parse_atom_escape(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  813. {
  814. if (auto escape = read_digits(ReadDigitsInitialZeroState::Disallow, ReadDigitFollowPolicy::DisallowNonDigit); escape.has_value()) {
  815. auto maybe_length = m_parser_state.capture_group_minimum_lengths.get(escape.value());
  816. if (!maybe_length.has_value()) {
  817. set_error(Error::InvalidNumber);
  818. return false;
  819. }
  820. match_length_minimum += maybe_length.value();
  821. stack.insert_bytecode_compare_values({ { CharacterCompareType::Reference, (ByteCodeValueType)escape.value() } });
  822. return true;
  823. }
  824. // CharacterEscape > ControlEscape
  825. if (try_skip("f")) {
  826. match_length_minimum += 1;
  827. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\f' } });
  828. return true;
  829. }
  830. if (try_skip("n")) {
  831. match_length_minimum += 1;
  832. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\n' } });
  833. return true;
  834. }
  835. if (try_skip("r")) {
  836. match_length_minimum += 1;
  837. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\r' } });
  838. return true;
  839. }
  840. if (try_skip("t")) {
  841. match_length_minimum += 1;
  842. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\t' } });
  843. return true;
  844. }
  845. if (try_skip("v")) {
  846. match_length_minimum += 1;
  847. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\v' } });
  848. return true;
  849. }
  850. // CharacterEscape > ControlLetter
  851. if (try_skip("c")) {
  852. for (auto c = 'A'; c <= 'z'; ++c) {
  853. if (try_skip({ &c, 1 })) {
  854. match_length_minimum += 1;
  855. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)(c & 0x3f) } });
  856. return true;
  857. }
  858. }
  859. if (unicode) {
  860. set_error(Error::InvalidPattern);
  861. return false;
  862. }
  863. // Allow '\c' in non-unicode mode, just matches 'c'.
  864. match_length_minimum += 1;
  865. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'c' } });
  866. return true;
  867. }
  868. // '\0'
  869. if (read_digits(ReadDigitsInitialZeroState::Require, ReadDigitFollowPolicy::DisallowDigit).has_value()) {
  870. match_length_minimum += 1;
  871. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)0 } });
  872. return true;
  873. }
  874. // HexEscape
  875. if (try_skip("x")) {
  876. if (auto hex_escape = read_digits(ReadDigitsInitialZeroState::Allow, ReadDigitFollowPolicy::Any, true, 2); hex_escape.has_value()) {
  877. match_length_minimum += 1;
  878. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)hex_escape.value() } });
  879. return true;
  880. } else if (!unicode) {
  881. // '\x' is allowed in non-unicode mode, just matches 'x'.
  882. match_length_minimum += 1;
  883. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'x' } });
  884. return true;
  885. } else {
  886. set_error(Error::InvalidPattern);
  887. return false;
  888. }
  889. }
  890. if (try_skip("u")) {
  891. // FIXME: Implement this path, unicode escape sequence.
  892. TODO();
  893. }
  894. // IdentityEscape
  895. for (auto ch : StringView { "^$\\.*+?()[]{}|" }) {
  896. if (try_skip({ &ch, 1 })) {
  897. match_length_minimum += 1;
  898. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)ch } });
  899. return true;
  900. }
  901. }
  902. if (unicode) {
  903. if (try_skip("/")) {
  904. match_length_minimum += 1;
  905. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'/' } });
  906. return true;
  907. }
  908. }
  909. if (named && try_skip("k")) {
  910. auto name = read_capture_group_specifier(true);
  911. if (name.is_empty()) {
  912. set_error(Error::InvalidNameForCaptureGroup);
  913. return false;
  914. }
  915. auto maybe_length = m_parser_state.named_capture_group_minimum_lengths.get(name);
  916. if (!maybe_length.has_value()) {
  917. set_error(Error::InvalidNameForCaptureGroup);
  918. return false;
  919. }
  920. match_length_minimum += maybe_length.value();
  921. stack.insert_bytecode_compare_named_reference(name, name.length());
  922. return true;
  923. }
  924. if (unicode) {
  925. if (try_skip("p{")) {
  926. // FIXME: Implement this path, Unicode property match.
  927. TODO();
  928. }
  929. if (try_skip("P{")) {
  930. // FIXME: Implement this path, Unicode property match.
  931. TODO();
  932. }
  933. }
  934. bool negate = false;
  935. auto ch = parse_character_class_escape(negate);
  936. if (!ch.has_value()) {
  937. if (!unicode) {
  938. // Allow all SourceCharacter's as escapes here.
  939. auto token = consume();
  940. match_length_minimum += 1;
  941. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)token.value()[0] } });
  942. return true;
  943. }
  944. set_error(Error::InvalidCharacterClass);
  945. return false;
  946. }
  947. Vector<CompareTypeAndValuePair> compares;
  948. if (negate)
  949. compares.empend(CompareTypeAndValuePair { CharacterCompareType::Inverse, 0 });
  950. compares.empend(CompareTypeAndValuePair { CharacterCompareType::CharClass, (ByteCodeValueType)ch.value() });
  951. match_length_minimum += 1;
  952. stack.insert_bytecode_compare_values(move(compares));
  953. return true;
  954. }
  955. Optional<CharClass> ECMA262Parser::parse_character_class_escape(bool& negate, bool expect_backslash)
  956. {
  957. if (expect_backslash && !try_skip("\\"))
  958. return {};
  959. // CharacterClassEscape
  960. CharClass ch_class;
  961. if (try_skip("d")) {
  962. ch_class = CharClass::Digit;
  963. } else if (try_skip("D")) {
  964. ch_class = CharClass::Digit;
  965. negate = true;
  966. } else if (try_skip("s")) {
  967. ch_class = CharClass::Space;
  968. } else if (try_skip("S")) {
  969. ch_class = CharClass::Space;
  970. negate = true;
  971. } else if (try_skip("w")) {
  972. ch_class = CharClass::Word;
  973. } else if (try_skip("W")) {
  974. ch_class = CharClass::Word;
  975. negate = true;
  976. } else {
  977. return {};
  978. }
  979. return ch_class;
  980. }
  981. bool ECMA262Parser::parse_character_class(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool)
  982. {
  983. consume(TokenType::LeftBracket, Error::InvalidPattern);
  984. Vector<CompareTypeAndValuePair> compares;
  985. if (match(TokenType::Circumflex)) {
  986. // Negated charclass
  987. consume();
  988. compares.empend(CompareTypeAndValuePair { CharacterCompareType::Inverse, 0 });
  989. }
  990. if (match(TokenType::RightBracket)) {
  991. consume();
  992. return true;
  993. }
  994. if (!parse_nonempty_class_ranges(compares, unicode))
  995. return false;
  996. match_length_minimum += 1;
  997. stack.insert_bytecode_compare_values(move(compares));
  998. return true;
  999. }
  1000. struct CharClassRangeElement {
  1001. union {
  1002. CharClass character_class;
  1003. u32 code_point { 0 };
  1004. };
  1005. bool is_negated { false };
  1006. bool is_character_class { false };
  1007. };
  1008. bool ECMA262Parser::parse_nonempty_class_ranges(Vector<CompareTypeAndValuePair>& ranges, bool unicode)
  1009. {
  1010. auto read_class_atom_no_dash = [&]() -> Optional<CharClassRangeElement> {
  1011. if (match(TokenType::EscapeSequence)) {
  1012. auto token = consume().value();
  1013. return { { .code_point = (u32)token[1], .is_character_class = false } };
  1014. }
  1015. if (try_skip("\\")) {
  1016. if (try_skip("f"))
  1017. return { { .code_point = '\f', .is_character_class = false } };
  1018. if (try_skip("n"))
  1019. return { { .code_point = '\n', .is_character_class = false } };
  1020. if (try_skip("r"))
  1021. return { { .code_point = '\r', .is_character_class = false } };
  1022. if (try_skip("t"))
  1023. return { { .code_point = '\t', .is_character_class = false } };
  1024. if (try_skip("v"))
  1025. return { { .code_point = '\v', .is_character_class = false } };
  1026. if (try_skip("b"))
  1027. return { { .code_point = '\b', .is_character_class = false } };
  1028. if (try_skip("/"))
  1029. return { { .code_point = '/', .is_character_class = false } };
  1030. // CharacterEscape > ControlLetter
  1031. if (try_skip("c")) {
  1032. for (auto c = 'A'; c <= 'z'; ++c) {
  1033. if (try_skip({ &c, 1 }))
  1034. return { { .code_point = (u32)(c & 0x3f), .is_character_class = false } };
  1035. }
  1036. }
  1037. // '\0'
  1038. if (read_digits(ReadDigitsInitialZeroState::Require, ReadDigitFollowPolicy::DisallowDigit).has_value())
  1039. return { { .code_point = 0, .is_character_class = false } };
  1040. // HexEscape
  1041. if (try_skip("x")) {
  1042. if (auto hex_escape = read_digits(ReadDigitsInitialZeroState::Allow, ReadDigitFollowPolicy::Any, true, 2); hex_escape.has_value()) {
  1043. return { { .code_point = hex_escape.value(), .is_character_class = false } };
  1044. } else if (!unicode) {
  1045. // '\x' is allowed in non-unicode mode, just matches 'x'.
  1046. return { { .code_point = 'x', .is_character_class = false } };
  1047. } else {
  1048. set_error(Error::InvalidPattern);
  1049. return {};
  1050. }
  1051. }
  1052. if (try_skip("u")) {
  1053. // FIXME: Implement this path, unicode escape sequence.
  1054. TODO();
  1055. }
  1056. if (unicode) {
  1057. if (try_skip("-"))
  1058. return { { .code_point = '-', .is_character_class = false } };
  1059. }
  1060. if (try_skip("p{") || try_skip("P{")) {
  1061. // FIXME: Implement these; unicode properties.
  1062. TODO();
  1063. }
  1064. if (try_skip("d"))
  1065. return { { .character_class = CharClass::Digit, .is_character_class = true } };
  1066. if (try_skip("s"))
  1067. return { { .character_class = CharClass::Space, .is_character_class = true } };
  1068. if (try_skip("w"))
  1069. return { { .character_class = CharClass::Word, .is_character_class = true } };
  1070. if (try_skip("D"))
  1071. return { { .character_class = CharClass::Digit, .is_negated = true, .is_character_class = true } };
  1072. if (try_skip("S"))
  1073. return { { .character_class = CharClass::Space, .is_negated = true, .is_character_class = true } };
  1074. if (try_skip("W"))
  1075. return { { .character_class = CharClass::Word, .is_negated = true, .is_character_class = true } };
  1076. if (!unicode) {
  1077. // Any unrecognised escape is allowed in non-unicode mode.
  1078. return { { .code_point = (u32)skip(), .is_character_class = false } };
  1079. }
  1080. }
  1081. if (match(TokenType::RightBracket) || match(TokenType::HyphenMinus))
  1082. return {};
  1083. // Allow any (other) SourceCharacter.
  1084. return { { .code_point = (u32)skip(), .is_character_class = false } };
  1085. };
  1086. auto read_class_atom = [&]() -> Optional<CharClassRangeElement> {
  1087. if (match(TokenType::HyphenMinus)) {
  1088. consume();
  1089. return { { .code_point = '-', .is_character_class = false } };
  1090. }
  1091. return read_class_atom_no_dash();
  1092. };
  1093. while (!match(TokenType::RightBracket)) {
  1094. if (match(TokenType::Eof)) {
  1095. set_error(Error::MismatchingBracket);
  1096. return false;
  1097. }
  1098. auto first_atom = read_class_atom();
  1099. if (!first_atom.has_value())
  1100. return false;
  1101. if (match(TokenType::HyphenMinus)) {
  1102. consume();
  1103. if (match(TokenType::RightBracket)) {
  1104. // Allow '-' as the last element in a charclass, even after an atom.
  1105. m_parser_state.lexer.back(2); // -]
  1106. m_parser_state.current_token = m_parser_state.lexer.next();
  1107. goto read_as_single_atom;
  1108. }
  1109. auto second_atom = read_class_atom();
  1110. if (!second_atom.has_value())
  1111. return false;
  1112. if (first_atom.value().is_character_class || second_atom.value().is_character_class) {
  1113. set_error(Error::InvalidRange);
  1114. return false;
  1115. }
  1116. if (first_atom.value().code_point > second_atom.value().code_point) {
  1117. set_error(Error::InvalidRange);
  1118. return false;
  1119. }
  1120. ASSERT(!first_atom.value().is_negated);
  1121. ASSERT(!second_atom.value().is_negated);
  1122. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::CharRange, CharRange { first_atom.value().code_point, second_atom.value().code_point } });
  1123. continue;
  1124. }
  1125. read_as_single_atom:;
  1126. auto atom = first_atom.value();
  1127. if (atom.is_character_class) {
  1128. if (atom.is_negated)
  1129. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::TemporaryInverse, 0 });
  1130. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::CharClass, (ByteCodeValueType)first_atom.value().character_class });
  1131. } else {
  1132. ASSERT(!atom.is_negated);
  1133. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::Char, first_atom.value().code_point });
  1134. }
  1135. }
  1136. consume(TokenType::RightBracket, Error::MismatchingBracket);
  1137. return true;
  1138. }
  1139. StringView ECMA262Parser::read_capture_group_specifier(bool take_starting_angle_bracket)
  1140. {
  1141. if (take_starting_angle_bracket && !consume("<"))
  1142. return {};
  1143. size_t offset = 0;
  1144. while (match(TokenType::Char)) {
  1145. auto c = m_parser_state.current_token.value();
  1146. if (c == ">")
  1147. break;
  1148. offset += consume().value().length();
  1149. }
  1150. auto name = m_parser_state.lexer.slice_back(offset);
  1151. if (!consume(">") || name.is_empty())
  1152. set_error(Error::InvalidNameForCaptureGroup);
  1153. return name;
  1154. }
  1155. bool ECMA262Parser::parse_capture_group(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  1156. {
  1157. consume(TokenType::LeftParen, Error::InvalidPattern);
  1158. if (match(TokenType::Questionmark)) {
  1159. // Non-capturing group or group with specifier.
  1160. consume();
  1161. if (match(TokenType::Colon)) {
  1162. consume();
  1163. ByteCode noncapture_group_bytecode;
  1164. size_t length = 0;
  1165. if (!parse_disjunction(noncapture_group_bytecode, length, unicode, named))
  1166. return set_error(Error::InvalidPattern);
  1167. consume(TokenType::RightParen, Error::MismatchingParen);
  1168. stack.append(move(noncapture_group_bytecode));
  1169. match_length_minimum += length;
  1170. return true;
  1171. }
  1172. if (consume("<")) {
  1173. ++m_parser_state.named_capture_groups_count;
  1174. auto name = read_capture_group_specifier();
  1175. if (name.is_empty()) {
  1176. set_error(Error::InvalidNameForCaptureGroup);
  1177. return false;
  1178. }
  1179. ByteCode capture_group_bytecode;
  1180. size_t length = 0;
  1181. if (!parse_disjunction(capture_group_bytecode, length, unicode, named))
  1182. return set_error(Error::InvalidPattern);
  1183. consume(TokenType::RightParen, Error::MismatchingParen);
  1184. stack.insert_bytecode_group_capture_left(name);
  1185. stack.append(move(capture_group_bytecode));
  1186. stack.insert_bytecode_group_capture_right(name);
  1187. match_length_minimum += length;
  1188. m_parser_state.named_capture_group_minimum_lengths.set(name, length);
  1189. return true;
  1190. }
  1191. set_error(Error::InvalidCaptureGroup);
  1192. return false;
  1193. }
  1194. auto group_index = ++m_parser_state.capture_groups_count;
  1195. stack.insert_bytecode_group_capture_left(group_index);
  1196. ByteCode capture_group_bytecode;
  1197. size_t length = 0;
  1198. if (!parse_disjunction(capture_group_bytecode, length, unicode, named))
  1199. return set_error(Error::InvalidPattern);
  1200. stack.append(move(capture_group_bytecode));
  1201. m_parser_state.capture_group_minimum_lengths.set(group_index, length);
  1202. consume(TokenType::RightParen, Error::MismatchingParen);
  1203. stack.insert_bytecode_group_capture_right(group_index);
  1204. match_length_minimum += length;
  1205. return true;
  1206. }
  1207. }