Parser.cpp 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@gmx.de>
  3. * Copyright (c) 2020, Linus Groh <mail@linusgroh.de>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "Parser.h"
  28. #include <AK/ScopeGuard.h>
  29. #include <AK/StdLibExtras.h>
  30. #include <AK/TemporaryChange.h>
  31. #include <ctype.h>
  32. namespace JS {
  33. static bool statement_is_use_strict_directive(NonnullRefPtr<Statement> statement)
  34. {
  35. if (!statement->is_expression_statement())
  36. return false;
  37. auto& expression_statement = static_cast<ExpressionStatement&>(*statement);
  38. auto& expression = expression_statement.expression();
  39. if (!expression.is_string_literal())
  40. return false;
  41. return static_cast<const StringLiteral&>(expression).is_use_strict_directive();
  42. }
  43. class ScopePusher {
  44. public:
  45. enum Type {
  46. Var = 1,
  47. Let = 2,
  48. Function = 3,
  49. };
  50. ScopePusher(Parser& parser, unsigned mask)
  51. : m_parser(parser)
  52. , m_mask(mask)
  53. {
  54. if (m_mask & Var)
  55. m_parser.m_parser_state.m_var_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  56. if (m_mask & Let)
  57. m_parser.m_parser_state.m_let_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  58. if (m_mask & Function)
  59. m_parser.m_parser_state.m_function_scopes.append(NonnullRefPtrVector<FunctionDeclaration>());
  60. }
  61. ~ScopePusher()
  62. {
  63. if (m_mask & Var)
  64. m_parser.m_parser_state.m_var_scopes.take_last();
  65. if (m_mask & Let)
  66. m_parser.m_parser_state.m_let_scopes.take_last();
  67. if (m_mask & Function)
  68. m_parser.m_parser_state.m_function_scopes.take_last();
  69. }
  70. Parser& m_parser;
  71. unsigned m_mask { 0 };
  72. };
  73. class OperatorPrecedenceTable {
  74. public:
  75. constexpr OperatorPrecedenceTable()
  76. : m_token_precedence()
  77. {
  78. for (size_t i = 0; i < array_size(m_operator_precedence); ++i) {
  79. auto& op = m_operator_precedence[i];
  80. m_token_precedence[static_cast<size_t>(op.token)] = op.precedence;
  81. }
  82. }
  83. constexpr int get(TokenType token) const
  84. {
  85. int p = m_token_precedence[static_cast<size_t>(token)];
  86. if (p == 0) {
  87. warnln("Internal Error: No precedence for operator {}", Token::name(token));
  88. ASSERT_NOT_REACHED();
  89. return -1;
  90. }
  91. return p;
  92. }
  93. private:
  94. int m_token_precedence[cs_num_of_js_tokens];
  95. struct OperatorPrecedence {
  96. TokenType token;
  97. int precedence;
  98. };
  99. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  100. static constexpr const OperatorPrecedence m_operator_precedence[] = {
  101. { TokenType::Period, 20 },
  102. { TokenType::BracketOpen, 20 },
  103. { TokenType::ParenOpen, 20 },
  104. { TokenType::QuestionMarkPeriod, 20 },
  105. { TokenType::New, 19 },
  106. { TokenType::PlusPlus, 18 },
  107. { TokenType::MinusMinus, 18 },
  108. { TokenType::ExclamationMark, 17 },
  109. { TokenType::Tilde, 17 },
  110. { TokenType::Typeof, 17 },
  111. { TokenType::Void, 17 },
  112. { TokenType::Delete, 17 },
  113. { TokenType::Await, 17 },
  114. { TokenType::DoubleAsterisk, 16 },
  115. { TokenType::Asterisk, 15 },
  116. { TokenType::Slash, 15 },
  117. { TokenType::Percent, 15 },
  118. { TokenType::Plus, 14 },
  119. { TokenType::Minus, 14 },
  120. { TokenType::ShiftLeft, 13 },
  121. { TokenType::ShiftRight, 13 },
  122. { TokenType::UnsignedShiftRight, 13 },
  123. { TokenType::LessThan, 12 },
  124. { TokenType::LessThanEquals, 12 },
  125. { TokenType::GreaterThan, 12 },
  126. { TokenType::GreaterThanEquals, 12 },
  127. { TokenType::In, 12 },
  128. { TokenType::Instanceof, 12 },
  129. { TokenType::EqualsEquals, 11 },
  130. { TokenType::ExclamationMarkEquals, 11 },
  131. { TokenType::EqualsEqualsEquals, 11 },
  132. { TokenType::ExclamationMarkEqualsEquals, 11 },
  133. { TokenType::Ampersand, 10 },
  134. { TokenType::Caret, 9 },
  135. { TokenType::Pipe, 8 },
  136. { TokenType::DoubleQuestionMark, 7 },
  137. { TokenType::DoubleAmpersand, 6 },
  138. { TokenType::DoublePipe, 5 },
  139. { TokenType::QuestionMark, 4 },
  140. { TokenType::Equals, 3 },
  141. { TokenType::PlusEquals, 3 },
  142. { TokenType::MinusEquals, 3 },
  143. { TokenType::DoubleAsteriskEquals, 3 },
  144. { TokenType::AsteriskEquals, 3 },
  145. { TokenType::SlashEquals, 3 },
  146. { TokenType::PercentEquals, 3 },
  147. { TokenType::ShiftLeftEquals, 3 },
  148. { TokenType::ShiftRightEquals, 3 },
  149. { TokenType::UnsignedShiftRightEquals, 3 },
  150. { TokenType::AmpersandEquals, 3 },
  151. { TokenType::CaretEquals, 3 },
  152. { TokenType::PipeEquals, 3 },
  153. { TokenType::DoubleAmpersandEquals, 3 },
  154. { TokenType::DoublePipeEquals, 3 },
  155. { TokenType::DoubleQuestionMarkEquals, 3 },
  156. { TokenType::Yield, 2 },
  157. { TokenType::Comma, 1 },
  158. };
  159. };
  160. constexpr OperatorPrecedenceTable g_operator_precedence;
  161. Parser::ParserState::ParserState(Lexer lexer)
  162. : m_lexer(move(lexer))
  163. , m_current_token(m_lexer.next())
  164. {
  165. }
  166. Parser::Parser(Lexer lexer)
  167. : m_parser_state(move(lexer))
  168. {
  169. }
  170. Associativity Parser::operator_associativity(TokenType type) const
  171. {
  172. switch (type) {
  173. case TokenType::Period:
  174. case TokenType::BracketOpen:
  175. case TokenType::ParenOpen:
  176. case TokenType::QuestionMarkPeriod:
  177. case TokenType::Asterisk:
  178. case TokenType::Slash:
  179. case TokenType::Percent:
  180. case TokenType::Plus:
  181. case TokenType::Minus:
  182. case TokenType::ShiftLeft:
  183. case TokenType::ShiftRight:
  184. case TokenType::UnsignedShiftRight:
  185. case TokenType::LessThan:
  186. case TokenType::LessThanEquals:
  187. case TokenType::GreaterThan:
  188. case TokenType::GreaterThanEquals:
  189. case TokenType::In:
  190. case TokenType::Instanceof:
  191. case TokenType::EqualsEquals:
  192. case TokenType::ExclamationMarkEquals:
  193. case TokenType::EqualsEqualsEquals:
  194. case TokenType::ExclamationMarkEqualsEquals:
  195. case TokenType::Typeof:
  196. case TokenType::Void:
  197. case TokenType::Delete:
  198. case TokenType::Ampersand:
  199. case TokenType::Caret:
  200. case TokenType::Pipe:
  201. case TokenType::DoubleQuestionMark:
  202. case TokenType::DoubleAmpersand:
  203. case TokenType::DoublePipe:
  204. case TokenType::Comma:
  205. return Associativity::Left;
  206. default:
  207. return Associativity::Right;
  208. }
  209. }
  210. NonnullRefPtr<Program> Parser::parse_program()
  211. {
  212. ScopePusher scope(*this, ScopePusher::Var | ScopePusher::Let | ScopePusher::Function);
  213. auto program = adopt(*new Program);
  214. bool first = true;
  215. while (!done()) {
  216. if (match_declaration()) {
  217. program->append(parse_declaration());
  218. } else if (match_statement()) {
  219. auto statement = parse_statement();
  220. program->append(statement);
  221. if (statement_is_use_strict_directive(statement)) {
  222. if (first) {
  223. program->set_strict_mode();
  224. m_parser_state.m_strict_mode = true;
  225. }
  226. if (m_parser_state.m_string_legacy_octal_escape_sequence_in_scope)
  227. syntax_error("Octal escape sequence in string literal not allowed in strict mode");
  228. }
  229. } else {
  230. expected("statement or declaration");
  231. consume();
  232. }
  233. first = false;
  234. }
  235. if (m_parser_state.m_var_scopes.size() == 1) {
  236. program->add_variables(m_parser_state.m_var_scopes.last());
  237. program->add_variables(m_parser_state.m_let_scopes.last());
  238. program->add_functions(m_parser_state.m_function_scopes.last());
  239. } else {
  240. syntax_error("Unclosed scope");
  241. }
  242. return program;
  243. }
  244. NonnullRefPtr<Declaration> Parser::parse_declaration()
  245. {
  246. switch (m_parser_state.m_current_token.type()) {
  247. case TokenType::Class:
  248. return parse_class_declaration();
  249. case TokenType::Function: {
  250. auto declaration = parse_function_node<FunctionDeclaration>();
  251. m_parser_state.m_function_scopes.last().append(declaration);
  252. return declaration;
  253. }
  254. case TokenType::Let:
  255. case TokenType::Const:
  256. return parse_variable_declaration();
  257. default:
  258. expected("declaration");
  259. consume();
  260. return create_ast_node<ErrorDeclaration>();
  261. }
  262. }
  263. NonnullRefPtr<Statement> Parser::parse_statement()
  264. {
  265. switch (m_parser_state.m_current_token.type()) {
  266. case TokenType::CurlyOpen:
  267. return parse_block_statement();
  268. case TokenType::Return:
  269. return parse_return_statement();
  270. case TokenType::Var:
  271. return parse_variable_declaration();
  272. case TokenType::For:
  273. return parse_for_statement();
  274. case TokenType::If:
  275. return parse_if_statement();
  276. case TokenType::Throw:
  277. return parse_throw_statement();
  278. case TokenType::Try:
  279. return parse_try_statement();
  280. case TokenType::Break:
  281. return parse_break_statement();
  282. case TokenType::Continue:
  283. return parse_continue_statement();
  284. case TokenType::Switch:
  285. return parse_switch_statement();
  286. case TokenType::Do:
  287. return parse_do_while_statement();
  288. case TokenType::While:
  289. return parse_while_statement();
  290. case TokenType::With:
  291. if (m_parser_state.m_strict_mode)
  292. syntax_error("'with' statement not allowed in strict mode");
  293. return parse_with_statement();
  294. case TokenType::Debugger:
  295. return parse_debugger_statement();
  296. case TokenType::Semicolon:
  297. consume();
  298. return create_ast_node<EmptyStatement>();
  299. default:
  300. if (match(TokenType::Identifier)) {
  301. auto result = try_parse_labelled_statement();
  302. if (!result.is_null())
  303. return result.release_nonnull();
  304. }
  305. if (match_expression()) {
  306. if (match(TokenType::Function))
  307. syntax_error("Function declaration not allowed in single-statement context");
  308. auto expr = parse_expression(0);
  309. consume_or_insert_semicolon();
  310. return create_ast_node<ExpressionStatement>(move(expr));
  311. }
  312. expected("statement");
  313. consume();
  314. return create_ast_node<ErrorStatement>();
  315. }
  316. }
  317. RefPtr<FunctionExpression> Parser::try_parse_arrow_function_expression(bool expect_parens)
  318. {
  319. save_state();
  320. m_parser_state.m_var_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  321. ArmedScopeGuard state_rollback_guard = [&] {
  322. m_parser_state.m_var_scopes.take_last();
  323. load_state();
  324. };
  325. Vector<FunctionNode::Parameter> parameters;
  326. i32 function_length = -1;
  327. if (expect_parens) {
  328. // We have parens around the function parameters and can re-use the same parsing
  329. // logic used for regular functions: multiple parameters, default values, rest
  330. // parameter, maybe a trailing comma. If we have a new syntax error afterwards we
  331. // check if it's about a wrong token (something like duplicate parameter name must
  332. // not abort), know parsing failed and rollback the parser state.
  333. auto previous_syntax_errors = m_parser_state.m_errors.size();
  334. parameters = parse_function_parameters(function_length, FunctionNodeParseOptions::IsArrowFunction);
  335. if (m_parser_state.m_errors.size() > previous_syntax_errors && m_parser_state.m_errors[previous_syntax_errors].message.starts_with("Unexpected token"))
  336. return nullptr;
  337. if (!match(TokenType::ParenClose))
  338. return nullptr;
  339. consume();
  340. } else {
  341. // No parens - this must be an identifier followed by arrow. That's it.
  342. if (!match(TokenType::Identifier))
  343. return nullptr;
  344. parameters.append({ consume().value(), {} });
  345. }
  346. // If there's a newline between the closing paren and arrow it's not a valid arrow function,
  347. // ASI should kick in instead (it'll then fail with "Unexpected token Arrow")
  348. if (m_parser_state.m_current_token.trivia_contains_line_terminator())
  349. return nullptr;
  350. if (!match(TokenType::Arrow))
  351. return nullptr;
  352. consume();
  353. if (function_length == -1)
  354. function_length = parameters.size();
  355. auto old_labels_in_scope = move(m_parser_state.m_labels_in_scope);
  356. ScopeGuard guard([&]() {
  357. m_parser_state.m_labels_in_scope = move(old_labels_in_scope);
  358. });
  359. bool is_strict = false;
  360. auto function_body_result = [&]() -> RefPtr<BlockStatement> {
  361. TemporaryChange change(m_parser_state.m_in_arrow_function_context, true);
  362. if (match(TokenType::CurlyOpen)) {
  363. // Parse a function body with statements
  364. return parse_block_statement(is_strict);
  365. }
  366. if (match_expression()) {
  367. // Parse a function body which returns a single expression
  368. // FIXME: We synthesize a block with a return statement
  369. // for arrow function bodies which are a single expression.
  370. // Esprima generates a single "ArrowFunctionExpression"
  371. // with a "body" property.
  372. auto return_expression = parse_expression(2);
  373. auto return_block = create_ast_node<BlockStatement>();
  374. return_block->append<ReturnStatement>(move(return_expression));
  375. return return_block;
  376. }
  377. // Invalid arrow function body
  378. return nullptr;
  379. }();
  380. if (!function_body_result.is_null()) {
  381. state_rollback_guard.disarm();
  382. auto body = function_body_result.release_nonnull();
  383. return create_ast_node<FunctionExpression>("", move(body), move(parameters), function_length, m_parser_state.m_var_scopes.take_last(), is_strict, true);
  384. }
  385. return nullptr;
  386. }
  387. RefPtr<Statement> Parser::try_parse_labelled_statement()
  388. {
  389. save_state();
  390. ArmedScopeGuard state_rollback_guard = [&] {
  391. load_state();
  392. };
  393. auto identifier = consume(TokenType::Identifier).value();
  394. if (!match(TokenType::Colon))
  395. return {};
  396. consume(TokenType::Colon);
  397. if (!match_statement())
  398. return {};
  399. m_parser_state.m_labels_in_scope.set(identifier);
  400. auto statement = parse_statement();
  401. m_parser_state.m_labels_in_scope.remove(identifier);
  402. statement->set_label(identifier);
  403. state_rollback_guard.disarm();
  404. return statement;
  405. }
  406. RefPtr<MetaProperty> Parser::try_parse_new_target_expression()
  407. {
  408. save_state();
  409. ArmedScopeGuard state_rollback_guard = [&] {
  410. load_state();
  411. };
  412. consume(TokenType::New);
  413. if (!match(TokenType::Period))
  414. return {};
  415. consume();
  416. if (!match(TokenType::Identifier))
  417. return {};
  418. if (consume().value() != "target")
  419. return {};
  420. state_rollback_guard.disarm();
  421. return create_ast_node<MetaProperty>(MetaProperty::Type::NewTarget);
  422. }
  423. NonnullRefPtr<ClassDeclaration> Parser::parse_class_declaration()
  424. {
  425. return create_ast_node<ClassDeclaration>(parse_class_expression(true));
  426. }
  427. NonnullRefPtr<ClassExpression> Parser::parse_class_expression(bool expect_class_name)
  428. {
  429. // Classes are always in strict mode.
  430. TemporaryChange strict_mode_rollback(m_parser_state.m_strict_mode, true);
  431. consume(TokenType::Class);
  432. NonnullRefPtrVector<ClassMethod> methods;
  433. RefPtr<Expression> super_class;
  434. RefPtr<FunctionExpression> constructor;
  435. String class_name = expect_class_name || match(TokenType::Identifier) ? consume(TokenType::Identifier).value().to_string() : "";
  436. if (match(TokenType::Extends)) {
  437. consume();
  438. super_class = parse_primary_expression();
  439. }
  440. consume(TokenType::CurlyOpen);
  441. while (!done() && !match(TokenType::CurlyClose)) {
  442. RefPtr<Expression> property_key;
  443. bool is_static = false;
  444. bool is_constructor = false;
  445. auto method_kind = ClassMethod::Kind::Method;
  446. if (match(TokenType::Semicolon)) {
  447. consume();
  448. continue;
  449. }
  450. if (match_property_key()) {
  451. StringView name;
  452. if (match(TokenType::Identifier) && m_parser_state.m_current_token.value() == "static") {
  453. consume();
  454. is_static = true;
  455. }
  456. if (match(TokenType::Identifier)) {
  457. auto identifier_name = m_parser_state.m_current_token.value();
  458. if (identifier_name == "get") {
  459. method_kind = ClassMethod::Kind::Getter;
  460. consume();
  461. } else if (identifier_name == "set") {
  462. method_kind = ClassMethod::Kind::Setter;
  463. consume();
  464. }
  465. }
  466. if (match_property_key()) {
  467. switch (m_parser_state.m_current_token.type()) {
  468. case TokenType::Identifier:
  469. name = consume().value();
  470. property_key = create_ast_node<StringLiteral>(name);
  471. break;
  472. case TokenType::StringLiteral: {
  473. auto string_literal = parse_string_literal(consume());
  474. name = string_literal->value();
  475. property_key = move(string_literal);
  476. break;
  477. }
  478. default:
  479. property_key = parse_property_key();
  480. break;
  481. }
  482. } else {
  483. expected("property key");
  484. }
  485. // Constructor may be a StringLiteral or an Identifier.
  486. if (!is_static && name == "constructor") {
  487. if (method_kind != ClassMethod::Kind::Method)
  488. syntax_error("Class constructor may not be an accessor");
  489. if (!constructor.is_null())
  490. syntax_error("Classes may not have more than one constructor");
  491. is_constructor = true;
  492. }
  493. }
  494. if (match(TokenType::ParenOpen)) {
  495. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  496. if (!super_class.is_null())
  497. parse_options |= FunctionNodeParseOptions::AllowSuperConstructorCall;
  498. if (method_kind == ClassMethod::Kind::Getter)
  499. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  500. if (method_kind == ClassMethod::Kind::Setter)
  501. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  502. auto function = parse_function_node<FunctionExpression>(parse_options);
  503. if (is_constructor) {
  504. constructor = move(function);
  505. } else if (!property_key.is_null()) {
  506. methods.append(create_ast_node<ClassMethod>(property_key.release_nonnull(), move(function), method_kind, is_static));
  507. } else {
  508. syntax_error("No key for class method");
  509. }
  510. } else {
  511. expected("ParenOpen");
  512. consume();
  513. }
  514. }
  515. consume(TokenType::CurlyClose);
  516. if (constructor.is_null()) {
  517. auto constructor_body = create_ast_node<BlockStatement>();
  518. if (!super_class.is_null()) {
  519. // Set constructor to the result of parsing the source text
  520. // constructor(... args){ super (...args);}
  521. auto super_call = create_ast_node<CallExpression>(create_ast_node<SuperExpression>(), Vector { CallExpression::Argument { create_ast_node<Identifier>("args"), true } });
  522. constructor_body->append(create_ast_node<ExpressionStatement>(move(super_call)));
  523. constructor_body->add_variables(m_parser_state.m_var_scopes.last());
  524. constructor = create_ast_node<FunctionExpression>(class_name, move(constructor_body), Vector { FunctionNode::Parameter { "args", nullptr, true } }, 0, NonnullRefPtrVector<VariableDeclaration>(), true);
  525. } else {
  526. constructor = create_ast_node<FunctionExpression>(class_name, move(constructor_body), Vector<FunctionNode::Parameter> {}, 0, NonnullRefPtrVector<VariableDeclaration>(), true);
  527. }
  528. }
  529. return create_ast_node<ClassExpression>(move(class_name), move(constructor), move(super_class), move(methods));
  530. }
  531. NonnullRefPtr<Expression> Parser::parse_primary_expression()
  532. {
  533. if (match_unary_prefixed_expression())
  534. return parse_unary_prefixed_expression();
  535. switch (m_parser_state.m_current_token.type()) {
  536. case TokenType::ParenOpen: {
  537. consume(TokenType::ParenOpen);
  538. if (match(TokenType::ParenClose) || match(TokenType::Identifier) || match(TokenType::TripleDot)) {
  539. auto arrow_function_result = try_parse_arrow_function_expression(true);
  540. if (!arrow_function_result.is_null())
  541. return arrow_function_result.release_nonnull();
  542. }
  543. auto expression = parse_expression(0);
  544. consume(TokenType::ParenClose);
  545. return expression;
  546. }
  547. case TokenType::This:
  548. consume();
  549. return create_ast_node<ThisExpression>();
  550. case TokenType::Class:
  551. return parse_class_expression(false);
  552. case TokenType::Super:
  553. consume();
  554. if (!m_parser_state.m_allow_super_property_lookup)
  555. syntax_error("'super' keyword unexpected here");
  556. return create_ast_node<SuperExpression>();
  557. case TokenType::Identifier: {
  558. auto arrow_function_result = try_parse_arrow_function_expression(false);
  559. if (!arrow_function_result.is_null())
  560. return arrow_function_result.release_nonnull();
  561. return create_ast_node<Identifier>(consume().value());
  562. }
  563. case TokenType::NumericLiteral:
  564. return create_ast_node<NumericLiteral>(consume_and_validate_numeric_literal().double_value());
  565. case TokenType::BigIntLiteral:
  566. return create_ast_node<BigIntLiteral>(consume().value());
  567. case TokenType::BoolLiteral:
  568. return create_ast_node<BooleanLiteral>(consume().bool_value());
  569. case TokenType::StringLiteral:
  570. return parse_string_literal(consume());
  571. case TokenType::NullLiteral:
  572. consume();
  573. return create_ast_node<NullLiteral>();
  574. case TokenType::CurlyOpen:
  575. return parse_object_expression();
  576. case TokenType::Function:
  577. return parse_function_node<FunctionExpression>();
  578. case TokenType::BracketOpen:
  579. return parse_array_expression();
  580. case TokenType::RegexLiteral:
  581. return parse_regexp_literal();
  582. case TokenType::TemplateLiteralStart:
  583. return parse_template_literal(false);
  584. case TokenType::New: {
  585. auto new_start = position();
  586. auto new_target_result = try_parse_new_target_expression();
  587. if (!new_target_result.is_null()) {
  588. if (!m_parser_state.m_in_function_context)
  589. syntax_error("'new.target' not allowed outside of a function", new_start);
  590. return new_target_result.release_nonnull();
  591. }
  592. return parse_new_expression();
  593. }
  594. default:
  595. expected("primary expression");
  596. consume();
  597. return create_ast_node<ErrorExpression>();
  598. }
  599. }
  600. NonnullRefPtr<RegExpLiteral> Parser::parse_regexp_literal()
  601. {
  602. auto content = consume().value();
  603. auto flags = match(TokenType::RegexFlags) ? consume().value() : "";
  604. return create_ast_node<RegExpLiteral>(content.substring_view(1, content.length() - 2), flags);
  605. }
  606. NonnullRefPtr<Expression> Parser::parse_unary_prefixed_expression()
  607. {
  608. auto precedence = g_operator_precedence.get(m_parser_state.m_current_token.type());
  609. auto associativity = operator_associativity(m_parser_state.m_current_token.type());
  610. switch (m_parser_state.m_current_token.type()) {
  611. case TokenType::PlusPlus: {
  612. consume();
  613. auto rhs_start = position();
  614. auto rhs = parse_expression(precedence, associativity);
  615. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  616. // other engines throw ReferenceError for ++foo()
  617. if (!rhs->is_identifier() && !rhs->is_member_expression())
  618. syntax_error(String::formatted("Right-hand side of prefix increment operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  619. return create_ast_node<UpdateExpression>(UpdateOp::Increment, move(rhs), true);
  620. }
  621. case TokenType::MinusMinus: {
  622. consume();
  623. auto rhs_start = position();
  624. auto rhs = parse_expression(precedence, associativity);
  625. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  626. // other engines throw ReferenceError for --foo()
  627. if (!rhs->is_identifier() && !rhs->is_member_expression())
  628. syntax_error(String::formatted("Right-hand side of prefix decrement operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  629. return create_ast_node<UpdateExpression>(UpdateOp::Decrement, move(rhs), true);
  630. }
  631. case TokenType::ExclamationMark:
  632. consume();
  633. return create_ast_node<UnaryExpression>(UnaryOp::Not, parse_expression(precedence, associativity));
  634. case TokenType::Tilde:
  635. consume();
  636. return create_ast_node<UnaryExpression>(UnaryOp::BitwiseNot, parse_expression(precedence, associativity));
  637. case TokenType::Plus:
  638. consume();
  639. return create_ast_node<UnaryExpression>(UnaryOp::Plus, parse_expression(precedence, associativity));
  640. case TokenType::Minus:
  641. consume();
  642. return create_ast_node<UnaryExpression>(UnaryOp::Minus, parse_expression(precedence, associativity));
  643. case TokenType::Typeof:
  644. consume();
  645. return create_ast_node<UnaryExpression>(UnaryOp::Typeof, parse_expression(precedence, associativity));
  646. case TokenType::Void:
  647. consume();
  648. return create_ast_node<UnaryExpression>(UnaryOp::Void, parse_expression(precedence, associativity));
  649. case TokenType::Delete:
  650. consume();
  651. return create_ast_node<UnaryExpression>(UnaryOp::Delete, parse_expression(precedence, associativity));
  652. default:
  653. expected("primary expression");
  654. consume();
  655. return create_ast_node<ErrorExpression>();
  656. }
  657. }
  658. NonnullRefPtr<Expression> Parser::parse_property_key()
  659. {
  660. if (match(TokenType::StringLiteral)) {
  661. return parse_string_literal(consume());
  662. } else if (match(TokenType::NumericLiteral)) {
  663. // FIXME: "evaluate" key to double value, see https://github.com/SerenityOS/serenity/issues/3717
  664. return create_ast_node<StringLiteral>(consume_and_validate_numeric_literal().value());
  665. } else if (match(TokenType::BigIntLiteral)) {
  666. auto value = consume(TokenType::BigIntLiteral).value();
  667. return create_ast_node<StringLiteral>(value.substring_view(0, value.length() - 1));
  668. } else if (match(TokenType::BracketOpen)) {
  669. consume(TokenType::BracketOpen);
  670. auto result = parse_expression(0);
  671. consume(TokenType::BracketClose);
  672. return result;
  673. } else {
  674. if (!match_identifier_name())
  675. expected("IdentifierName");
  676. return create_ast_node<StringLiteral>(consume().value());
  677. }
  678. }
  679. NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
  680. {
  681. consume(TokenType::CurlyOpen);
  682. NonnullRefPtrVector<ObjectProperty> properties;
  683. ObjectProperty::Type property_type;
  684. auto skip_to_next_property = [&] {
  685. while (!done() && !match(TokenType::Comma) && !match(TokenType::CurlyOpen))
  686. consume();
  687. };
  688. while (!done() && !match(TokenType::CurlyClose)) {
  689. property_type = ObjectProperty::Type::KeyValue;
  690. RefPtr<Expression> property_name;
  691. RefPtr<Expression> property_value;
  692. if (match(TokenType::TripleDot)) {
  693. consume();
  694. property_name = parse_expression(4);
  695. properties.append(create_ast_node<ObjectProperty>(*property_name, nullptr, ObjectProperty::Type::Spread, false));
  696. if (!match(TokenType::Comma))
  697. break;
  698. consume(TokenType::Comma);
  699. continue;
  700. }
  701. if (match(TokenType::Identifier)) {
  702. auto identifier = consume().value();
  703. if (identifier == "get" && match_property_key()) {
  704. property_type = ObjectProperty::Type::Getter;
  705. property_name = parse_property_key();
  706. } else if (identifier == "set" && match_property_key()) {
  707. property_type = ObjectProperty::Type::Setter;
  708. property_name = parse_property_key();
  709. } else {
  710. property_name = create_ast_node<StringLiteral>(identifier);
  711. property_value = create_ast_node<Identifier>(identifier);
  712. }
  713. } else {
  714. property_name = parse_property_key();
  715. }
  716. if (property_type == ObjectProperty::Type::Getter || property_type == ObjectProperty::Type::Setter) {
  717. if (!match(TokenType::ParenOpen)) {
  718. syntax_error("Expected '(' for object getter or setter property");
  719. skip_to_next_property();
  720. continue;
  721. }
  722. }
  723. if (match(TokenType::ParenOpen)) {
  724. ASSERT(property_name);
  725. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  726. if (property_type == ObjectProperty::Type::Getter)
  727. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  728. if (property_type == ObjectProperty::Type::Setter)
  729. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  730. auto function = parse_function_node<FunctionExpression>(parse_options);
  731. properties.append(create_ast_node<ObjectProperty>(*property_name, function, property_type, true));
  732. } else if (match(TokenType::Colon)) {
  733. if (!property_name) {
  734. syntax_error("Expected a property name");
  735. skip_to_next_property();
  736. continue;
  737. }
  738. consume();
  739. properties.append(create_ast_node<ObjectProperty>(*property_name, parse_expression(2), property_type, false));
  740. } else if (property_name && property_value) {
  741. properties.append(create_ast_node<ObjectProperty>(*property_name, *property_value, property_type, false));
  742. } else {
  743. syntax_error("Expected a property");
  744. skip_to_next_property();
  745. continue;
  746. }
  747. if (!match(TokenType::Comma))
  748. break;
  749. consume(TokenType::Comma);
  750. }
  751. consume(TokenType::CurlyClose);
  752. return create_ast_node<ObjectExpression>(properties);
  753. }
  754. NonnullRefPtr<ArrayExpression> Parser::parse_array_expression()
  755. {
  756. consume(TokenType::BracketOpen);
  757. Vector<RefPtr<Expression>> elements;
  758. while (match_expression() || match(TokenType::TripleDot) || match(TokenType::Comma)) {
  759. RefPtr<Expression> expression;
  760. if (match(TokenType::TripleDot)) {
  761. consume(TokenType::TripleDot);
  762. expression = create_ast_node<SpreadExpression>(parse_expression(2));
  763. } else if (match_expression()) {
  764. expression = parse_expression(2);
  765. }
  766. elements.append(expression);
  767. if (!match(TokenType::Comma))
  768. break;
  769. consume(TokenType::Comma);
  770. }
  771. consume(TokenType::BracketClose);
  772. return create_ast_node<ArrayExpression>(move(elements));
  773. }
  774. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(Token token, bool in_template_literal)
  775. {
  776. auto status = Token::StringValueStatus::Ok;
  777. auto string = token.string_value(status);
  778. if (status != Token::StringValueStatus::Ok) {
  779. String message;
  780. if (status == Token::StringValueStatus::LegacyOctalEscapeSequence) {
  781. m_parser_state.m_string_legacy_octal_escape_sequence_in_scope = true;
  782. if (in_template_literal)
  783. message = "Octal escape sequence not allowed in template literal";
  784. else if (m_parser_state.m_strict_mode)
  785. message = "Octal escape sequence in string literal not allowed in strict mode";
  786. } else if (status == Token::StringValueStatus::MalformedHexEscape || status == Token::StringValueStatus::MalformedUnicodeEscape) {
  787. auto type = status == Token::StringValueStatus::MalformedUnicodeEscape ? "unicode" : "hexadecimal";
  788. message = String::formatted("Malformed {} escape sequence", type);
  789. } else if (status == Token::StringValueStatus::UnicodeEscapeOverflow) {
  790. message = "Unicode code_point must not be greater than 0x10ffff in escape sequence";
  791. } else {
  792. ASSERT_NOT_REACHED();
  793. }
  794. if (!message.is_empty())
  795. syntax_error(message, Position { token.line_number(), token.line_column() });
  796. }
  797. auto is_use_strict_directive = !in_template_literal && (token.value() == "'use strict'" || token.value() == "\"use strict\"");
  798. return create_ast_node<StringLiteral>(string, is_use_strict_directive);
  799. }
  800. NonnullRefPtr<TemplateLiteral> Parser::parse_template_literal(bool is_tagged)
  801. {
  802. consume(TokenType::TemplateLiteralStart);
  803. NonnullRefPtrVector<Expression> expressions;
  804. NonnullRefPtrVector<Expression> raw_strings;
  805. auto append_empty_string = [&expressions, &raw_strings, is_tagged]() {
  806. auto string_literal = create_ast_node<StringLiteral>("");
  807. expressions.append(string_literal);
  808. if (is_tagged)
  809. raw_strings.append(string_literal);
  810. };
  811. if (!match(TokenType::TemplateLiteralString))
  812. append_empty_string();
  813. while (!done() && !match(TokenType::TemplateLiteralEnd) && !match(TokenType::UnterminatedTemplateLiteral)) {
  814. if (match(TokenType::TemplateLiteralString)) {
  815. auto token = consume();
  816. expressions.append(parse_string_literal(token, true));
  817. if (is_tagged)
  818. raw_strings.append(create_ast_node<StringLiteral>(token.value()));
  819. } else if (match(TokenType::TemplateLiteralExprStart)) {
  820. consume(TokenType::TemplateLiteralExprStart);
  821. if (match(TokenType::TemplateLiteralExprEnd)) {
  822. syntax_error("Empty template literal expression block");
  823. return create_ast_node<TemplateLiteral>(expressions);
  824. }
  825. expressions.append(parse_expression(0));
  826. if (match(TokenType::UnterminatedTemplateLiteral)) {
  827. syntax_error("Unterminated template literal");
  828. return create_ast_node<TemplateLiteral>(expressions);
  829. }
  830. consume(TokenType::TemplateLiteralExprEnd);
  831. if (!match(TokenType::TemplateLiteralString))
  832. append_empty_string();
  833. } else {
  834. expected("Template literal string or expression");
  835. break;
  836. }
  837. }
  838. if (match(TokenType::UnterminatedTemplateLiteral)) {
  839. syntax_error("Unterminated template literal");
  840. } else {
  841. consume(TokenType::TemplateLiteralEnd);
  842. }
  843. if (is_tagged)
  844. return create_ast_node<TemplateLiteral>(expressions, raw_strings);
  845. return create_ast_node<TemplateLiteral>(expressions);
  846. }
  847. NonnullRefPtr<Expression> Parser::parse_expression(int min_precedence, Associativity associativity, Vector<TokenType> forbidden)
  848. {
  849. auto expression = parse_primary_expression();
  850. while (match(TokenType::TemplateLiteralStart)) {
  851. auto template_literal = parse_template_literal(true);
  852. expression = create_ast_node<TaggedTemplateLiteral>(move(expression), move(template_literal));
  853. }
  854. while (match_secondary_expression(forbidden)) {
  855. int new_precedence = g_operator_precedence.get(m_parser_state.m_current_token.type());
  856. if (new_precedence < min_precedence)
  857. break;
  858. if (new_precedence == min_precedence && associativity == Associativity::Left)
  859. break;
  860. Associativity new_associativity = operator_associativity(m_parser_state.m_current_token.type());
  861. expression = parse_secondary_expression(move(expression), new_precedence, new_associativity);
  862. while (match(TokenType::TemplateLiteralStart)) {
  863. auto template_literal = parse_template_literal(true);
  864. expression = create_ast_node<TaggedTemplateLiteral>(move(expression), move(template_literal));
  865. }
  866. }
  867. if (match(TokenType::Comma) && min_precedence <= 1) {
  868. NonnullRefPtrVector<Expression> expressions;
  869. expressions.append(expression);
  870. while (match(TokenType::Comma)) {
  871. consume();
  872. expressions.append(parse_expression(2));
  873. }
  874. expression = create_ast_node<SequenceExpression>(move(expressions));
  875. }
  876. return expression;
  877. }
  878. NonnullRefPtr<Expression> Parser::parse_secondary_expression(NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  879. {
  880. switch (m_parser_state.m_current_token.type()) {
  881. case TokenType::Plus:
  882. consume();
  883. return create_ast_node<BinaryExpression>(BinaryOp::Addition, move(lhs), parse_expression(min_precedence, associativity));
  884. case TokenType::PlusEquals:
  885. return parse_assignment_expression(AssignmentOp::AdditionAssignment, move(lhs), min_precedence, associativity);
  886. case TokenType::Minus:
  887. consume();
  888. return create_ast_node<BinaryExpression>(BinaryOp::Subtraction, move(lhs), parse_expression(min_precedence, associativity));
  889. case TokenType::MinusEquals:
  890. return parse_assignment_expression(AssignmentOp::SubtractionAssignment, move(lhs), min_precedence, associativity);
  891. case TokenType::Asterisk:
  892. consume();
  893. return create_ast_node<BinaryExpression>(BinaryOp::Multiplication, move(lhs), parse_expression(min_precedence, associativity));
  894. case TokenType::AsteriskEquals:
  895. return parse_assignment_expression(AssignmentOp::MultiplicationAssignment, move(lhs), min_precedence, associativity);
  896. case TokenType::Slash:
  897. consume();
  898. return create_ast_node<BinaryExpression>(BinaryOp::Division, move(lhs), parse_expression(min_precedence, associativity));
  899. case TokenType::SlashEquals:
  900. return parse_assignment_expression(AssignmentOp::DivisionAssignment, move(lhs), min_precedence, associativity);
  901. case TokenType::Percent:
  902. consume();
  903. return create_ast_node<BinaryExpression>(BinaryOp::Modulo, move(lhs), parse_expression(min_precedence, associativity));
  904. case TokenType::PercentEquals:
  905. return parse_assignment_expression(AssignmentOp::ModuloAssignment, move(lhs), min_precedence, associativity);
  906. case TokenType::DoubleAsterisk:
  907. consume();
  908. return create_ast_node<BinaryExpression>(BinaryOp::Exponentiation, move(lhs), parse_expression(min_precedence, associativity));
  909. case TokenType::DoubleAsteriskEquals:
  910. return parse_assignment_expression(AssignmentOp::ExponentiationAssignment, move(lhs), min_precedence, associativity);
  911. case TokenType::GreaterThan:
  912. consume();
  913. return create_ast_node<BinaryExpression>(BinaryOp::GreaterThan, move(lhs), parse_expression(min_precedence, associativity));
  914. case TokenType::GreaterThanEquals:
  915. consume();
  916. return create_ast_node<BinaryExpression>(BinaryOp::GreaterThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  917. case TokenType::LessThan:
  918. consume();
  919. return create_ast_node<BinaryExpression>(BinaryOp::LessThan, move(lhs), parse_expression(min_precedence, associativity));
  920. case TokenType::LessThanEquals:
  921. consume();
  922. return create_ast_node<BinaryExpression>(BinaryOp::LessThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  923. case TokenType::EqualsEqualsEquals:
  924. consume();
  925. return create_ast_node<BinaryExpression>(BinaryOp::TypedEquals, move(lhs), parse_expression(min_precedence, associativity));
  926. case TokenType::ExclamationMarkEqualsEquals:
  927. consume();
  928. return create_ast_node<BinaryExpression>(BinaryOp::TypedInequals, move(lhs), parse_expression(min_precedence, associativity));
  929. case TokenType::EqualsEquals:
  930. consume();
  931. return create_ast_node<BinaryExpression>(BinaryOp::AbstractEquals, move(lhs), parse_expression(min_precedence, associativity));
  932. case TokenType::ExclamationMarkEquals:
  933. consume();
  934. return create_ast_node<BinaryExpression>(BinaryOp::AbstractInequals, move(lhs), parse_expression(min_precedence, associativity));
  935. case TokenType::In:
  936. consume();
  937. return create_ast_node<BinaryExpression>(BinaryOp::In, move(lhs), parse_expression(min_precedence, associativity));
  938. case TokenType::Instanceof:
  939. consume();
  940. return create_ast_node<BinaryExpression>(BinaryOp::InstanceOf, move(lhs), parse_expression(min_precedence, associativity));
  941. case TokenType::Ampersand:
  942. consume();
  943. return create_ast_node<BinaryExpression>(BinaryOp::BitwiseAnd, move(lhs), parse_expression(min_precedence, associativity));
  944. case TokenType::AmpersandEquals:
  945. return parse_assignment_expression(AssignmentOp::BitwiseAndAssignment, move(lhs), min_precedence, associativity);
  946. case TokenType::Pipe:
  947. consume();
  948. return create_ast_node<BinaryExpression>(BinaryOp::BitwiseOr, move(lhs), parse_expression(min_precedence, associativity));
  949. case TokenType::PipeEquals:
  950. return parse_assignment_expression(AssignmentOp::BitwiseOrAssignment, move(lhs), min_precedence, associativity);
  951. case TokenType::Caret:
  952. consume();
  953. return create_ast_node<BinaryExpression>(BinaryOp::BitwiseXor, move(lhs), parse_expression(min_precedence, associativity));
  954. case TokenType::CaretEquals:
  955. return parse_assignment_expression(AssignmentOp::BitwiseXorAssignment, move(lhs), min_precedence, associativity);
  956. case TokenType::ShiftLeft:
  957. consume();
  958. return create_ast_node<BinaryExpression>(BinaryOp::LeftShift, move(lhs), parse_expression(min_precedence, associativity));
  959. case TokenType::ShiftLeftEquals:
  960. return parse_assignment_expression(AssignmentOp::LeftShiftAssignment, move(lhs), min_precedence, associativity);
  961. case TokenType::ShiftRight:
  962. consume();
  963. return create_ast_node<BinaryExpression>(BinaryOp::RightShift, move(lhs), parse_expression(min_precedence, associativity));
  964. case TokenType::ShiftRightEquals:
  965. return parse_assignment_expression(AssignmentOp::RightShiftAssignment, move(lhs), min_precedence, associativity);
  966. case TokenType::UnsignedShiftRight:
  967. consume();
  968. return create_ast_node<BinaryExpression>(BinaryOp::UnsignedRightShift, move(lhs), parse_expression(min_precedence, associativity));
  969. case TokenType::UnsignedShiftRightEquals:
  970. return parse_assignment_expression(AssignmentOp::UnsignedRightShiftAssignment, move(lhs), min_precedence, associativity);
  971. case TokenType::ParenOpen:
  972. return parse_call_expression(move(lhs));
  973. case TokenType::Equals:
  974. return parse_assignment_expression(AssignmentOp::Assignment, move(lhs), min_precedence, associativity);
  975. case TokenType::Period:
  976. consume();
  977. if (!match_identifier_name())
  978. expected("IdentifierName");
  979. return create_ast_node<MemberExpression>(move(lhs), create_ast_node<Identifier>(consume().value()));
  980. case TokenType::BracketOpen: {
  981. consume(TokenType::BracketOpen);
  982. auto expression = create_ast_node<MemberExpression>(move(lhs), parse_expression(0), true);
  983. consume(TokenType::BracketClose);
  984. return expression;
  985. }
  986. case TokenType::PlusPlus:
  987. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  988. // other engines throw ReferenceError for foo()++
  989. if (!lhs->is_identifier() && !lhs->is_member_expression())
  990. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  991. consume();
  992. return create_ast_node<UpdateExpression>(UpdateOp::Increment, move(lhs));
  993. case TokenType::MinusMinus:
  994. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  995. // other engines throw ReferenceError for foo()--
  996. if (!lhs->is_identifier() && !lhs->is_member_expression())
  997. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  998. consume();
  999. return create_ast_node<UpdateExpression>(UpdateOp::Decrement, move(lhs));
  1000. case TokenType::DoubleAmpersand:
  1001. consume();
  1002. return create_ast_node<LogicalExpression>(LogicalOp::And, move(lhs), parse_expression(min_precedence, associativity));
  1003. case TokenType::DoubleAmpersandEquals:
  1004. return parse_assignment_expression(AssignmentOp::AndAssignment, move(lhs), min_precedence, associativity);
  1005. case TokenType::DoublePipe:
  1006. consume();
  1007. return create_ast_node<LogicalExpression>(LogicalOp::Or, move(lhs), parse_expression(min_precedence, associativity));
  1008. case TokenType::DoublePipeEquals:
  1009. return parse_assignment_expression(AssignmentOp::OrAssignment, move(lhs), min_precedence, associativity);
  1010. case TokenType::DoubleQuestionMark:
  1011. consume();
  1012. return create_ast_node<LogicalExpression>(LogicalOp::NullishCoalescing, move(lhs), parse_expression(min_precedence, associativity));
  1013. case TokenType::DoubleQuestionMarkEquals:
  1014. return parse_assignment_expression(AssignmentOp::NullishAssignment, move(lhs), min_precedence, associativity);
  1015. case TokenType::QuestionMark:
  1016. return parse_conditional_expression(move(lhs));
  1017. default:
  1018. expected("secondary expression");
  1019. consume();
  1020. return create_ast_node<ErrorExpression>();
  1021. }
  1022. }
  1023. NonnullRefPtr<AssignmentExpression> Parser::parse_assignment_expression(AssignmentOp assignment_op, NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  1024. {
  1025. ASSERT(match(TokenType::Equals)
  1026. || match(TokenType::PlusEquals)
  1027. || match(TokenType::MinusEquals)
  1028. || match(TokenType::AsteriskEquals)
  1029. || match(TokenType::SlashEquals)
  1030. || match(TokenType::PercentEquals)
  1031. || match(TokenType::DoubleAsteriskEquals)
  1032. || match(TokenType::AmpersandEquals)
  1033. || match(TokenType::PipeEquals)
  1034. || match(TokenType::CaretEquals)
  1035. || match(TokenType::ShiftLeftEquals)
  1036. || match(TokenType::ShiftRightEquals)
  1037. || match(TokenType::UnsignedShiftRightEquals)
  1038. || match(TokenType::DoubleAmpersandEquals)
  1039. || match(TokenType::DoublePipeEquals)
  1040. || match(TokenType::DoubleQuestionMarkEquals));
  1041. consume();
  1042. if (!lhs->is_identifier() && !lhs->is_member_expression() && !lhs->is_call_expression()) {
  1043. syntax_error("Invalid left-hand side in assignment");
  1044. } else if (m_parser_state.m_strict_mode && lhs->is_identifier()) {
  1045. auto name = static_cast<const Identifier&>(*lhs).string();
  1046. if (name == "eval" || name == "arguments")
  1047. syntax_error(String::formatted("'{}' cannot be assigned to in strict mode code", name));
  1048. } else if (m_parser_state.m_strict_mode && lhs->is_call_expression()) {
  1049. syntax_error("Cannot assign to function call");
  1050. }
  1051. return create_ast_node<AssignmentExpression>(assignment_op, move(lhs), parse_expression(min_precedence, associativity));
  1052. }
  1053. NonnullRefPtr<CallExpression> Parser::parse_call_expression(NonnullRefPtr<Expression> lhs)
  1054. {
  1055. if (!m_parser_state.m_allow_super_constructor_call && lhs->is_super_expression())
  1056. syntax_error("'super' keyword unexpected here");
  1057. consume(TokenType::ParenOpen);
  1058. Vector<CallExpression::Argument> arguments;
  1059. while (match_expression() || match(TokenType::TripleDot)) {
  1060. if (match(TokenType::TripleDot)) {
  1061. consume();
  1062. arguments.append({ parse_expression(2), true });
  1063. } else {
  1064. arguments.append({ parse_expression(2), false });
  1065. }
  1066. if (!match(TokenType::Comma))
  1067. break;
  1068. consume();
  1069. }
  1070. consume(TokenType::ParenClose);
  1071. return create_ast_node<CallExpression>(move(lhs), move(arguments));
  1072. }
  1073. NonnullRefPtr<NewExpression> Parser::parse_new_expression()
  1074. {
  1075. consume(TokenType::New);
  1076. auto callee = parse_expression(g_operator_precedence.get(TokenType::New), Associativity::Right, { TokenType::ParenOpen });
  1077. Vector<CallExpression::Argument> arguments;
  1078. if (match(TokenType::ParenOpen)) {
  1079. consume(TokenType::ParenOpen);
  1080. while (match_expression() || match(TokenType::TripleDot)) {
  1081. if (match(TokenType::TripleDot)) {
  1082. consume();
  1083. arguments.append({ parse_expression(2), true });
  1084. } else {
  1085. arguments.append({ parse_expression(2), false });
  1086. }
  1087. if (!match(TokenType::Comma))
  1088. break;
  1089. consume();
  1090. }
  1091. consume(TokenType::ParenClose);
  1092. }
  1093. return create_ast_node<NewExpression>(move(callee), move(arguments));
  1094. }
  1095. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement()
  1096. {
  1097. if (!m_parser_state.m_in_function_context && !m_parser_state.m_in_arrow_function_context)
  1098. syntax_error("'return' not allowed outside of a function");
  1099. consume(TokenType::Return);
  1100. // Automatic semicolon insertion: terminate statement when return is followed by newline
  1101. if (m_parser_state.m_current_token.trivia_contains_line_terminator())
  1102. return create_ast_node<ReturnStatement>(nullptr);
  1103. if (match_expression()) {
  1104. auto expression = parse_expression(0);
  1105. consume_or_insert_semicolon();
  1106. return create_ast_node<ReturnStatement>(move(expression));
  1107. }
  1108. consume_or_insert_semicolon();
  1109. return create_ast_node<ReturnStatement>(nullptr);
  1110. }
  1111. NonnullRefPtr<BlockStatement> Parser::parse_block_statement()
  1112. {
  1113. bool dummy = false;
  1114. return parse_block_statement(dummy);
  1115. }
  1116. NonnullRefPtr<BlockStatement> Parser::parse_block_statement(bool& is_strict)
  1117. {
  1118. ScopePusher scope(*this, ScopePusher::Let);
  1119. auto block = create_ast_node<BlockStatement>();
  1120. consume(TokenType::CurlyOpen);
  1121. bool first = true;
  1122. bool initial_strict_mode_state = m_parser_state.m_strict_mode;
  1123. if (initial_strict_mode_state)
  1124. is_strict = true;
  1125. while (!done() && !match(TokenType::CurlyClose)) {
  1126. if (match_declaration()) {
  1127. block->append(parse_declaration());
  1128. } else if (match_statement()) {
  1129. auto statement = parse_statement();
  1130. block->append(statement);
  1131. if (statement_is_use_strict_directive(statement)) {
  1132. if (first && !initial_strict_mode_state) {
  1133. is_strict = true;
  1134. m_parser_state.m_strict_mode = true;
  1135. }
  1136. if (m_parser_state.m_string_legacy_octal_escape_sequence_in_scope)
  1137. syntax_error("Octal escape sequence in string literal not allowed in strict mode");
  1138. }
  1139. } else {
  1140. expected("statement or declaration");
  1141. consume();
  1142. }
  1143. first = false;
  1144. }
  1145. m_parser_state.m_strict_mode = initial_strict_mode_state;
  1146. m_parser_state.m_string_legacy_octal_escape_sequence_in_scope = false;
  1147. consume(TokenType::CurlyClose);
  1148. block->add_variables(m_parser_state.m_let_scopes.last());
  1149. block->add_functions(m_parser_state.m_function_scopes.last());
  1150. return block;
  1151. }
  1152. template<typename FunctionNodeType>
  1153. NonnullRefPtr<FunctionNodeType> Parser::parse_function_node(u8 parse_options)
  1154. {
  1155. ASSERT(!(parse_options & FunctionNodeParseOptions::IsGetterFunction && parse_options & FunctionNodeParseOptions::IsSetterFunction));
  1156. TemporaryChange super_property_access_rollback(m_parser_state.m_allow_super_property_lookup, !!(parse_options & FunctionNodeParseOptions::AllowSuperPropertyLookup));
  1157. TemporaryChange super_constructor_call_rollback(m_parser_state.m_allow_super_constructor_call, !!(parse_options & FunctionNodeParseOptions::AllowSuperConstructorCall));
  1158. ScopePusher scope(*this, ScopePusher::Var | ScopePusher::Function);
  1159. String name;
  1160. if (parse_options & FunctionNodeParseOptions::CheckForFunctionAndName) {
  1161. consume(TokenType::Function);
  1162. if (FunctionNodeType::must_have_name() || match(TokenType::Identifier))
  1163. name = consume(TokenType::Identifier).value();
  1164. }
  1165. consume(TokenType::ParenOpen);
  1166. i32 function_length = -1;
  1167. auto parameters = parse_function_parameters(function_length, parse_options);
  1168. consume(TokenType::ParenClose);
  1169. if (function_length == -1)
  1170. function_length = parameters.size();
  1171. TemporaryChange change(m_parser_state.m_in_function_context, true);
  1172. auto old_labels_in_scope = move(m_parser_state.m_labels_in_scope);
  1173. ScopeGuard guard([&]() {
  1174. m_parser_state.m_labels_in_scope = move(old_labels_in_scope);
  1175. });
  1176. bool is_strict = false;
  1177. auto body = parse_block_statement(is_strict);
  1178. body->add_variables(m_parser_state.m_var_scopes.last());
  1179. body->add_functions(m_parser_state.m_function_scopes.last());
  1180. return create_ast_node<FunctionNodeType>(name, move(body), move(parameters), function_length, NonnullRefPtrVector<VariableDeclaration>(), is_strict);
  1181. }
  1182. Vector<FunctionNode::Parameter> Parser::parse_function_parameters(int& function_length, u8 parse_options)
  1183. {
  1184. bool has_default_parameter = false;
  1185. bool has_rest_parameter = false;
  1186. Vector<FunctionNode::Parameter> parameters;
  1187. auto consume_and_validate_identifier = [&]() -> Token {
  1188. auto token = consume(TokenType::Identifier);
  1189. auto parameter_name = token.value();
  1190. for (auto& parameter : parameters) {
  1191. if (parameter_name != parameter.name)
  1192. continue;
  1193. String message;
  1194. if (parse_options & FunctionNodeParseOptions::IsArrowFunction)
  1195. message = String::formatted("Duplicate parameter '{}' not allowed in arrow function", parameter_name);
  1196. else if (m_parser_state.m_strict_mode)
  1197. message = String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name);
  1198. else if (has_default_parameter || match(TokenType::Equals))
  1199. message = String::formatted("Duplicate parameter '{}' not allowed in function with default parameter", parameter_name);
  1200. else if (has_rest_parameter)
  1201. message = String::formatted("Duplicate parameter '{}' not allowed in function with rest parameter", parameter_name);
  1202. if (!message.is_empty())
  1203. syntax_error(message, Position { token.line_number(), token.line_column() });
  1204. break;
  1205. }
  1206. return token;
  1207. };
  1208. while (match(TokenType::Identifier) || match(TokenType::TripleDot)) {
  1209. if (parse_options & FunctionNodeParseOptions::IsGetterFunction)
  1210. syntax_error("Getter function must have no arguments");
  1211. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && (parameters.size() >= 1 || match(TokenType::TripleDot)))
  1212. syntax_error("Setter function must have one argument");
  1213. if (match(TokenType::TripleDot)) {
  1214. consume();
  1215. has_rest_parameter = true;
  1216. auto parameter_name = consume_and_validate_identifier().value();
  1217. function_length = parameters.size();
  1218. parameters.append({ parameter_name, nullptr, true });
  1219. break;
  1220. }
  1221. auto parameter_name = consume_and_validate_identifier().value();
  1222. RefPtr<Expression> default_value;
  1223. if (match(TokenType::Equals)) {
  1224. consume();
  1225. has_default_parameter = true;
  1226. function_length = parameters.size();
  1227. default_value = parse_expression(2);
  1228. }
  1229. parameters.append({ parameter_name, default_value });
  1230. if (match(TokenType::ParenClose))
  1231. break;
  1232. consume(TokenType::Comma);
  1233. }
  1234. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && parameters.is_empty())
  1235. syntax_error("Setter function must have one argument");
  1236. return parameters;
  1237. }
  1238. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(bool for_loop_variable_declaration)
  1239. {
  1240. DeclarationKind declaration_kind;
  1241. switch (m_parser_state.m_current_token.type()) {
  1242. case TokenType::Var:
  1243. declaration_kind = DeclarationKind::Var;
  1244. break;
  1245. case TokenType::Let:
  1246. declaration_kind = DeclarationKind::Let;
  1247. break;
  1248. case TokenType::Const:
  1249. declaration_kind = DeclarationKind::Const;
  1250. break;
  1251. default:
  1252. ASSERT_NOT_REACHED();
  1253. }
  1254. consume();
  1255. NonnullRefPtrVector<VariableDeclarator> declarations;
  1256. for (;;) {
  1257. auto id = consume(TokenType::Identifier).value();
  1258. RefPtr<Expression> init;
  1259. if (match(TokenType::Equals)) {
  1260. consume();
  1261. init = parse_expression(2);
  1262. } else if (!for_loop_variable_declaration && declaration_kind == DeclarationKind::Const) {
  1263. syntax_error("Missing initializer in 'const' variable declaration");
  1264. }
  1265. declarations.append(create_ast_node<VariableDeclarator>(create_ast_node<Identifier>(move(id)), move(init)));
  1266. if (match(TokenType::Comma)) {
  1267. consume();
  1268. continue;
  1269. }
  1270. break;
  1271. }
  1272. if (!for_loop_variable_declaration)
  1273. consume_or_insert_semicolon();
  1274. auto declaration = create_ast_node<VariableDeclaration>(declaration_kind, move(declarations));
  1275. if (declaration_kind == DeclarationKind::Var)
  1276. m_parser_state.m_var_scopes.last().append(declaration);
  1277. else
  1278. m_parser_state.m_let_scopes.last().append(declaration);
  1279. return declaration;
  1280. }
  1281. NonnullRefPtr<ThrowStatement> Parser::parse_throw_statement()
  1282. {
  1283. consume(TokenType::Throw);
  1284. // Automatic semicolon insertion: terminate statement when throw is followed by newline
  1285. if (m_parser_state.m_current_token.trivia_contains_line_terminator()) {
  1286. syntax_error("No line break is allowed between 'throw' and its expression");
  1287. return create_ast_node<ThrowStatement>(create_ast_node<ErrorExpression>());
  1288. }
  1289. auto expression = parse_expression(0);
  1290. consume_or_insert_semicolon();
  1291. return create_ast_node<ThrowStatement>(move(expression));
  1292. }
  1293. NonnullRefPtr<BreakStatement> Parser::parse_break_statement()
  1294. {
  1295. consume(TokenType::Break);
  1296. FlyString target_label;
  1297. if (match(TokenType::Semicolon)) {
  1298. consume();
  1299. } else {
  1300. if (match(TokenType::Identifier) && !m_parser_state.m_current_token.trivia_contains_line_terminator()) {
  1301. target_label = consume().value();
  1302. if (!m_parser_state.m_labels_in_scope.contains(target_label))
  1303. syntax_error(String::formatted("Label '{}' not found", target_label));
  1304. }
  1305. consume_or_insert_semicolon();
  1306. }
  1307. if (target_label.is_null() && !m_parser_state.m_in_break_context)
  1308. syntax_error("Unlabeled 'break' not allowed outside of a loop or switch statement");
  1309. return create_ast_node<BreakStatement>(target_label);
  1310. }
  1311. NonnullRefPtr<ContinueStatement> Parser::parse_continue_statement()
  1312. {
  1313. if (!m_parser_state.m_in_continue_context)
  1314. syntax_error("'continue' not allow outside of a loop");
  1315. consume(TokenType::Continue);
  1316. FlyString target_label;
  1317. if (match(TokenType::Semicolon)) {
  1318. consume();
  1319. return create_ast_node<ContinueStatement>(target_label);
  1320. }
  1321. if (match(TokenType::Identifier) && !m_parser_state.m_current_token.trivia_contains_line_terminator()) {
  1322. target_label = consume().value();
  1323. if (!m_parser_state.m_labels_in_scope.contains(target_label))
  1324. syntax_error(String::formatted("Label '{}' not found", target_label));
  1325. }
  1326. consume_or_insert_semicolon();
  1327. return create_ast_node<ContinueStatement>(target_label);
  1328. }
  1329. NonnullRefPtr<ConditionalExpression> Parser::parse_conditional_expression(NonnullRefPtr<Expression> test)
  1330. {
  1331. consume(TokenType::QuestionMark);
  1332. auto consequent = parse_expression(2);
  1333. consume(TokenType::Colon);
  1334. auto alternate = parse_expression(2);
  1335. return create_ast_node<ConditionalExpression>(move(test), move(consequent), move(alternate));
  1336. }
  1337. NonnullRefPtr<TryStatement> Parser::parse_try_statement()
  1338. {
  1339. consume(TokenType::Try);
  1340. auto block = parse_block_statement();
  1341. RefPtr<CatchClause> handler;
  1342. if (match(TokenType::Catch))
  1343. handler = parse_catch_clause();
  1344. RefPtr<BlockStatement> finalizer;
  1345. if (match(TokenType::Finally)) {
  1346. consume();
  1347. finalizer = parse_block_statement();
  1348. }
  1349. if (!handler && !finalizer)
  1350. syntax_error("try statement must have a 'catch' or 'finally' clause");
  1351. return create_ast_node<TryStatement>(move(block), move(handler), move(finalizer));
  1352. }
  1353. NonnullRefPtr<DoWhileStatement> Parser::parse_do_while_statement()
  1354. {
  1355. consume(TokenType::Do);
  1356. auto body = [&]() -> NonnullRefPtr<Statement> {
  1357. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1358. TemporaryChange continue_change(m_parser_state.m_in_continue_context, true);
  1359. return parse_statement();
  1360. }();
  1361. consume(TokenType::While);
  1362. consume(TokenType::ParenOpen);
  1363. auto test = parse_expression(0);
  1364. consume(TokenType::ParenClose);
  1365. // Since ES 2015 a missing semicolon is inserted here, despite the regular ASI rules not applying
  1366. if (match(TokenType::Semicolon))
  1367. consume();
  1368. return create_ast_node<DoWhileStatement>(move(test), move(body));
  1369. }
  1370. NonnullRefPtr<WhileStatement> Parser::parse_while_statement()
  1371. {
  1372. consume(TokenType::While);
  1373. consume(TokenType::ParenOpen);
  1374. auto test = parse_expression(0);
  1375. consume(TokenType::ParenClose);
  1376. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1377. TemporaryChange continue_change(m_parser_state.m_in_continue_context, true);
  1378. auto body = parse_statement();
  1379. return create_ast_node<WhileStatement>(move(test), move(body));
  1380. }
  1381. NonnullRefPtr<SwitchStatement> Parser::parse_switch_statement()
  1382. {
  1383. consume(TokenType::Switch);
  1384. consume(TokenType::ParenOpen);
  1385. auto determinant = parse_expression(0);
  1386. consume(TokenType::ParenClose);
  1387. consume(TokenType::CurlyOpen);
  1388. NonnullRefPtrVector<SwitchCase> cases;
  1389. auto has_default = false;
  1390. while (match(TokenType::Case) || match(TokenType::Default)) {
  1391. if (match(TokenType::Default)) {
  1392. if (has_default)
  1393. syntax_error("Multiple 'default' clauses in switch statement");
  1394. has_default = true;
  1395. }
  1396. cases.append(parse_switch_case());
  1397. }
  1398. consume(TokenType::CurlyClose);
  1399. return create_ast_node<SwitchStatement>(move(determinant), move(cases));
  1400. }
  1401. NonnullRefPtr<WithStatement> Parser::parse_with_statement()
  1402. {
  1403. consume(TokenType::With);
  1404. consume(TokenType::ParenOpen);
  1405. auto object = parse_expression(0);
  1406. consume(TokenType::ParenClose);
  1407. auto body = parse_statement();
  1408. return create_ast_node<WithStatement>(move(object), move(body));
  1409. }
  1410. NonnullRefPtr<SwitchCase> Parser::parse_switch_case()
  1411. {
  1412. RefPtr<Expression> test;
  1413. if (consume().type() == TokenType::Case) {
  1414. test = parse_expression(0);
  1415. }
  1416. consume(TokenType::Colon);
  1417. NonnullRefPtrVector<Statement> consequent;
  1418. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1419. for (;;) {
  1420. if (match_declaration())
  1421. consequent.append(parse_declaration());
  1422. else if (match_statement())
  1423. consequent.append(parse_statement());
  1424. else
  1425. break;
  1426. }
  1427. return create_ast_node<SwitchCase>(move(test), move(consequent));
  1428. }
  1429. NonnullRefPtr<CatchClause> Parser::parse_catch_clause()
  1430. {
  1431. consume(TokenType::Catch);
  1432. String parameter;
  1433. if (match(TokenType::ParenOpen)) {
  1434. consume();
  1435. parameter = consume(TokenType::Identifier).value();
  1436. consume(TokenType::ParenClose);
  1437. }
  1438. auto body = parse_block_statement();
  1439. return create_ast_node<CatchClause>(parameter, move(body));
  1440. }
  1441. NonnullRefPtr<IfStatement> Parser::parse_if_statement()
  1442. {
  1443. auto parse_function_declaration_as_block_statement = [&] {
  1444. // https://tc39.es/ecma262/#sec-functiondeclarations-in-ifstatement-statement-clauses
  1445. // Code matching this production is processed as if each matching occurrence of
  1446. // FunctionDeclaration[?Yield, ?Await, ~Default] was the sole StatementListItem
  1447. // of a BlockStatement occupying that position in the source code.
  1448. ScopePusher scope(*this, ScopePusher::Let);
  1449. auto block = create_ast_node<BlockStatement>();
  1450. block->append(parse_declaration());
  1451. block->add_functions(m_parser_state.m_function_scopes.last());
  1452. return block;
  1453. };
  1454. consume(TokenType::If);
  1455. consume(TokenType::ParenOpen);
  1456. auto predicate = parse_expression(0);
  1457. consume(TokenType::ParenClose);
  1458. RefPtr<Statement> consequent;
  1459. if (!m_parser_state.m_strict_mode && match(TokenType::Function))
  1460. consequent = parse_function_declaration_as_block_statement();
  1461. else
  1462. consequent = parse_statement();
  1463. RefPtr<Statement> alternate;
  1464. if (match(TokenType::Else)) {
  1465. consume();
  1466. if (!m_parser_state.m_strict_mode && match(TokenType::Function))
  1467. alternate = parse_function_declaration_as_block_statement();
  1468. else
  1469. alternate = parse_statement();
  1470. }
  1471. return create_ast_node<IfStatement>(move(predicate), move(*consequent), move(alternate));
  1472. }
  1473. NonnullRefPtr<Statement> Parser::parse_for_statement()
  1474. {
  1475. auto match_for_in_of = [&]() {
  1476. return match(TokenType::In) || (match(TokenType::Identifier) && m_parser_state.m_current_token.value() == "of");
  1477. };
  1478. consume(TokenType::For);
  1479. consume(TokenType::ParenOpen);
  1480. bool in_scope = false;
  1481. RefPtr<ASTNode> init;
  1482. if (!match(TokenType::Semicolon)) {
  1483. if (match_expression()) {
  1484. init = parse_expression(0, Associativity::Right, { TokenType::In });
  1485. if (match_for_in_of())
  1486. return parse_for_in_of_statement(*init);
  1487. } else if (match_variable_declaration()) {
  1488. if (!match(TokenType::Var)) {
  1489. m_parser_state.m_let_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
  1490. in_scope = true;
  1491. }
  1492. init = parse_variable_declaration(true);
  1493. if (match_for_in_of())
  1494. return parse_for_in_of_statement(*init);
  1495. if (static_cast<VariableDeclaration&>(*init).declaration_kind() == DeclarationKind::Const) {
  1496. for (auto& declaration : static_cast<VariableDeclaration&>(*init).declarations()) {
  1497. if (!declaration.init())
  1498. syntax_error("Missing initializer in 'const' variable declaration");
  1499. }
  1500. }
  1501. } else {
  1502. syntax_error("Unexpected token in for loop");
  1503. }
  1504. }
  1505. consume(TokenType::Semicolon);
  1506. RefPtr<Expression> test;
  1507. if (!match(TokenType::Semicolon))
  1508. test = parse_expression(0);
  1509. consume(TokenType::Semicolon);
  1510. RefPtr<Expression> update;
  1511. if (!match(TokenType::ParenClose))
  1512. update = parse_expression(0);
  1513. consume(TokenType::ParenClose);
  1514. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1515. TemporaryChange continue_change(m_parser_state.m_in_continue_context, true);
  1516. auto body = parse_statement();
  1517. if (in_scope) {
  1518. m_parser_state.m_let_scopes.take_last();
  1519. }
  1520. return create_ast_node<ForStatement>(move(init), move(test), move(update), move(body));
  1521. }
  1522. NonnullRefPtr<Statement> Parser::parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs)
  1523. {
  1524. if (lhs->is_variable_declaration()) {
  1525. auto declarations = static_cast<VariableDeclaration&>(*lhs).declarations();
  1526. if (declarations.size() > 1)
  1527. syntax_error("multiple declarations not allowed in for..in/of");
  1528. if (declarations.first().init() != nullptr)
  1529. syntax_error("variable initializer not allowed in for..in/of");
  1530. }
  1531. auto in_or_of = consume();
  1532. auto rhs = parse_expression(0);
  1533. consume(TokenType::ParenClose);
  1534. TemporaryChange break_change(m_parser_state.m_in_break_context, true);
  1535. TemporaryChange continue_change(m_parser_state.m_in_continue_context, true);
  1536. auto body = parse_statement();
  1537. if (in_or_of.type() == TokenType::In)
  1538. return create_ast_node<ForInStatement>(move(lhs), move(rhs), move(body));
  1539. return create_ast_node<ForOfStatement>(move(lhs), move(rhs), move(body));
  1540. }
  1541. NonnullRefPtr<DebuggerStatement> Parser::parse_debugger_statement()
  1542. {
  1543. consume(TokenType::Debugger);
  1544. consume_or_insert_semicolon();
  1545. return create_ast_node<DebuggerStatement>();
  1546. }
  1547. bool Parser::match(TokenType type) const
  1548. {
  1549. return m_parser_state.m_current_token.type() == type;
  1550. }
  1551. bool Parser::match_expression() const
  1552. {
  1553. auto type = m_parser_state.m_current_token.type();
  1554. return type == TokenType::BoolLiteral
  1555. || type == TokenType::NumericLiteral
  1556. || type == TokenType::BigIntLiteral
  1557. || type == TokenType::StringLiteral
  1558. || type == TokenType::TemplateLiteralStart
  1559. || type == TokenType::NullLiteral
  1560. || type == TokenType::Identifier
  1561. || type == TokenType::New
  1562. || type == TokenType::CurlyOpen
  1563. || type == TokenType::BracketOpen
  1564. || type == TokenType::ParenOpen
  1565. || type == TokenType::Function
  1566. || type == TokenType::This
  1567. || type == TokenType::Super
  1568. || type == TokenType::RegexLiteral
  1569. || match_unary_prefixed_expression();
  1570. }
  1571. bool Parser::match_unary_prefixed_expression() const
  1572. {
  1573. auto type = m_parser_state.m_current_token.type();
  1574. return type == TokenType::PlusPlus
  1575. || type == TokenType::MinusMinus
  1576. || type == TokenType::ExclamationMark
  1577. || type == TokenType::Tilde
  1578. || type == TokenType::Plus
  1579. || type == TokenType::Minus
  1580. || type == TokenType::Typeof
  1581. || type == TokenType::Void
  1582. || type == TokenType::Delete;
  1583. }
  1584. bool Parser::match_secondary_expression(Vector<TokenType> forbidden) const
  1585. {
  1586. auto type = m_parser_state.m_current_token.type();
  1587. if (forbidden.contains_slow(type))
  1588. return false;
  1589. return type == TokenType::Plus
  1590. || type == TokenType::PlusEquals
  1591. || type == TokenType::Minus
  1592. || type == TokenType::MinusEquals
  1593. || type == TokenType::Asterisk
  1594. || type == TokenType::AsteriskEquals
  1595. || type == TokenType::Slash
  1596. || type == TokenType::SlashEquals
  1597. || type == TokenType::Percent
  1598. || type == TokenType::PercentEquals
  1599. || type == TokenType::DoubleAsterisk
  1600. || type == TokenType::DoubleAsteriskEquals
  1601. || type == TokenType::Equals
  1602. || type == TokenType::EqualsEqualsEquals
  1603. || type == TokenType::ExclamationMarkEqualsEquals
  1604. || type == TokenType::EqualsEquals
  1605. || type == TokenType::ExclamationMarkEquals
  1606. || type == TokenType::GreaterThan
  1607. || type == TokenType::GreaterThanEquals
  1608. || type == TokenType::LessThan
  1609. || type == TokenType::LessThanEquals
  1610. || type == TokenType::ParenOpen
  1611. || type == TokenType::Period
  1612. || type == TokenType::BracketOpen
  1613. || type == TokenType::PlusPlus
  1614. || type == TokenType::MinusMinus
  1615. || type == TokenType::In
  1616. || type == TokenType::Instanceof
  1617. || type == TokenType::QuestionMark
  1618. || type == TokenType::Ampersand
  1619. || type == TokenType::AmpersandEquals
  1620. || type == TokenType::Pipe
  1621. || type == TokenType::PipeEquals
  1622. || type == TokenType::Caret
  1623. || type == TokenType::CaretEquals
  1624. || type == TokenType::ShiftLeft
  1625. || type == TokenType::ShiftLeftEquals
  1626. || type == TokenType::ShiftRight
  1627. || type == TokenType::ShiftRightEquals
  1628. || type == TokenType::UnsignedShiftRight
  1629. || type == TokenType::UnsignedShiftRightEquals
  1630. || type == TokenType::DoubleAmpersand
  1631. || type == TokenType::DoubleAmpersandEquals
  1632. || type == TokenType::DoublePipe
  1633. || type == TokenType::DoublePipeEquals
  1634. || type == TokenType::DoubleQuestionMark
  1635. || type == TokenType::DoubleQuestionMarkEquals;
  1636. }
  1637. bool Parser::match_statement() const
  1638. {
  1639. auto type = m_parser_state.m_current_token.type();
  1640. return match_expression()
  1641. || type == TokenType::Return
  1642. || type == TokenType::Do
  1643. || type == TokenType::If
  1644. || type == TokenType::Throw
  1645. || type == TokenType::Try
  1646. || type == TokenType::While
  1647. || type == TokenType::With
  1648. || type == TokenType::For
  1649. || type == TokenType::CurlyOpen
  1650. || type == TokenType::Switch
  1651. || type == TokenType::Break
  1652. || type == TokenType::Continue
  1653. || type == TokenType::Var
  1654. || type == TokenType::Debugger
  1655. || type == TokenType::Semicolon;
  1656. }
  1657. bool Parser::match_declaration() const
  1658. {
  1659. auto type = m_parser_state.m_current_token.type();
  1660. return type == TokenType::Function
  1661. || type == TokenType::Class
  1662. || type == TokenType::Const
  1663. || type == TokenType::Let;
  1664. }
  1665. bool Parser::match_variable_declaration() const
  1666. {
  1667. auto type = m_parser_state.m_current_token.type();
  1668. return type == TokenType::Var
  1669. || type == TokenType::Let
  1670. || type == TokenType::Const;
  1671. }
  1672. bool Parser::match_identifier_name() const
  1673. {
  1674. return m_parser_state.m_current_token.is_identifier_name();
  1675. }
  1676. bool Parser::match_property_key() const
  1677. {
  1678. auto type = m_parser_state.m_current_token.type();
  1679. return match_identifier_name()
  1680. || type == TokenType::BracketOpen
  1681. || type == TokenType::StringLiteral
  1682. || type == TokenType::NumericLiteral
  1683. || type == TokenType::BigIntLiteral;
  1684. }
  1685. bool Parser::done() const
  1686. {
  1687. return match(TokenType::Eof);
  1688. }
  1689. Token Parser::consume()
  1690. {
  1691. auto old_token = m_parser_state.m_current_token;
  1692. m_parser_state.m_current_token = m_parser_state.m_lexer.next();
  1693. return old_token;
  1694. }
  1695. void Parser::consume_or_insert_semicolon()
  1696. {
  1697. // Semicolon was found and will be consumed
  1698. if (match(TokenType::Semicolon)) {
  1699. consume();
  1700. return;
  1701. }
  1702. // Insert semicolon if...
  1703. // ...token is preceded by one or more newlines
  1704. if (m_parser_state.m_current_token.trivia_contains_line_terminator())
  1705. return;
  1706. // ...token is a closing curly brace
  1707. if (match(TokenType::CurlyClose))
  1708. return;
  1709. // ...token is eof
  1710. if (match(TokenType::Eof))
  1711. return;
  1712. // No rule for semicolon insertion applies -> syntax error
  1713. expected("Semicolon");
  1714. }
  1715. Token Parser::consume(TokenType expected_type)
  1716. {
  1717. if (!match(expected_type)) {
  1718. expected(Token::name(expected_type));
  1719. }
  1720. return consume();
  1721. }
  1722. Token Parser::consume_and_validate_numeric_literal()
  1723. {
  1724. auto is_unprefixed_octal_number = [](const StringView& value) {
  1725. return value.length() > 1 && value[0] == '0' && isdigit(value[1]);
  1726. };
  1727. auto literal_start = position();
  1728. auto token = consume(TokenType::NumericLiteral);
  1729. if (m_parser_state.m_strict_mode && is_unprefixed_octal_number(token.value()))
  1730. syntax_error("Unprefixed octal number not allowed in strict mode", literal_start);
  1731. if (match_identifier_name() && m_parser_state.m_current_token.trivia().is_empty())
  1732. syntax_error("Numeric literal must not be immediately followed by identifier");
  1733. return token;
  1734. }
  1735. void Parser::expected(const char* what)
  1736. {
  1737. auto message = m_parser_state.m_current_token.message();
  1738. if (message.is_empty())
  1739. message = String::formatted("Unexpected token {}. Expected {}", m_parser_state.m_current_token.name(), what);
  1740. syntax_error(message);
  1741. }
  1742. Parser::Position Parser::position() const
  1743. {
  1744. return {
  1745. m_parser_state.m_current_token.line_number(),
  1746. m_parser_state.m_current_token.line_column()
  1747. };
  1748. }
  1749. void Parser::syntax_error(const String& message, Optional<Position> position)
  1750. {
  1751. if (!position.has_value())
  1752. position = this->position();
  1753. m_parser_state.m_errors.append({ message, position });
  1754. }
  1755. void Parser::save_state()
  1756. {
  1757. m_saved_state.append(m_parser_state);
  1758. }
  1759. void Parser::load_state()
  1760. {
  1761. ASSERT(!m_saved_state.is_empty());
  1762. m_parser_state = m_saved_state.take_last();
  1763. }
  1764. }