RegexParser.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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. ALWAYS_INLINE bool Parser::match_ordinary_characters()
  141. {
  142. // NOTE: This method must not be called during bracket and repetition parsing!
  143. // FIXME: Add assertion for that?
  144. auto type = m_parser_state.current_token.type();
  145. return (type == TokenType::Char
  146. || type == TokenType::Comma
  147. || type == TokenType::Slash
  148. || type == TokenType::EqualSign
  149. || type == TokenType::HyphenMinus
  150. || type == TokenType::Colon);
  151. }
  152. // =============================
  153. // PosixExtended Parser
  154. // =============================
  155. bool PosixExtendedParser::parse_internal(ByteCode& stack, size_t& match_length_minimum)
  156. {
  157. return parse_root(stack, match_length_minimum);
  158. }
  159. ALWAYS_INLINE bool PosixExtendedParser::match_repetition_symbol()
  160. {
  161. auto type = m_parser_state.current_token.type();
  162. return (type == TokenType::Asterisk
  163. || type == TokenType::Plus
  164. || type == TokenType::Questionmark
  165. || type == TokenType::LeftCurly);
  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::Circumflex)) {
  253. auto t = consume();
  254. if (values.is_empty())
  255. values.append({ CharacterCompareType::Inverse, 0 });
  256. else
  257. values.append({ CharacterCompareType::Char, (ByteCodeValueType)*t.value().characters_without_null_termination() });
  258. } else if (match(TokenType::LeftBracket)) {
  259. consume();
  260. if (match(TokenType::Period)) {
  261. consume();
  262. // FIXME: Parse collating element, this is needed when we have locale support
  263. // This could have impact on length parameter, I guess.
  264. ASSERT_NOT_REACHED();
  265. consume(TokenType::Period, Error::InvalidCollationElement);
  266. consume(TokenType::RightBracket, Error::MismatchingBracket);
  267. } else if (match(TokenType::EqualSign)) {
  268. consume();
  269. // FIXME: Parse collating element, this is needed when we have locale support
  270. // This could have impact on length parameter, I guess.
  271. ASSERT_NOT_REACHED();
  272. consume(TokenType::EqualSign, Error::InvalidCollationElement);
  273. consume(TokenType::RightBracket, Error::MismatchingBracket);
  274. } else if (match(TokenType::Colon)) {
  275. consume();
  276. CharClass ch_class;
  277. // parse character class
  278. if (match(TokenType::Char)) {
  279. if (consume("alnum"))
  280. ch_class = CharClass::Alnum;
  281. else if (consume("alpha"))
  282. ch_class = CharClass::Alpha;
  283. else if (consume("blank"))
  284. ch_class = CharClass::Blank;
  285. else if (consume("cntrl"))
  286. ch_class = CharClass::Cntrl;
  287. else if (consume("digit"))
  288. ch_class = CharClass::Digit;
  289. else if (consume("graph"))
  290. ch_class = CharClass::Graph;
  291. else if (consume("lower"))
  292. ch_class = CharClass::Lower;
  293. else if (consume("print"))
  294. ch_class = CharClass::Print;
  295. else if (consume("punct"))
  296. ch_class = CharClass::Punct;
  297. else if (consume("space"))
  298. ch_class = CharClass::Space;
  299. else if (consume("upper"))
  300. ch_class = CharClass::Upper;
  301. else if (consume("xdigit"))
  302. ch_class = CharClass::Xdigit;
  303. else
  304. return set_error(Error::InvalidCharacterClass);
  305. values.append({ CharacterCompareType::CharClass, (ByteCodeValueType)ch_class });
  306. } else
  307. return set_error(Error::InvalidCharacterClass);
  308. // FIXME: we do not support locale specific character classes until locales are implemented
  309. consume(TokenType::Colon, Error::InvalidCharacterClass);
  310. consume(TokenType::RightBracket, Error::MismatchingBracket);
  311. } else {
  312. return set_error(Error::MismatchingBracket);
  313. }
  314. } else if (match(TokenType::RightBracket)) {
  315. if (values.is_empty() || (values.size() == 1 && values.last().type == CharacterCompareType::Inverse)) {
  316. // handle bracket as ordinary character
  317. values.append({ CharacterCompareType::Char, (ByteCodeValueType)*consume().value().characters_without_null_termination() });
  318. } else {
  319. // closing bracket expression
  320. break;
  321. }
  322. } else {
  323. values.append({ CharacterCompareType::Char, (ByteCodeValueType)skip() });
  324. }
  325. // check if range expression has to be completed...
  326. if (values.size() >= 3 && values.at(values.size() - 2).type == CharacterCompareType::RangeExpressionDummy) {
  327. if (values.last().type != CharacterCompareType::Char)
  328. return set_error(Error::InvalidRange);
  329. auto value2 = values.take_last();
  330. values.take_last(); // RangeExpressionDummy
  331. auto value1 = values.take_last();
  332. values.append({ CharacterCompareType::CharRange, static_cast<ByteCodeValueType>(CharRange { (u32)value1.value, (u32)value2.value }) });
  333. }
  334. }
  335. if (values.size())
  336. match_length_minimum = 1;
  337. if (values.first().type == CharacterCompareType::Inverse)
  338. match_length_minimum = 0;
  339. stack.insert_bytecode_compare_values(move(values));
  340. return !has_error();
  341. }
  342. ALWAYS_INLINE bool PosixExtendedParser::parse_sub_expression(ByteCode& stack, size_t& match_length_minimum)
  343. {
  344. ByteCode bytecode;
  345. size_t length = 0;
  346. bool should_parse_repetition_symbol { false };
  347. for (;;) {
  348. if (match_ordinary_characters()) {
  349. Token start_token = m_parser_state.current_token;
  350. Token last_token = m_parser_state.current_token;
  351. for (;;) {
  352. if (!match_ordinary_characters())
  353. break;
  354. ++length;
  355. last_token = consume();
  356. }
  357. if (length > 1) {
  358. // last character is inserted into 'bytecode' for duplication symbol handling
  359. auto new_length = length - ((match_repetition_symbol() && length > 1) ? 1 : 0);
  360. stack.insert_bytecode_compare_string(start_token.value(), new_length);
  361. }
  362. if ((match_repetition_symbol() && length > 1) || length == 1) // Create own compare opcode for last character before duplication symbol
  363. bytecode.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)last_token.value().characters_without_null_termination()[0] } });
  364. should_parse_repetition_symbol = true;
  365. break;
  366. }
  367. if (match_repetition_symbol())
  368. return set_error(Error::InvalidRepetitionMarker);
  369. if (match(TokenType::Period)) {
  370. length = 1;
  371. consume();
  372. bytecode.insert_bytecode_compare_values({ { CharacterCompareType::AnyChar, 0 } });
  373. should_parse_repetition_symbol = true;
  374. break;
  375. }
  376. if (match(TokenType::EscapeSequence)) {
  377. length = 1;
  378. Token t = consume();
  379. #ifdef REGEX_DEBUG
  380. printf("[PARSER] EscapeSequence with substring %s\n", String(t.value()).characters());
  381. #endif
  382. bytecode.insert_bytecode_compare_values({ { CharacterCompareType::Char, (u32)t.value().characters_without_null_termination()[1] } });
  383. should_parse_repetition_symbol = true;
  384. break;
  385. }
  386. if (match(TokenType::LeftBracket)) {
  387. consume();
  388. ByteCode sub_ops;
  389. if (!parse_bracket_expression(sub_ops, length) || !sub_ops.size())
  390. return set_error(Error::InvalidBracketContent);
  391. bytecode.append(move(sub_ops));
  392. consume(TokenType::RightBracket, Error::MismatchingBracket);
  393. should_parse_repetition_symbol = true;
  394. break;
  395. }
  396. if (match(TokenType::RightBracket)) {
  397. return set_error(Error::MismatchingBracket);
  398. }
  399. if (match(TokenType::RightCurly)) {
  400. return set_error(Error::MismatchingBrace);
  401. }
  402. if (match(TokenType::Circumflex)) {
  403. consume();
  404. bytecode.empend((ByteCodeValueType)OpCodeId::CheckBegin);
  405. break;
  406. }
  407. if (match(TokenType::Dollar)) {
  408. consume();
  409. bytecode.empend((ByteCodeValueType)OpCodeId::CheckEnd);
  410. break;
  411. }
  412. if (match(TokenType::RightParen))
  413. return false;
  414. if (match(TokenType::LeftParen)) {
  415. consume();
  416. Optional<StringView> capture_group_name;
  417. bool prevent_capture_group = false;
  418. if (match(TokenType::Questionmark)) {
  419. consume();
  420. if (match(TokenType::Colon)) {
  421. consume();
  422. prevent_capture_group = true;
  423. } else if (consume("<")) { // named capturing group
  424. Token start_token = m_parser_state.current_token;
  425. Token last_token = m_parser_state.current_token;
  426. size_t capture_group_name_length = 0;
  427. for (;;) {
  428. if (!match_ordinary_characters())
  429. return set_error(Error::InvalidNameForCaptureGroup);
  430. if (match(TokenType::Char) && m_parser_state.current_token.value()[0] == '>') {
  431. consume();
  432. break;
  433. }
  434. ++capture_group_name_length;
  435. last_token = consume();
  436. }
  437. capture_group_name = StringView(start_token.value().characters_without_null_termination(), capture_group_name_length);
  438. } else if (match(TokenType::EqualSign)) { // positive lookahead
  439. consume();
  440. ASSERT_NOT_REACHED();
  441. } else if (consume("!")) { // negative lookahead
  442. ASSERT_NOT_REACHED();
  443. } else if (consume("<")) {
  444. if (match(TokenType::EqualSign)) { // positive lookbehind
  445. consume();
  446. ASSERT_NOT_REACHED();
  447. }
  448. if (consume("!")) // negative lookbehind
  449. ASSERT_NOT_REACHED();
  450. } else {
  451. return set_error(Error::InvalidRepetitionMarker);
  452. }
  453. }
  454. if (!(m_parser_state.regex_options & AllFlags::SkipSubExprResults || prevent_capture_group)) {
  455. if (capture_group_name.has_value())
  456. bytecode.insert_bytecode_group_capture_left(capture_group_name.value());
  457. else
  458. bytecode.insert_bytecode_group_capture_left(m_parser_state.capture_groups_count);
  459. }
  460. ByteCode capture_group_bytecode;
  461. if (!parse_root(capture_group_bytecode, length))
  462. return set_error(Error::InvalidPattern);
  463. bytecode.append(move(capture_group_bytecode));
  464. consume(TokenType::RightParen, Error::MismatchingParen);
  465. if (!(m_parser_state.regex_options & AllFlags::SkipSubExprResults || prevent_capture_group)) {
  466. if (capture_group_name.has_value()) {
  467. bytecode.insert_bytecode_group_capture_right(capture_group_name.value());
  468. ++m_parser_state.named_capture_groups_count;
  469. } else {
  470. bytecode.insert_bytecode_group_capture_right(m_parser_state.capture_groups_count);
  471. ++m_parser_state.capture_groups_count;
  472. }
  473. }
  474. should_parse_repetition_symbol = true;
  475. break;
  476. }
  477. return false;
  478. }
  479. if (match_repetition_symbol()) {
  480. if (should_parse_repetition_symbol)
  481. parse_repetition_symbol(bytecode, length);
  482. else
  483. return set_error(Error::InvalidRepetitionMarker);
  484. }
  485. stack.append(move(bytecode));
  486. match_length_minimum += length;
  487. return true;
  488. }
  489. bool PosixExtendedParser::parse_root(ByteCode& stack, size_t& match_length_minimum)
  490. {
  491. ByteCode bytecode_left;
  492. size_t match_length_minimum_left { 0 };
  493. if (match_repetition_symbol())
  494. return set_error(Error::InvalidRepetitionMarker);
  495. for (;;) {
  496. if (!parse_sub_expression(bytecode_left, match_length_minimum_left))
  497. break;
  498. if (match(TokenType::Pipe)) {
  499. consume();
  500. ByteCode bytecode_right;
  501. size_t match_length_minimum_right { 0 };
  502. if (!parse_root(bytecode_right, match_length_minimum_right) || bytecode_right.is_empty())
  503. return set_error(Error::InvalidPattern);
  504. ByteCode new_bytecode;
  505. new_bytecode.insert_bytecode_alternation(move(bytecode_left), move(bytecode_right));
  506. bytecode_left = move(new_bytecode);
  507. match_length_minimum_left = min(match_length_minimum_right, match_length_minimum_left);
  508. }
  509. }
  510. if (bytecode_left.is_empty())
  511. set_error(Error::EmptySubExpression);
  512. stack.append(move(bytecode_left));
  513. match_length_minimum = match_length_minimum_left;
  514. return !has_error();
  515. }
  516. // =============================
  517. // ECMA262 Parser
  518. // =============================
  519. bool ECMA262Parser::parse_internal(ByteCode& stack, size_t& match_length_minimum)
  520. {
  521. if (m_parser_state.regex_options.has_flag_set(AllFlags::Unicode)) {
  522. return parse_pattern(stack, match_length_minimum, true, true);
  523. } else {
  524. ByteCode new_stack;
  525. size_t new_match_length = 0;
  526. auto res = parse_pattern(new_stack, new_match_length, false, false);
  527. if (m_parser_state.named_capture_groups_count > 0) {
  528. reset();
  529. return parse_pattern(stack, match_length_minimum, false, true);
  530. }
  531. if (!res)
  532. return false;
  533. stack.append(new_stack);
  534. match_length_minimum = new_match_length;
  535. return res;
  536. }
  537. }
  538. bool ECMA262Parser::parse_pattern(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  539. {
  540. return parse_disjunction(stack, match_length_minimum, unicode, named);
  541. }
  542. bool ECMA262Parser::parse_disjunction(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  543. {
  544. ByteCode left_alternative_stack;
  545. size_t left_alternative_min_length = 0;
  546. auto alt_ok = parse_alternative(left_alternative_stack, left_alternative_min_length, unicode, named);
  547. if (!alt_ok)
  548. return false;
  549. if (!match(TokenType::Pipe)) {
  550. stack.append(left_alternative_stack);
  551. match_length_minimum = left_alternative_min_length;
  552. return alt_ok;
  553. }
  554. consume();
  555. ByteCode right_alternative_stack;
  556. size_t right_alternative_min_length = 0;
  557. auto continuation_ok = parse_disjunction(right_alternative_stack, right_alternative_min_length, unicode, named);
  558. if (!continuation_ok)
  559. return false;
  560. stack.insert_bytecode_alternation(move(left_alternative_stack), move(right_alternative_stack));
  561. match_length_minimum = min(left_alternative_min_length, right_alternative_min_length);
  562. return continuation_ok;
  563. }
  564. bool ECMA262Parser::parse_alternative(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  565. {
  566. for (;;) {
  567. if (match(TokenType::Eof))
  568. return true;
  569. if (parse_term(stack, match_length_minimum, unicode, named))
  570. continue;
  571. return !has_error();
  572. }
  573. }
  574. bool ECMA262Parser::parse_term(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  575. {
  576. if (parse_assertion(stack, match_length_minimum, unicode, named))
  577. return true;
  578. ByteCode atom_stack;
  579. size_t minimum_atom_length = 0;
  580. if (!parse_atom(atom_stack, minimum_atom_length, unicode, named))
  581. return false;
  582. if (!parse_quantifier(atom_stack, minimum_atom_length, unicode, named))
  583. return false;
  584. stack.append(move(atom_stack));
  585. match_length_minimum += minimum_atom_length;
  586. return true;
  587. }
  588. bool ECMA262Parser::parse_assertion(ByteCode& stack, [[maybe_unused]] size_t& match_length_minimum, bool unicode, bool named)
  589. {
  590. if (match(TokenType::Circumflex)) {
  591. consume();
  592. stack.empend((ByteCodeValueType)OpCodeId::CheckBegin);
  593. return true;
  594. }
  595. if (match(TokenType::Dollar)) {
  596. consume();
  597. stack.empend((ByteCodeValueType)OpCodeId::CheckEnd);
  598. return true;
  599. }
  600. if (try_skip("\\b")) {
  601. stack.insert_bytecode_check_boundary(BoundaryCheckType::Word);
  602. return true;
  603. }
  604. if (try_skip("\\B")) {
  605. stack.insert_bytecode_check_boundary(BoundaryCheckType::NonWord);
  606. return true;
  607. }
  608. if (match(TokenType::LeftParen)) {
  609. if (!try_skip("(?"))
  610. return false;
  611. ByteCode assertion_stack;
  612. size_t length_dummy = 0;
  613. auto parse_inner_disjunction = [&] {
  614. auto disjunction_ok = parse_disjunction(assertion_stack, length_dummy, unicode, named);
  615. if (!disjunction_ok)
  616. return false;
  617. consume(TokenType::RightParen, Error::MismatchingParen);
  618. return true;
  619. };
  620. if (try_skip("=")) {
  621. if (!parse_inner_disjunction())
  622. return false;
  623. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::LookAhead);
  624. return true;
  625. }
  626. if (try_skip("!")) {
  627. if (!parse_inner_disjunction())
  628. return false;
  629. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::NegatedLookAhead);
  630. return true;
  631. }
  632. if (try_skip("<=")) {
  633. if (!parse_inner_disjunction())
  634. return false;
  635. // FIXME: Somehow ensure that this assertion regexp has a fixed length.
  636. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::LookBehind, length_dummy);
  637. return true;
  638. }
  639. if (try_skip("<!")) {
  640. if (!parse_inner_disjunction())
  641. return false;
  642. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::NegatedLookBehind, length_dummy);
  643. return true;
  644. }
  645. // If none of these matched, put the '(?' back.
  646. m_parser_state.lexer.back(3);
  647. m_parser_state.current_token = m_parser_state.lexer.next();
  648. return false;
  649. }
  650. return false;
  651. }
  652. Optional<unsigned> ECMA262Parser::read_digits(ECMA262Parser::ReadDigitsInitialZeroState initial_zero, ECMA262Parser::ReadDigitFollowPolicy follow_policy, bool hex, int max_count)
  653. {
  654. if (!match(TokenType::Char))
  655. return {};
  656. if (initial_zero != ReadDigitsInitialZeroState::Allow) {
  657. auto has_initial_zero = m_parser_state.current_token.value() == "0";
  658. if (initial_zero == ReadDigitsInitialZeroState::Disallow && has_initial_zero)
  659. return {};
  660. if (initial_zero == ReadDigitsInitialZeroState::Require && !has_initial_zero)
  661. return {};
  662. }
  663. int count = 0;
  664. size_t offset = 0;
  665. while (match(TokenType::Char)) {
  666. auto c = m_parser_state.current_token.value();
  667. if (follow_policy == ReadDigitFollowPolicy::DisallowDigit) {
  668. if (hex && AK::StringUtils::convert_to_uint_from_hex(c).has_value())
  669. break;
  670. if (!hex && c.to_uint().has_value())
  671. break;
  672. }
  673. if (follow_policy == ReadDigitFollowPolicy::DisallowNonDigit) {
  674. if (hex && !AK::StringUtils::convert_to_uint_from_hex(c).has_value())
  675. break;
  676. if (!hex && !c.to_uint().has_value())
  677. break;
  678. }
  679. if (max_count > 0 && count >= max_count)
  680. break;
  681. offset += consume().value().length();
  682. ++count;
  683. }
  684. auto str = m_parser_state.lexer.slice_back(offset);
  685. if (hex)
  686. return AK::StringUtils::convert_to_uint_from_hex(str);
  687. return str.to_uint();
  688. }
  689. bool ECMA262Parser::parse_quantifier(ByteCode& stack, size_t& match_length_minimum, bool, bool)
  690. {
  691. enum class Repetition {
  692. OneOrMore,
  693. ZeroOrMore,
  694. Optional,
  695. Explicit,
  696. None,
  697. } repetition_mark { Repetition::None };
  698. bool ungreedy = false;
  699. Optional<size_t> repeat_min, repeat_max;
  700. if (match(TokenType::Asterisk)) {
  701. consume();
  702. repetition_mark = Repetition::ZeroOrMore;
  703. } else if (match(TokenType::Plus)) {
  704. consume();
  705. repetition_mark = Repetition::OneOrMore;
  706. } else if (match(TokenType::Questionmark)) {
  707. consume();
  708. repetition_mark = Repetition::Optional;
  709. } else if (match(TokenType::LeftCurly)) {
  710. consume();
  711. repetition_mark = Repetition::Explicit;
  712. auto low_bound = read_digits();
  713. if (!low_bound.has_value()) {
  714. set_error(Error::InvalidBraceContent);
  715. return false;
  716. }
  717. repeat_min = low_bound.value();
  718. if (match(TokenType::Comma)) {
  719. consume();
  720. auto high_bound = read_digits();
  721. if (!high_bound.has_value()) {
  722. set_error(Error::InvalidBraceContent);
  723. return false;
  724. }
  725. repeat_max = high_bound.value();
  726. }
  727. if (!match(TokenType::RightCurly)) {
  728. set_error(Error::MismatchingBrace);
  729. return false;
  730. }
  731. consume();
  732. if (repeat_max.has_value()) {
  733. if (repeat_min.value() > repeat_max.value())
  734. set_error(Error::InvalidBraceContent);
  735. }
  736. } else {
  737. return true;
  738. }
  739. if (match(TokenType::Questionmark)) {
  740. if (repetition_mark == Repetition::Explicit) {
  741. set_error(Error::InvalidRepetitionMarker);
  742. return false;
  743. }
  744. consume();
  745. ungreedy = true;
  746. }
  747. ByteCode new_bytecode;
  748. switch (repetition_mark) {
  749. case Repetition::OneOrMore:
  750. new_bytecode.insert_bytecode_repetition_min_one(stack, !ungreedy);
  751. break;
  752. case Repetition::ZeroOrMore:
  753. new_bytecode.insert_bytecode_repetition_any(stack, !ungreedy);
  754. match_length_minimum = 0;
  755. break;
  756. case Repetition::Optional:
  757. new_bytecode.insert_bytecode_repetition_zero_or_one(stack, !ungreedy);
  758. match_length_minimum = 0;
  759. break;
  760. case Repetition::Explicit:
  761. new_bytecode.insert_bytecode_repetition_min_max(stack, repeat_min.value(), repeat_max);
  762. match_length_minimum *= repeat_min.value();
  763. break;
  764. case Repetition::None:
  765. ASSERT_NOT_REACHED();
  766. }
  767. return true;
  768. }
  769. bool ECMA262Parser::parse_atom(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  770. {
  771. if (match(TokenType::EscapeSequence)) {
  772. // Also part of AtomEscape.
  773. auto token = consume();
  774. match_length_minimum += 1;
  775. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)token.value()[0] } });
  776. return true;
  777. }
  778. if (try_skip("\\")) {
  779. // AtomEscape.
  780. return parse_atom_escape(stack, match_length_minimum, unicode, named);
  781. }
  782. if (match(TokenType::LeftBracket)) {
  783. // Character class.
  784. return parse_character_class(stack, match_length_minimum, unicode, named);
  785. }
  786. if (match(TokenType::LeftParen)) {
  787. // Non-capturing group, or a capture group.
  788. return parse_capture_group(stack, match_length_minimum, unicode, named);
  789. }
  790. if (match(TokenType::Period)) {
  791. consume();
  792. match_length_minimum += 1;
  793. stack.insert_bytecode_compare_values({ { CharacterCompareType::AnyChar, 0 } });
  794. return true;
  795. }
  796. if (match(TokenType::Circumflex) || match(TokenType::Dollar) || match(TokenType::RightBracket)
  797. || match(TokenType::RightCurly) || match(TokenType::RightParen) || match(TokenType::Pipe)
  798. || match(TokenType::Plus) || match(TokenType::Asterisk) || match(TokenType::Questionmark)) {
  799. return false;
  800. }
  801. if (match_ordinary_characters()) {
  802. auto token = consume().value();
  803. match_length_minimum += 1;
  804. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)token[0] } });
  805. return true;
  806. }
  807. set_error(Error::InvalidPattern);
  808. return false;
  809. }
  810. bool ECMA262Parser::parse_atom_escape(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  811. {
  812. if (auto escape = read_digits(ReadDigitsInitialZeroState::Disallow, ReadDigitFollowPolicy::DisallowNonDigit); escape.has_value()) {
  813. auto maybe_length = m_parser_state.capture_group_minimum_lengths.get(escape.value());
  814. if (!maybe_length.has_value()) {
  815. set_error(Error::InvalidNumber);
  816. return false;
  817. }
  818. match_length_minimum += maybe_length.value();
  819. stack.insert_bytecode_compare_values({ { CharacterCompareType::Reference, (ByteCodeValueType)escape.value() } });
  820. return true;
  821. }
  822. // CharacterEscape > ControlEscape
  823. if (try_skip("f")) {
  824. match_length_minimum += 1;
  825. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\f' } });
  826. return true;
  827. }
  828. if (try_skip("n")) {
  829. match_length_minimum += 1;
  830. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\n' } });
  831. return true;
  832. }
  833. if (try_skip("r")) {
  834. match_length_minimum += 1;
  835. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\r' } });
  836. return true;
  837. }
  838. if (try_skip("t")) {
  839. match_length_minimum += 1;
  840. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\t' } });
  841. return true;
  842. }
  843. if (try_skip("v")) {
  844. match_length_minimum += 1;
  845. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\v' } });
  846. return true;
  847. }
  848. // CharacterEscape > ControlLetter
  849. if (try_skip("c")) {
  850. for (auto c = 'A'; c <= 'z'; ++c) {
  851. if (try_skip({ &c, 1 })) {
  852. match_length_minimum += 1;
  853. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)(c & 0x3f) } });
  854. return true;
  855. }
  856. }
  857. if (unicode) {
  858. set_error(Error::InvalidPattern);
  859. return false;
  860. }
  861. // Allow '\c' in non-unicode mode, just matches 'c'.
  862. match_length_minimum += 1;
  863. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'c' } });
  864. return true;
  865. }
  866. // '\0'
  867. if (read_digits(ReadDigitsInitialZeroState::Require, ReadDigitFollowPolicy::DisallowDigit).has_value()) {
  868. match_length_minimum += 1;
  869. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)0 } });
  870. return true;
  871. }
  872. // HexEscape
  873. if (try_skip("x")) {
  874. if (auto hex_escape = read_digits(ReadDigitsInitialZeroState::Allow, ReadDigitFollowPolicy::Any, true, 2); hex_escape.has_value()) {
  875. match_length_minimum += 1;
  876. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)hex_escape.value() } });
  877. return true;
  878. } else if (!unicode) {
  879. // '\x' is allowed in non-unicode mode, just matches 'x'.
  880. match_length_minimum += 1;
  881. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'x' } });
  882. return true;
  883. } else {
  884. set_error(Error::InvalidPattern);
  885. return false;
  886. }
  887. }
  888. if (try_skip("u")) {
  889. // FIXME: Implement this path, unicode escape sequence.
  890. TODO();
  891. }
  892. // IdentityEscape
  893. for (auto ch : StringView { "^$\\.*+?()[]{}|" }) {
  894. if (try_skip({ &ch, 1 })) {
  895. match_length_minimum += 1;
  896. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)ch } });
  897. return true;
  898. }
  899. }
  900. if (unicode) {
  901. if (try_skip("/")) {
  902. match_length_minimum += 1;
  903. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'/' } });
  904. return true;
  905. }
  906. }
  907. if (named && try_skip("k")) {
  908. auto name = read_capture_group_specifier(true);
  909. if (name.is_empty()) {
  910. set_error(Error::InvalidNameForCaptureGroup);
  911. return false;
  912. }
  913. auto maybe_length = m_parser_state.named_capture_group_minimum_lengths.get(name);
  914. if (!maybe_length.has_value()) {
  915. set_error(Error::InvalidNameForCaptureGroup);
  916. return false;
  917. }
  918. match_length_minimum += maybe_length.value();
  919. stack.insert_bytecode_compare_named_reference(name, name.length());
  920. return true;
  921. }
  922. if (unicode) {
  923. if (try_skip("p{")) {
  924. // FIXME: Implement this path, Unicode property match.
  925. TODO();
  926. }
  927. if (try_skip("P{")) {
  928. // FIXME: Implement this path, Unicode property match.
  929. TODO();
  930. }
  931. }
  932. bool negate = false;
  933. auto ch = parse_character_class_escape(negate);
  934. if (!ch.has_value()) {
  935. if (!unicode) {
  936. // Allow all SourceCharacter's as escapes here.
  937. auto token = consume();
  938. match_length_minimum += 1;
  939. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)token.value()[0] } });
  940. return true;
  941. }
  942. set_error(Error::InvalidCharacterClass);
  943. return false;
  944. }
  945. Vector<CompareTypeAndValuePair> compares;
  946. if (negate)
  947. compares.empend(CompareTypeAndValuePair { CharacterCompareType::Inverse, 0 });
  948. compares.empend(CompareTypeAndValuePair { CharacterCompareType::CharClass, (ByteCodeValueType)ch.value() });
  949. match_length_minimum += 1;
  950. stack.insert_bytecode_compare_values(move(compares));
  951. return true;
  952. }
  953. Optional<CharClass> ECMA262Parser::parse_character_class_escape(bool& negate, bool expect_backslash)
  954. {
  955. if (expect_backslash && !try_skip("\\"))
  956. return {};
  957. // CharacterClassEscape
  958. CharClass ch_class;
  959. if (try_skip("d")) {
  960. ch_class = CharClass::Digit;
  961. } else if (try_skip("D")) {
  962. ch_class = CharClass::Digit;
  963. negate = true;
  964. } else if (try_skip("s")) {
  965. ch_class = CharClass::Space;
  966. } else if (try_skip("S")) {
  967. ch_class = CharClass::Space;
  968. negate = true;
  969. } else if (try_skip("w")) {
  970. ch_class = CharClass::Word;
  971. } else if (try_skip("W")) {
  972. ch_class = CharClass::Word;
  973. negate = true;
  974. } else {
  975. return {};
  976. }
  977. return ch_class;
  978. }
  979. bool ECMA262Parser::parse_character_class(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool)
  980. {
  981. consume(TokenType::LeftBracket, Error::InvalidPattern);
  982. Vector<CompareTypeAndValuePair> compares;
  983. if (match(TokenType::Circumflex)) {
  984. // Negated charclass
  985. consume();
  986. compares.empend(CompareTypeAndValuePair { CharacterCompareType::Inverse, 0 });
  987. }
  988. if (match(TokenType::RightBracket)) {
  989. consume();
  990. return true;
  991. }
  992. if (!parse_nonempty_class_ranges(compares, unicode))
  993. return false;
  994. match_length_minimum += 1;
  995. stack.insert_bytecode_compare_values(move(compares));
  996. return true;
  997. }
  998. struct CharClassRangeElement {
  999. union {
  1000. CharClass character_class;
  1001. u32 code_point { 0 };
  1002. };
  1003. bool is_negated { false };
  1004. bool is_character_class { false };
  1005. };
  1006. bool ECMA262Parser::parse_nonempty_class_ranges(Vector<CompareTypeAndValuePair>& ranges, bool unicode)
  1007. {
  1008. auto read_class_atom_no_dash = [&]() -> Optional<CharClassRangeElement> {
  1009. if (match(TokenType::EscapeSequence)) {
  1010. auto token = consume().value();
  1011. return { { .code_point = (u32)token[1], .is_character_class = false } };
  1012. }
  1013. if (try_skip("\\")) {
  1014. if (try_skip("f"))
  1015. return { { .code_point = '\f', .is_character_class = false } };
  1016. if (try_skip("n"))
  1017. return { { .code_point = '\n', .is_character_class = false } };
  1018. if (try_skip("r"))
  1019. return { { .code_point = '\r', .is_character_class = false } };
  1020. if (try_skip("t"))
  1021. return { { .code_point = '\t', .is_character_class = false } };
  1022. if (try_skip("v"))
  1023. return { { .code_point = '\v', .is_character_class = false } };
  1024. if (try_skip("b"))
  1025. return { { .code_point = '\b', .is_character_class = false } };
  1026. if (try_skip("/"))
  1027. return { { .code_point = '/', .is_character_class = false } };
  1028. // CharacterEscape > ControlLetter
  1029. if (try_skip("c")) {
  1030. for (auto c = 'A'; c <= 'z'; ++c) {
  1031. if (try_skip({ &c, 1 }))
  1032. return { { .code_point = (u32)(c & 0x3f), .is_character_class = false } };
  1033. }
  1034. }
  1035. // '\0'
  1036. if (read_digits(ReadDigitsInitialZeroState::Require, ReadDigitFollowPolicy::DisallowDigit).has_value())
  1037. return { { .code_point = 0, .is_character_class = false } };
  1038. // HexEscape
  1039. if (try_skip("x")) {
  1040. if (auto hex_escape = read_digits(ReadDigitsInitialZeroState::Allow, ReadDigitFollowPolicy::Any, true, 2); hex_escape.has_value()) {
  1041. return { { .code_point = hex_escape.value(), .is_character_class = false } };
  1042. } else if (!unicode) {
  1043. // '\x' is allowed in non-unicode mode, just matches 'x'.
  1044. return { { .code_point = 'x', .is_character_class = false } };
  1045. } else {
  1046. set_error(Error::InvalidPattern);
  1047. return {};
  1048. }
  1049. }
  1050. if (try_skip("u")) {
  1051. // FIXME: Implement this path, unicode escape sequence.
  1052. TODO();
  1053. }
  1054. if (unicode) {
  1055. if (try_skip("-"))
  1056. return { { .code_point = '-', .is_character_class = false } };
  1057. }
  1058. if (try_skip("p{") || try_skip("P{")) {
  1059. // FIXME: Implement these; unicode properties.
  1060. TODO();
  1061. }
  1062. if (try_skip("d"))
  1063. return { { .character_class = CharClass::Digit, .is_character_class = true } };
  1064. if (try_skip("s"))
  1065. return { { .character_class = CharClass::Space, .is_character_class = true } };
  1066. if (try_skip("w"))
  1067. return { { .character_class = CharClass::Word, .is_character_class = true } };
  1068. if (try_skip("D"))
  1069. return { { .character_class = CharClass::Digit, .is_negated = true, .is_character_class = true } };
  1070. if (try_skip("S"))
  1071. return { { .character_class = CharClass::Space, .is_negated = true, .is_character_class = true } };
  1072. if (try_skip("W"))
  1073. return { { .character_class = CharClass::Word, .is_negated = true, .is_character_class = true } };
  1074. if (!unicode) {
  1075. // Any unrecognised escape is allowed in non-unicode mode.
  1076. return { { .code_point = (u32)skip(), .is_character_class = false } };
  1077. }
  1078. }
  1079. if (match(TokenType::RightBracket) || match(TokenType::HyphenMinus))
  1080. return {};
  1081. // Allow any (other) SourceCharacter.
  1082. return { { .code_point = (u32)skip(), .is_character_class = false } };
  1083. };
  1084. auto read_class_atom = [&]() -> Optional<CharClassRangeElement> {
  1085. if (match(TokenType::HyphenMinus)) {
  1086. consume();
  1087. return { { .code_point = '-', .is_character_class = false } };
  1088. }
  1089. return read_class_atom_no_dash();
  1090. };
  1091. while (!match(TokenType::RightBracket)) {
  1092. if (match(TokenType::Eof)) {
  1093. set_error(Error::MismatchingBracket);
  1094. return false;
  1095. }
  1096. auto first_atom = read_class_atom();
  1097. if (!first_atom.has_value())
  1098. return false;
  1099. if (match(TokenType::HyphenMinus)) {
  1100. consume();
  1101. if (match(TokenType::RightBracket)) {
  1102. // Allow '-' as the last element in a charclass, even after an atom.
  1103. m_parser_state.lexer.back(2); // -]
  1104. m_parser_state.current_token = m_parser_state.lexer.next();
  1105. goto read_as_single_atom;
  1106. }
  1107. auto second_atom = read_class_atom();
  1108. if (!second_atom.has_value())
  1109. return false;
  1110. if (first_atom.value().is_character_class || second_atom.value().is_character_class) {
  1111. set_error(Error::InvalidRange);
  1112. return false;
  1113. }
  1114. if (first_atom.value().code_point > second_atom.value().code_point) {
  1115. set_error(Error::InvalidRange);
  1116. return false;
  1117. }
  1118. ASSERT(!first_atom.value().is_negated);
  1119. ASSERT(!second_atom.value().is_negated);
  1120. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::CharRange, CharRange { first_atom.value().code_point, second_atom.value().code_point } });
  1121. continue;
  1122. }
  1123. read_as_single_atom:;
  1124. auto atom = first_atom.value();
  1125. if (atom.is_character_class) {
  1126. if (atom.is_negated)
  1127. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::TemporaryInverse, 0 });
  1128. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::CharClass, (ByteCodeValueType)first_atom.value().character_class });
  1129. } else {
  1130. ASSERT(!atom.is_negated);
  1131. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::Char, first_atom.value().code_point });
  1132. }
  1133. }
  1134. consume(TokenType::RightBracket, Error::MismatchingBracket);
  1135. return true;
  1136. }
  1137. StringView ECMA262Parser::read_capture_group_specifier(bool take_starting_angle_bracket)
  1138. {
  1139. if (take_starting_angle_bracket && !consume("<"))
  1140. return {};
  1141. size_t offset = 0;
  1142. while (match(TokenType::Char)) {
  1143. auto c = m_parser_state.current_token.value();
  1144. if (c == ">")
  1145. break;
  1146. offset += consume().value().length();
  1147. }
  1148. auto name = m_parser_state.lexer.slice_back(offset);
  1149. if (!consume(">") || name.is_empty())
  1150. set_error(Error::InvalidNameForCaptureGroup);
  1151. return name;
  1152. }
  1153. bool ECMA262Parser::parse_capture_group(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  1154. {
  1155. consume(TokenType::LeftParen, Error::InvalidPattern);
  1156. if (match(TokenType::Questionmark)) {
  1157. // Non-capturing group or group with specifier.
  1158. consume();
  1159. if (match(TokenType::Colon)) {
  1160. consume();
  1161. ByteCode noncapture_group_bytecode;
  1162. size_t length = 0;
  1163. if (!parse_disjunction(noncapture_group_bytecode, length, unicode, named))
  1164. return set_error(Error::InvalidPattern);
  1165. consume(TokenType::RightParen, Error::MismatchingParen);
  1166. stack.append(move(noncapture_group_bytecode));
  1167. match_length_minimum += length;
  1168. return true;
  1169. }
  1170. if (consume("<")) {
  1171. ++m_parser_state.named_capture_groups_count;
  1172. auto name = read_capture_group_specifier();
  1173. if (name.is_empty()) {
  1174. set_error(Error::InvalidNameForCaptureGroup);
  1175. return false;
  1176. }
  1177. ByteCode capture_group_bytecode;
  1178. size_t length = 0;
  1179. if (!parse_disjunction(capture_group_bytecode, length, unicode, named))
  1180. return set_error(Error::InvalidPattern);
  1181. consume(TokenType::RightParen, Error::MismatchingParen);
  1182. stack.insert_bytecode_group_capture_left(name);
  1183. stack.append(move(capture_group_bytecode));
  1184. stack.insert_bytecode_group_capture_right(name);
  1185. match_length_minimum += length;
  1186. m_parser_state.named_capture_group_minimum_lengths.set(name, length);
  1187. return true;
  1188. }
  1189. set_error(Error::InvalidCaptureGroup);
  1190. return false;
  1191. }
  1192. auto group_index = ++m_parser_state.capture_groups_count;
  1193. stack.insert_bytecode_group_capture_left(group_index);
  1194. ByteCode capture_group_bytecode;
  1195. size_t length = 0;
  1196. if (!parse_disjunction(capture_group_bytecode, length, unicode, named))
  1197. return set_error(Error::InvalidPattern);
  1198. stack.append(move(capture_group_bytecode));
  1199. m_parser_state.capture_group_minimum_lengths.set(group_index, length);
  1200. consume(TokenType::RightParen, Error::MismatchingParen);
  1201. stack.insert_bytecode_group_capture_right(group_index);
  1202. match_length_minimum += length;
  1203. return true;
  1204. }
  1205. }