RegexParser.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  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. dbgln("[PARSER] Error: Unexpected token {}. Expected: {}", m_parser_state.current_token.name(), 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: don't 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().characters_without_null_termination(), 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. if (done()) {
  612. set_error(Error::InvalidCaptureGroup);
  613. return false;
  614. }
  615. ByteCode assertion_stack;
  616. size_t length_dummy = 0;
  617. auto parse_inner_disjunction = [&] {
  618. auto disjunction_ok = parse_disjunction(assertion_stack, length_dummy, unicode, named);
  619. if (!disjunction_ok)
  620. return false;
  621. consume(TokenType::RightParen, Error::MismatchingParen);
  622. return true;
  623. };
  624. if (try_skip("=")) {
  625. if (!parse_inner_disjunction())
  626. return false;
  627. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::LookAhead);
  628. return true;
  629. }
  630. if (try_skip("!")) {
  631. if (!parse_inner_disjunction())
  632. return false;
  633. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::NegatedLookAhead);
  634. return true;
  635. }
  636. if (try_skip("<=")) {
  637. if (!parse_inner_disjunction())
  638. return false;
  639. // FIXME: Somehow ensure that this assertion regexp has a fixed length.
  640. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::LookBehind, length_dummy);
  641. return true;
  642. }
  643. if (try_skip("<!")) {
  644. if (!parse_inner_disjunction())
  645. return false;
  646. stack.insert_bytecode_lookaround(move(assertion_stack), ByteCode::LookAroundType::NegatedLookBehind, length_dummy);
  647. return true;
  648. }
  649. // If none of these matched, put the '(?' back.
  650. m_parser_state.lexer.back(3);
  651. m_parser_state.current_token = m_parser_state.lexer.next();
  652. return false;
  653. }
  654. return false;
  655. }
  656. Optional<unsigned> ECMA262Parser::read_digits(ECMA262Parser::ReadDigitsInitialZeroState initial_zero, ECMA262Parser::ReadDigitFollowPolicy follow_policy, bool hex, int max_count)
  657. {
  658. if (!match(TokenType::Char))
  659. return {};
  660. if (initial_zero != ReadDigitsInitialZeroState::Allow) {
  661. auto has_initial_zero = m_parser_state.current_token.value() == "0";
  662. if (initial_zero == ReadDigitsInitialZeroState::Disallow && has_initial_zero)
  663. return {};
  664. if (initial_zero == ReadDigitsInitialZeroState::Require && !has_initial_zero)
  665. return {};
  666. }
  667. int count = 0;
  668. size_t offset = 0;
  669. auto start_token = m_parser_state.current_token;
  670. while (match(TokenType::Char)) {
  671. auto c = m_parser_state.current_token.value();
  672. if (follow_policy == ReadDigitFollowPolicy::DisallowDigit) {
  673. if (hex && AK::StringUtils::convert_to_uint_from_hex(c).has_value())
  674. break;
  675. if (!hex && c.to_uint().has_value())
  676. break;
  677. }
  678. if (follow_policy == ReadDigitFollowPolicy::DisallowNonDigit) {
  679. if (hex && !AK::StringUtils::convert_to_uint_from_hex(c).has_value())
  680. break;
  681. if (!hex && !c.to_uint().has_value())
  682. break;
  683. }
  684. if (max_count > 0 && count >= max_count)
  685. break;
  686. offset += consume().value().length();
  687. ++count;
  688. }
  689. StringView str { start_token.value().characters_without_null_termination(), offset };
  690. if (hex)
  691. return AK::StringUtils::convert_to_uint_from_hex(str);
  692. return str.to_uint();
  693. }
  694. bool ECMA262Parser::parse_quantifier(ByteCode& stack, size_t& match_length_minimum, bool, bool)
  695. {
  696. enum class Repetition {
  697. OneOrMore,
  698. ZeroOrMore,
  699. Optional,
  700. Explicit,
  701. None,
  702. } repetition_mark { Repetition::None };
  703. bool ungreedy = false;
  704. Optional<size_t> repeat_min, repeat_max;
  705. if (match(TokenType::Asterisk)) {
  706. consume();
  707. repetition_mark = Repetition::ZeroOrMore;
  708. } else if (match(TokenType::Plus)) {
  709. consume();
  710. repetition_mark = Repetition::OneOrMore;
  711. } else if (match(TokenType::Questionmark)) {
  712. consume();
  713. repetition_mark = Repetition::Optional;
  714. } else if (match(TokenType::LeftCurly)) {
  715. consume();
  716. repetition_mark = Repetition::Explicit;
  717. auto low_bound = read_digits();
  718. if (!low_bound.has_value()) {
  719. set_error(Error::InvalidBraceContent);
  720. return false;
  721. }
  722. repeat_min = low_bound.value();
  723. if (match(TokenType::Comma)) {
  724. consume();
  725. auto high_bound = read_digits();
  726. if (!high_bound.has_value()) {
  727. set_error(Error::InvalidBraceContent);
  728. return false;
  729. }
  730. repeat_max = high_bound.value();
  731. }
  732. if (!match(TokenType::RightCurly)) {
  733. set_error(Error::MismatchingBrace);
  734. return false;
  735. }
  736. consume();
  737. if (repeat_max.has_value()) {
  738. if (repeat_min.value() > repeat_max.value())
  739. set_error(Error::InvalidBraceContent);
  740. }
  741. } else {
  742. return true;
  743. }
  744. if (match(TokenType::Questionmark)) {
  745. if (repetition_mark == Repetition::Explicit) {
  746. set_error(Error::InvalidRepetitionMarker);
  747. return false;
  748. }
  749. consume();
  750. ungreedy = true;
  751. }
  752. ByteCode new_bytecode;
  753. switch (repetition_mark) {
  754. case Repetition::OneOrMore:
  755. new_bytecode.insert_bytecode_repetition_min_one(stack, !ungreedy);
  756. break;
  757. case Repetition::ZeroOrMore:
  758. new_bytecode.insert_bytecode_repetition_any(stack, !ungreedy);
  759. match_length_minimum = 0;
  760. break;
  761. case Repetition::Optional:
  762. new_bytecode.insert_bytecode_repetition_zero_or_one(stack, !ungreedy);
  763. match_length_minimum = 0;
  764. break;
  765. case Repetition::Explicit:
  766. new_bytecode.insert_bytecode_repetition_min_max(stack, repeat_min.value(), repeat_max);
  767. match_length_minimum *= repeat_min.value();
  768. break;
  769. case Repetition::None:
  770. ASSERT_NOT_REACHED();
  771. }
  772. return true;
  773. }
  774. bool ECMA262Parser::parse_atom(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  775. {
  776. if (match(TokenType::EscapeSequence)) {
  777. // Also part of AtomEscape.
  778. auto token = consume();
  779. match_length_minimum += 1;
  780. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)token.value()[0] } });
  781. return true;
  782. }
  783. if (try_skip("\\")) {
  784. // AtomEscape.
  785. return parse_atom_escape(stack, match_length_minimum, unicode, named);
  786. }
  787. if (match(TokenType::LeftBracket)) {
  788. // Character class.
  789. return parse_character_class(stack, match_length_minimum, unicode, named);
  790. }
  791. if (match(TokenType::LeftParen)) {
  792. // Non-capturing group, or a capture group.
  793. return parse_capture_group(stack, match_length_minimum, unicode, named);
  794. }
  795. if (match(TokenType::Period)) {
  796. consume();
  797. match_length_minimum += 1;
  798. stack.insert_bytecode_compare_values({ { CharacterCompareType::AnyChar, 0 } });
  799. return true;
  800. }
  801. if (match(TokenType::Circumflex) || match(TokenType::Dollar) || match(TokenType::RightBracket)
  802. || match(TokenType::RightCurly) || match(TokenType::RightParen) || match(TokenType::Pipe)
  803. || match(TokenType::Plus) || match(TokenType::Asterisk) || match(TokenType::Questionmark)) {
  804. return false;
  805. }
  806. if (match_ordinary_characters()) {
  807. auto token = consume().value();
  808. match_length_minimum += 1;
  809. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)token[0] } });
  810. return true;
  811. }
  812. set_error(Error::InvalidPattern);
  813. return false;
  814. }
  815. bool ECMA262Parser::parse_atom_escape(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  816. {
  817. if (auto escape = read_digits(ReadDigitsInitialZeroState::Disallow, ReadDigitFollowPolicy::DisallowNonDigit); escape.has_value()) {
  818. auto maybe_length = m_parser_state.capture_group_minimum_lengths.get(escape.value());
  819. if (!maybe_length.has_value()) {
  820. set_error(Error::InvalidNumber);
  821. return false;
  822. }
  823. match_length_minimum += maybe_length.value();
  824. stack.insert_bytecode_compare_values({ { CharacterCompareType::Reference, (ByteCodeValueType)escape.value() } });
  825. return true;
  826. }
  827. // CharacterEscape > ControlEscape
  828. if (try_skip("f")) {
  829. match_length_minimum += 1;
  830. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\f' } });
  831. return true;
  832. }
  833. if (try_skip("n")) {
  834. match_length_minimum += 1;
  835. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\n' } });
  836. return true;
  837. }
  838. if (try_skip("r")) {
  839. match_length_minimum += 1;
  840. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\r' } });
  841. return true;
  842. }
  843. if (try_skip("t")) {
  844. match_length_minimum += 1;
  845. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\t' } });
  846. return true;
  847. }
  848. if (try_skip("v")) {
  849. match_length_minimum += 1;
  850. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'\v' } });
  851. return true;
  852. }
  853. // CharacterEscape > ControlLetter
  854. if (try_skip("c")) {
  855. for (auto c = 'A'; c <= 'z'; ++c) {
  856. if (try_skip({ &c, 1 })) {
  857. match_length_minimum += 1;
  858. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)(c & 0x3f) } });
  859. return true;
  860. }
  861. }
  862. if (unicode) {
  863. set_error(Error::InvalidPattern);
  864. return false;
  865. }
  866. // Allow '\c' in non-unicode mode, just matches 'c'.
  867. match_length_minimum += 1;
  868. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'c' } });
  869. return true;
  870. }
  871. // '\0'
  872. if (read_digits(ReadDigitsInitialZeroState::Require, ReadDigitFollowPolicy::DisallowDigit).has_value()) {
  873. match_length_minimum += 1;
  874. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)0 } });
  875. return true;
  876. }
  877. // HexEscape
  878. if (try_skip("x")) {
  879. if (auto hex_escape = read_digits(ReadDigitsInitialZeroState::Allow, ReadDigitFollowPolicy::Any, true, 2); hex_escape.has_value()) {
  880. match_length_minimum += 1;
  881. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)hex_escape.value() } });
  882. return true;
  883. } else if (!unicode) {
  884. // '\x' is allowed in non-unicode mode, just matches 'x'.
  885. match_length_minimum += 1;
  886. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'x' } });
  887. return true;
  888. } else {
  889. set_error(Error::InvalidPattern);
  890. return false;
  891. }
  892. }
  893. if (try_skip("u")) {
  894. if (auto code_point = read_digits(ReadDigitsInitialZeroState::Allow, ReadDigitFollowPolicy::Any, true, 4); code_point.has_value()) {
  895. // FIXME: The minimum length depends on the mode - should be utf8-length in u8 mode.
  896. match_length_minimum += 1;
  897. StringBuilder builder;
  898. builder.append_code_point(code_point.value());
  899. // FIXME: This isn't actually correct for ECMAScript.
  900. auto u8_encoded = builder.string_view();
  901. stack.insert_bytecode_compare_string(u8_encoded);
  902. return true;
  903. } else if (!unicode) {
  904. // '\u' is allowed in non-unicode mode, just matches 'u'.
  905. match_length_minimum += 1;
  906. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'u' } });
  907. return true;
  908. } else {
  909. set_error(Error::InvalidPattern);
  910. return false;
  911. }
  912. }
  913. // IdentityEscape
  914. for (auto ch : StringView { "^$\\.*+?()[]{}|" }) {
  915. if (try_skip({ &ch, 1 })) {
  916. match_length_minimum += 1;
  917. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)ch } });
  918. return true;
  919. }
  920. }
  921. if (unicode) {
  922. if (try_skip("/")) {
  923. match_length_minimum += 1;
  924. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)'/' } });
  925. return true;
  926. }
  927. }
  928. if (named && try_skip("k")) {
  929. auto name = read_capture_group_specifier(true);
  930. if (name.is_empty()) {
  931. set_error(Error::InvalidNameForCaptureGroup);
  932. return false;
  933. }
  934. auto maybe_length = m_parser_state.named_capture_group_minimum_lengths.get(name);
  935. if (!maybe_length.has_value()) {
  936. set_error(Error::InvalidNameForCaptureGroup);
  937. return false;
  938. }
  939. match_length_minimum += maybe_length.value();
  940. stack.insert_bytecode_compare_named_reference(name);
  941. return true;
  942. }
  943. if (unicode) {
  944. if (try_skip("p{")) {
  945. // FIXME: Implement this path, Unicode property match.
  946. TODO();
  947. }
  948. if (try_skip("P{")) {
  949. // FIXME: Implement this path, Unicode property match.
  950. TODO();
  951. }
  952. }
  953. if (done())
  954. return set_error(Error::InvalidTrailingEscape);
  955. bool negate = false;
  956. auto ch = parse_character_class_escape(negate);
  957. if (!ch.has_value()) {
  958. if (!unicode) {
  959. // Allow all SourceCharacter's as escapes here.
  960. auto token = consume();
  961. match_length_minimum += 1;
  962. stack.insert_bytecode_compare_values({ { CharacterCompareType::Char, (ByteCodeValueType)token.value()[0] } });
  963. return true;
  964. }
  965. set_error(Error::InvalidCharacterClass);
  966. return false;
  967. }
  968. Vector<CompareTypeAndValuePair> compares;
  969. if (negate)
  970. compares.empend(CompareTypeAndValuePair { CharacterCompareType::Inverse, 0 });
  971. compares.empend(CompareTypeAndValuePair { CharacterCompareType::CharClass, (ByteCodeValueType)ch.value() });
  972. match_length_minimum += 1;
  973. stack.insert_bytecode_compare_values(move(compares));
  974. return true;
  975. }
  976. Optional<CharClass> ECMA262Parser::parse_character_class_escape(bool& negate, bool expect_backslash)
  977. {
  978. if (expect_backslash && !try_skip("\\"))
  979. return {};
  980. // CharacterClassEscape
  981. CharClass ch_class;
  982. if (try_skip("d")) {
  983. ch_class = CharClass::Digit;
  984. } else if (try_skip("D")) {
  985. ch_class = CharClass::Digit;
  986. negate = true;
  987. } else if (try_skip("s")) {
  988. ch_class = CharClass::Space;
  989. } else if (try_skip("S")) {
  990. ch_class = CharClass::Space;
  991. negate = true;
  992. } else if (try_skip("w")) {
  993. ch_class = CharClass::Word;
  994. } else if (try_skip("W")) {
  995. ch_class = CharClass::Word;
  996. negate = true;
  997. } else {
  998. return {};
  999. }
  1000. return ch_class;
  1001. }
  1002. bool ECMA262Parser::parse_character_class(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool)
  1003. {
  1004. consume(TokenType::LeftBracket, Error::InvalidPattern);
  1005. Vector<CompareTypeAndValuePair> compares;
  1006. if (match(TokenType::Circumflex)) {
  1007. // Negated charclass
  1008. consume();
  1009. compares.empend(CompareTypeAndValuePair { CharacterCompareType::Inverse, 0 });
  1010. }
  1011. if (match(TokenType::RightBracket)) {
  1012. consume();
  1013. return true;
  1014. }
  1015. if (!parse_nonempty_class_ranges(compares, unicode))
  1016. return false;
  1017. match_length_minimum += 1;
  1018. stack.insert_bytecode_compare_values(move(compares));
  1019. return true;
  1020. }
  1021. struct CharClassRangeElement {
  1022. union {
  1023. CharClass character_class;
  1024. u32 code_point { 0 };
  1025. };
  1026. bool is_negated { false };
  1027. bool is_character_class { false };
  1028. };
  1029. bool ECMA262Parser::parse_nonempty_class_ranges(Vector<CompareTypeAndValuePair>& ranges, bool unicode)
  1030. {
  1031. auto read_class_atom_no_dash = [&]() -> Optional<CharClassRangeElement> {
  1032. if (match(TokenType::EscapeSequence)) {
  1033. auto token = consume().value();
  1034. return { { .code_point = (u32)token[1], .is_character_class = false } };
  1035. }
  1036. if (try_skip("\\")) {
  1037. if (done()) {
  1038. set_error(Error::InvalidTrailingEscape);
  1039. return {};
  1040. }
  1041. if (try_skip("f"))
  1042. return { { .code_point = '\f', .is_character_class = false } };
  1043. if (try_skip("n"))
  1044. return { { .code_point = '\n', .is_character_class = false } };
  1045. if (try_skip("r"))
  1046. return { { .code_point = '\r', .is_character_class = false } };
  1047. if (try_skip("t"))
  1048. return { { .code_point = '\t', .is_character_class = false } };
  1049. if (try_skip("v"))
  1050. return { { .code_point = '\v', .is_character_class = false } };
  1051. if (try_skip("b"))
  1052. return { { .code_point = '\b', .is_character_class = false } };
  1053. if (try_skip("/"))
  1054. return { { .code_point = '/', .is_character_class = false } };
  1055. // CharacterEscape > ControlLetter
  1056. if (try_skip("c")) {
  1057. for (auto c = 'A'; c <= 'z'; ++c) {
  1058. if (try_skip({ &c, 1 }))
  1059. return { { .code_point = (u32)(c & 0x3f), .is_character_class = false } };
  1060. }
  1061. }
  1062. // '\0'
  1063. if (read_digits(ReadDigitsInitialZeroState::Require, ReadDigitFollowPolicy::DisallowDigit).has_value())
  1064. return { { .code_point = 0, .is_character_class = false } };
  1065. // HexEscape
  1066. if (try_skip("x")) {
  1067. if (auto hex_escape = read_digits(ReadDigitsInitialZeroState::Allow, ReadDigitFollowPolicy::Any, true, 2); hex_escape.has_value()) {
  1068. return { { .code_point = hex_escape.value(), .is_character_class = false } };
  1069. } else if (!unicode) {
  1070. // '\x' is allowed in non-unicode mode, just matches 'x'.
  1071. return { { .code_point = 'x', .is_character_class = false } };
  1072. } else {
  1073. set_error(Error::InvalidPattern);
  1074. return {};
  1075. }
  1076. }
  1077. if (try_skip("u")) {
  1078. if (auto code_point = read_digits(ReadDigitsInitialZeroState::Allow, ReadDigitFollowPolicy::Any, true, 4); code_point.has_value()) {
  1079. // FIXME: While codepoint ranges are supported, codepoint matches as "Char" are not!
  1080. return { { .code_point = code_point.value(), .is_character_class = false } };
  1081. } else if (!unicode) {
  1082. // '\u' is allowed in non-unicode mode, just matches 'u'.
  1083. return { { .code_point = 'u', .is_character_class = false } };
  1084. } else {
  1085. set_error(Error::InvalidPattern);
  1086. return {};
  1087. }
  1088. }
  1089. if (unicode) {
  1090. if (try_skip("-"))
  1091. return { { .code_point = '-', .is_character_class = false } };
  1092. }
  1093. if (try_skip("p{") || try_skip("P{")) {
  1094. // FIXME: Implement these; unicode properties.
  1095. TODO();
  1096. }
  1097. if (try_skip("d"))
  1098. return { { .character_class = CharClass::Digit, .is_character_class = true } };
  1099. if (try_skip("s"))
  1100. return { { .character_class = CharClass::Space, .is_character_class = true } };
  1101. if (try_skip("w"))
  1102. return { { .character_class = CharClass::Word, .is_character_class = true } };
  1103. if (try_skip("D"))
  1104. return { { .character_class = CharClass::Digit, .is_negated = true, .is_character_class = true } };
  1105. if (try_skip("S"))
  1106. return { { .character_class = CharClass::Space, .is_negated = true, .is_character_class = true } };
  1107. if (try_skip("W"))
  1108. return { { .character_class = CharClass::Word, .is_negated = true, .is_character_class = true } };
  1109. if (!unicode) {
  1110. // Any unrecognised escape is allowed in non-unicode mode.
  1111. return { { .code_point = (u32)skip(), .is_character_class = false } };
  1112. }
  1113. }
  1114. if (match(TokenType::RightBracket) || match(TokenType::HyphenMinus))
  1115. return {};
  1116. // Allow any (other) SourceCharacter.
  1117. return { { .code_point = (u32)skip(), .is_character_class = false } };
  1118. };
  1119. auto read_class_atom = [&]() -> Optional<CharClassRangeElement> {
  1120. if (match(TokenType::HyphenMinus)) {
  1121. consume();
  1122. return { { .code_point = '-', .is_character_class = false } };
  1123. }
  1124. return read_class_atom_no_dash();
  1125. };
  1126. while (!match(TokenType::RightBracket)) {
  1127. if (match(TokenType::Eof)) {
  1128. set_error(Error::MismatchingBracket);
  1129. return false;
  1130. }
  1131. auto first_atom = read_class_atom();
  1132. if (!first_atom.has_value())
  1133. return false;
  1134. if (match(TokenType::HyphenMinus)) {
  1135. consume();
  1136. if (match(TokenType::RightBracket)) {
  1137. // Allow '-' as the last element in a charclass, even after an atom.
  1138. m_parser_state.lexer.back(2); // -]
  1139. m_parser_state.current_token = m_parser_state.lexer.next();
  1140. goto read_as_single_atom;
  1141. }
  1142. auto second_atom = read_class_atom();
  1143. if (!second_atom.has_value())
  1144. return false;
  1145. if (first_atom.value().is_character_class || second_atom.value().is_character_class) {
  1146. set_error(Error::InvalidRange);
  1147. return false;
  1148. }
  1149. if (first_atom.value().code_point > second_atom.value().code_point) {
  1150. set_error(Error::InvalidRange);
  1151. return false;
  1152. }
  1153. ASSERT(!first_atom.value().is_negated);
  1154. ASSERT(!second_atom.value().is_negated);
  1155. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::CharRange, CharRange { first_atom.value().code_point, second_atom.value().code_point } });
  1156. continue;
  1157. }
  1158. read_as_single_atom:;
  1159. auto atom = first_atom.value();
  1160. if (atom.is_character_class) {
  1161. if (atom.is_negated)
  1162. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::TemporaryInverse, 0 });
  1163. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::CharClass, (ByteCodeValueType)first_atom.value().character_class });
  1164. } else {
  1165. ASSERT(!atom.is_negated);
  1166. ranges.empend(CompareTypeAndValuePair { CharacterCompareType::Char, first_atom.value().code_point });
  1167. }
  1168. }
  1169. consume(TokenType::RightBracket, Error::MismatchingBracket);
  1170. return true;
  1171. }
  1172. StringView ECMA262Parser::read_capture_group_specifier(bool take_starting_angle_bracket)
  1173. {
  1174. if (take_starting_angle_bracket && !consume("<"))
  1175. return {};
  1176. auto start_token = m_parser_state.current_token;
  1177. size_t offset = 0;
  1178. while (match(TokenType::Char)) {
  1179. auto c = m_parser_state.current_token.value();
  1180. if (c == ">")
  1181. break;
  1182. offset += consume().value().length();
  1183. }
  1184. StringView name { start_token.value().characters_without_null_termination(), offset };
  1185. if (!consume(">") || name.is_empty())
  1186. set_error(Error::InvalidNameForCaptureGroup);
  1187. return name;
  1188. }
  1189. bool ECMA262Parser::parse_capture_group(ByteCode& stack, size_t& match_length_minimum, bool unicode, bool named)
  1190. {
  1191. consume(TokenType::LeftParen, Error::InvalidPattern);
  1192. if (match(TokenType::Questionmark)) {
  1193. // Non-capturing group or group with specifier.
  1194. consume();
  1195. if (match(TokenType::Colon)) {
  1196. consume();
  1197. ByteCode noncapture_group_bytecode;
  1198. size_t length = 0;
  1199. if (!parse_disjunction(noncapture_group_bytecode, length, unicode, named))
  1200. return set_error(Error::InvalidPattern);
  1201. consume(TokenType::RightParen, Error::MismatchingParen);
  1202. stack.append(move(noncapture_group_bytecode));
  1203. match_length_minimum += length;
  1204. return true;
  1205. }
  1206. if (consume("<")) {
  1207. ++m_parser_state.named_capture_groups_count;
  1208. auto name = read_capture_group_specifier();
  1209. if (name.is_empty()) {
  1210. set_error(Error::InvalidNameForCaptureGroup);
  1211. return false;
  1212. }
  1213. ByteCode capture_group_bytecode;
  1214. size_t length = 0;
  1215. if (!parse_disjunction(capture_group_bytecode, length, unicode, named))
  1216. return set_error(Error::InvalidPattern);
  1217. consume(TokenType::RightParen, Error::MismatchingParen);
  1218. stack.insert_bytecode_group_capture_left(name);
  1219. stack.append(move(capture_group_bytecode));
  1220. stack.insert_bytecode_group_capture_right(name);
  1221. match_length_minimum += length;
  1222. m_parser_state.named_capture_group_minimum_lengths.set(name, length);
  1223. return true;
  1224. }
  1225. set_error(Error::InvalidCaptureGroup);
  1226. return false;
  1227. }
  1228. auto group_index = ++m_parser_state.capture_groups_count;
  1229. stack.insert_bytecode_group_capture_left(group_index);
  1230. ByteCode capture_group_bytecode;
  1231. size_t length = 0;
  1232. if (!parse_disjunction(capture_group_bytecode, length, unicode, named))
  1233. return set_error(Error::InvalidPattern);
  1234. stack.append(move(capture_group_bytecode));
  1235. m_parser_state.capture_group_minimum_lengths.set(group_index, length);
  1236. consume(TokenType::RightParen, Error::MismatchingParen);
  1237. stack.insert_bytecode_group_capture_right(group_index);
  1238. match_length_minimum += length;
  1239. return true;
  1240. }
  1241. }