Parser.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. * Copyright (c) 2021-2022, David Tuin <davidot@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/Assertions.h>
  9. #include <AK/HashTable.h>
  10. #include <AK/NonnullRefPtr.h>
  11. #include <AK/StringBuilder.h>
  12. #include <LibJS/AST.h>
  13. #include <LibJS/Lexer.h>
  14. #include <LibJS/ParserError.h>
  15. #include <LibJS/Runtime/FunctionConstructor.h>
  16. #include <LibJS/SourceRange.h>
  17. #include <LibJS/Token.h>
  18. #include <initializer_list>
  19. #include <stdio.h>
  20. namespace JS {
  21. enum class Associativity {
  22. Left,
  23. Right
  24. };
  25. struct FunctionNodeParseOptions {
  26. enum : u16 {
  27. CheckForFunctionAndName = 1 << 0,
  28. AllowSuperPropertyLookup = 1 << 1,
  29. AllowSuperConstructorCall = 1 << 2,
  30. IsGetterFunction = 1 << 3,
  31. IsSetterFunction = 1 << 4,
  32. IsArrowFunction = 1 << 5,
  33. IsGeneratorFunction = 1 << 6,
  34. IsAsyncFunction = 1 << 7,
  35. HasDefaultExportName = 1 << 8,
  36. };
  37. };
  38. class ScopePusher;
  39. class Parser {
  40. public:
  41. struct EvalInitialState {
  42. bool in_eval_function_context { false };
  43. bool allow_super_property_lookup { false };
  44. bool allow_super_constructor_call { false };
  45. bool in_class_field_initializer { false };
  46. };
  47. explicit Parser(Lexer lexer, Program::Type program_type = Program::Type::Script, Optional<EvalInitialState> initial_state_for_eval = {});
  48. NonnullRefPtr<Program> parse_program(bool starts_in_strict_mode = false);
  49. template<typename FunctionNodeType>
  50. NonnullRefPtr<FunctionNodeType> parse_function_node(u16 parse_options = FunctionNodeParseOptions::CheckForFunctionAndName, Optional<Position> const& function_start = {});
  51. Vector<FunctionParameter> parse_formal_parameters(int& function_length, u16 parse_options = 0);
  52. enum class AllowDuplicates {
  53. Yes,
  54. No
  55. };
  56. enum class AllowMemberExpressions {
  57. Yes,
  58. No
  59. };
  60. RefPtr<BindingPattern> parse_binding_pattern(AllowDuplicates is_var_declaration = AllowDuplicates::No, AllowMemberExpressions allow_member_expressions = AllowMemberExpressions::No);
  61. struct PrimaryExpressionParseResult {
  62. NonnullRefPtr<Expression> result;
  63. bool should_continue_parsing_as_expression { true };
  64. };
  65. NonnullRefPtr<Declaration> parse_declaration();
  66. enum class AllowLabelledFunction {
  67. No,
  68. Yes
  69. };
  70. NonnullRefPtr<Statement> parse_statement(AllowLabelledFunction allow_labelled_function = AllowLabelledFunction::No);
  71. NonnullRefPtr<BlockStatement> parse_block_statement();
  72. NonnullRefPtr<FunctionBody> parse_function_body(Vector<FunctionParameter> const& parameters, FunctionKind function_kind, bool& contains_direct_call_to_eval);
  73. NonnullRefPtr<ReturnStatement> parse_return_statement();
  74. NonnullRefPtr<VariableDeclaration> parse_variable_declaration(bool for_loop_variable_declaration = false);
  75. NonnullRefPtr<Statement> parse_for_statement();
  76. enum class IsForAwaitLoop {
  77. No,
  78. Yes
  79. };
  80. struct ForbiddenTokens {
  81. ForbiddenTokens(std::initializer_list<TokenType> const& forbidden);
  82. ForbiddenTokens merge(ForbiddenTokens other) const;
  83. bool allows(TokenType token) const;
  84. ForbiddenTokens forbid(std::initializer_list<TokenType> const& forbidden) const;
  85. private:
  86. void forbid_tokens(std::initializer_list<TokenType> const& forbidden);
  87. bool m_forbid_in_token : 1 { false };
  88. bool m_forbid_logical_tokens : 1 { false };
  89. bool m_forbid_coalesce_token : 1 { false };
  90. bool m_forbid_paren_open : 1 { false };
  91. bool m_forbid_question_mark_period : 1 { false };
  92. bool m_forbid_equals : 1 { false };
  93. };
  94. struct ExpressionResult {
  95. template<typename T>
  96. ExpressionResult(NonnullRefPtr<T> expression, ForbiddenTokens forbidden = {})
  97. : expression(expression)
  98. , forbidden(forbidden)
  99. {
  100. }
  101. NonnullRefPtr<Expression> expression;
  102. ForbiddenTokens forbidden;
  103. };
  104. NonnullRefPtr<Statement> parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs, IsForAwaitLoop is_await);
  105. NonnullRefPtr<IfStatement> parse_if_statement();
  106. NonnullRefPtr<ThrowStatement> parse_throw_statement();
  107. NonnullRefPtr<TryStatement> parse_try_statement();
  108. NonnullRefPtr<CatchClause> parse_catch_clause();
  109. NonnullRefPtr<SwitchStatement> parse_switch_statement();
  110. NonnullRefPtr<SwitchCase> parse_switch_case();
  111. NonnullRefPtr<BreakStatement> parse_break_statement();
  112. NonnullRefPtr<ContinueStatement> parse_continue_statement();
  113. NonnullRefPtr<DoWhileStatement> parse_do_while_statement();
  114. NonnullRefPtr<WhileStatement> parse_while_statement();
  115. NonnullRefPtr<WithStatement> parse_with_statement();
  116. NonnullRefPtr<DebuggerStatement> parse_debugger_statement();
  117. NonnullRefPtr<ConditionalExpression> parse_conditional_expression(NonnullRefPtr<Expression> test, ForbiddenTokens);
  118. NonnullRefPtr<OptionalChain> parse_optional_chain(NonnullRefPtr<Expression> base);
  119. NonnullRefPtr<Expression> parse_expression(int min_precedence, Associativity associate = Associativity::Right, ForbiddenTokens forbidden = {});
  120. PrimaryExpressionParseResult parse_primary_expression();
  121. NonnullRefPtr<Expression> parse_unary_prefixed_expression();
  122. NonnullRefPtr<RegExpLiteral> parse_regexp_literal();
  123. NonnullRefPtr<ObjectExpression> parse_object_expression();
  124. NonnullRefPtr<ArrayExpression> parse_array_expression();
  125. enum class StringLiteralType {
  126. Normal,
  127. NonTaggedTemplate,
  128. TaggedTemplate
  129. };
  130. NonnullRefPtr<StringLiteral> parse_string_literal(Token const& token, StringLiteralType string_literal_type = StringLiteralType::Normal, bool* contains_invalid_escape = nullptr);
  131. NonnullRefPtr<TemplateLiteral> parse_template_literal(bool is_tagged);
  132. ExpressionResult parse_secondary_expression(NonnullRefPtr<Expression>, int min_precedence, Associativity associate = Associativity::Right, ForbiddenTokens forbidden = {});
  133. NonnullRefPtr<Expression> parse_call_expression(NonnullRefPtr<Expression>);
  134. NonnullRefPtr<NewExpression> parse_new_expression();
  135. NonnullRefPtr<ClassDeclaration> parse_class_declaration();
  136. NonnullRefPtr<ClassExpression> parse_class_expression(bool expect_class_name);
  137. NonnullRefPtr<YieldExpression> parse_yield_expression();
  138. NonnullRefPtr<AwaitExpression> parse_await_expression();
  139. NonnullRefPtr<Expression> parse_property_key();
  140. NonnullRefPtr<AssignmentExpression> parse_assignment_expression(AssignmentOp, NonnullRefPtr<Expression> lhs, int min_precedence, Associativity, ForbiddenTokens forbidden = {});
  141. NonnullRefPtr<Identifier> parse_identifier();
  142. NonnullRefPtr<ImportStatement> parse_import_statement(Program& program);
  143. NonnullRefPtr<ExportStatement> parse_export_statement(Program& program);
  144. RefPtr<FunctionExpression> try_parse_arrow_function_expression(bool expect_parens, bool is_async = false);
  145. RefPtr<LabelledStatement> try_parse_labelled_statement(AllowLabelledFunction allow_function);
  146. RefPtr<MetaProperty> try_parse_new_target_expression();
  147. RefPtr<MetaProperty> try_parse_import_meta_expression();
  148. NonnullRefPtr<ImportCall> parse_import_call();
  149. Vector<CallExpression::Argument> parse_arguments();
  150. bool has_errors() const { return m_state.errors.size(); }
  151. Vector<ParserError> const& errors() const { return m_state.errors; }
  152. void print_errors(bool print_hint = true) const
  153. {
  154. for (auto& error : m_state.errors) {
  155. if (print_hint) {
  156. auto hint = error.source_location_hint(m_state.lexer.source());
  157. if (!hint.is_empty())
  158. warnln("{}", hint);
  159. }
  160. warnln("SyntaxError: {}", error.to_string());
  161. }
  162. }
  163. struct TokenMemoization {
  164. bool try_parse_arrow_function_expression_failed;
  165. };
  166. // Needs to mess with m_state, and we're not going to expose a non-const getter for that :^)
  167. friend ThrowCompletionOr<ECMAScriptFunctionObject*> FunctionConstructor::create_dynamic_function(VM&, FunctionObject&, FunctionObject*, FunctionKind, MarkedVector<Value> const&);
  168. private:
  169. friend class ScopePusher;
  170. void parse_script(Program& program, bool starts_in_strict_mode);
  171. void parse_module(Program& program);
  172. Associativity operator_associativity(TokenType) const;
  173. bool match_expression() const;
  174. bool match_unary_prefixed_expression() const;
  175. bool match_secondary_expression(ForbiddenTokens forbidden = {}) const;
  176. bool match_statement() const;
  177. bool match_export_or_import() const;
  178. bool match_assert_clause() const;
  179. bool match_declaration() const;
  180. bool try_match_let_declaration() const;
  181. bool match_variable_declaration() const;
  182. bool match_identifier() const;
  183. bool match_identifier_name() const;
  184. bool match_property_key() const;
  185. bool is_private_identifier_valid() const;
  186. bool match(TokenType type) const;
  187. bool done() const;
  188. void expected(char const* what);
  189. void syntax_error(String const& message, Optional<Position> = {});
  190. Token consume();
  191. Token consume_identifier();
  192. Token consume_identifier_reference();
  193. Token consume(TokenType type);
  194. Token consume_and_validate_numeric_literal();
  195. void consume_or_insert_semicolon();
  196. void save_state();
  197. void load_state();
  198. void discard_saved_state();
  199. Position position() const;
  200. RefPtr<BindingPattern> synthesize_binding_pattern(Expression const& expression);
  201. Token next_token(size_t steps = 1) const;
  202. void check_identifier_name_for_assignment_validity(FlyString const&, bool force_strict = false);
  203. bool try_parse_arrow_function_expression_failed_at_position(Position const&) const;
  204. void set_try_parse_arrow_function_expression_failed_at_position(Position const&, bool);
  205. bool match_invalid_escaped_keyword() const;
  206. bool parse_directive(ScopeNode& body);
  207. void parse_statement_list(ScopeNode& output_node, AllowLabelledFunction allow_labelled_functions = AllowLabelledFunction::No);
  208. FlyString consume_string_value();
  209. ModuleRequest parse_module_request();
  210. struct RulePosition {
  211. AK_MAKE_NONCOPYABLE(RulePosition);
  212. AK_MAKE_NONMOVABLE(RulePosition);
  213. public:
  214. RulePosition(Parser& parser, Position position)
  215. : m_parser(parser)
  216. , m_position(position)
  217. {
  218. m_parser.m_rule_starts.append(position);
  219. }
  220. ~RulePosition()
  221. {
  222. auto last = m_parser.m_rule_starts.take_last();
  223. VERIFY(last.line == m_position.line);
  224. VERIFY(last.column == m_position.column);
  225. }
  226. Position const& position() const { return m_position; }
  227. private:
  228. Parser& m_parser;
  229. Position m_position;
  230. };
  231. [[nodiscard]] RulePosition push_start() { return { *this, position() }; }
  232. struct ParserState {
  233. Lexer lexer;
  234. Token current_token;
  235. Vector<ParserError> errors;
  236. ScopePusher* current_scope_pusher { nullptr };
  237. HashMap<StringView, Optional<Position>> labels_in_scope;
  238. HashMap<size_t, Position> invalid_property_range_in_object_expression;
  239. HashTable<StringView>* referenced_private_names { nullptr };
  240. bool strict_mode { false };
  241. bool allow_super_property_lookup { false };
  242. bool allow_super_constructor_call { false };
  243. bool in_function_context { false };
  244. bool in_eval_function_context { false }; // This controls if we allow new.target or not. Note that eval("return") is not allowed, so we have to have a separate state variable for eval.
  245. bool in_formal_parameter_context { false };
  246. bool in_generator_function_context { false };
  247. bool await_expression_is_valid { false };
  248. bool in_arrow_function_context { false };
  249. bool in_break_context { false };
  250. bool in_continue_context { false };
  251. bool string_legacy_octal_escape_sequence_in_scope { false };
  252. bool in_class_field_initializer { false };
  253. bool in_class_static_init_block { false };
  254. bool function_might_need_arguments_object { false };
  255. ParserState(Lexer, Program::Type);
  256. };
  257. class PositionKeyTraits {
  258. public:
  259. static int hash(Position const& position)
  260. {
  261. return int_hash(position.line) ^ int_hash(position.column);
  262. }
  263. static bool equals(Position const& a, Position const& b)
  264. {
  265. return a.column == b.column && a.line == b.line;
  266. }
  267. };
  268. NonnullRefPtr<SourceCode> m_source_code;
  269. Vector<Position> m_rule_starts;
  270. ParserState m_state;
  271. FlyString m_filename;
  272. Vector<ParserState> m_saved_state;
  273. HashMap<Position, TokenMemoization, PositionKeyTraits> m_token_memoizations;
  274. Program::Type m_program_type;
  275. };
  276. }