Parser.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. enum class IsForLoopVariableDeclaration {
  75. No,
  76. Yes
  77. };
  78. NonnullRefPtr<VariableDeclaration> parse_variable_declaration(IsForLoopVariableDeclaration is_for_loop_variable_declaration = IsForLoopVariableDeclaration::No);
  79. RefPtr<Identifier> parse_lexical_binding();
  80. NonnullRefPtr<UsingDeclaration> parse_using_declaration(IsForLoopVariableDeclaration is_for_loop_variable_declaration = IsForLoopVariableDeclaration::No);
  81. NonnullRefPtr<Statement> parse_for_statement();
  82. enum class IsForAwaitLoop {
  83. No,
  84. Yes
  85. };
  86. struct ForbiddenTokens {
  87. ForbiddenTokens(std::initializer_list<TokenType> const& forbidden);
  88. ForbiddenTokens merge(ForbiddenTokens other) const;
  89. bool allows(TokenType token) const;
  90. ForbiddenTokens forbid(std::initializer_list<TokenType> const& forbidden) const;
  91. private:
  92. void forbid_tokens(std::initializer_list<TokenType> const& forbidden);
  93. bool m_forbid_in_token : 1 { false };
  94. bool m_forbid_logical_tokens : 1 { false };
  95. bool m_forbid_coalesce_token : 1 { false };
  96. bool m_forbid_paren_open : 1 { false };
  97. bool m_forbid_question_mark_period : 1 { false };
  98. bool m_forbid_equals : 1 { false };
  99. };
  100. struct ExpressionResult {
  101. template<typename T>
  102. ExpressionResult(NonnullRefPtr<T> expression, ForbiddenTokens forbidden = {})
  103. : expression(expression)
  104. , forbidden(forbidden)
  105. {
  106. }
  107. NonnullRefPtr<Expression> expression;
  108. ForbiddenTokens forbidden;
  109. };
  110. NonnullRefPtr<Statement> parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs, IsForAwaitLoop is_await);
  111. NonnullRefPtr<IfStatement> parse_if_statement();
  112. NonnullRefPtr<ThrowStatement> parse_throw_statement();
  113. NonnullRefPtr<TryStatement> parse_try_statement();
  114. NonnullRefPtr<CatchClause> parse_catch_clause();
  115. NonnullRefPtr<SwitchStatement> parse_switch_statement();
  116. NonnullRefPtr<SwitchCase> parse_switch_case();
  117. NonnullRefPtr<BreakStatement> parse_break_statement();
  118. NonnullRefPtr<ContinueStatement> parse_continue_statement();
  119. NonnullRefPtr<DoWhileStatement> parse_do_while_statement();
  120. NonnullRefPtr<WhileStatement> parse_while_statement();
  121. NonnullRefPtr<WithStatement> parse_with_statement();
  122. NonnullRefPtr<DebuggerStatement> parse_debugger_statement();
  123. NonnullRefPtr<ConditionalExpression> parse_conditional_expression(NonnullRefPtr<Expression> test, ForbiddenTokens);
  124. NonnullRefPtr<OptionalChain> parse_optional_chain(NonnullRefPtr<Expression> base);
  125. NonnullRefPtr<Expression> parse_expression(int min_precedence, Associativity associate = Associativity::Right, ForbiddenTokens forbidden = {});
  126. PrimaryExpressionParseResult parse_primary_expression();
  127. NonnullRefPtr<Expression> parse_unary_prefixed_expression();
  128. NonnullRefPtr<RegExpLiteral> parse_regexp_literal();
  129. NonnullRefPtr<ObjectExpression> parse_object_expression();
  130. NonnullRefPtr<ArrayExpression> parse_array_expression();
  131. enum class StringLiteralType {
  132. Normal,
  133. NonTaggedTemplate,
  134. TaggedTemplate
  135. };
  136. NonnullRefPtr<StringLiteral> parse_string_literal(Token const& token, StringLiteralType string_literal_type = StringLiteralType::Normal, bool* contains_invalid_escape = nullptr);
  137. NonnullRefPtr<TemplateLiteral> parse_template_literal(bool is_tagged);
  138. ExpressionResult parse_secondary_expression(NonnullRefPtr<Expression>, int min_precedence, Associativity associate = Associativity::Right, ForbiddenTokens forbidden = {});
  139. NonnullRefPtr<Expression> parse_call_expression(NonnullRefPtr<Expression>);
  140. NonnullRefPtr<NewExpression> parse_new_expression();
  141. NonnullRefPtr<ClassDeclaration> parse_class_declaration();
  142. NonnullRefPtr<ClassExpression> parse_class_expression(bool expect_class_name);
  143. NonnullRefPtr<YieldExpression> parse_yield_expression();
  144. NonnullRefPtr<AwaitExpression> parse_await_expression();
  145. NonnullRefPtr<Expression> parse_property_key();
  146. NonnullRefPtr<AssignmentExpression> parse_assignment_expression(AssignmentOp, NonnullRefPtr<Expression> lhs, int min_precedence, Associativity, ForbiddenTokens forbidden = {});
  147. NonnullRefPtr<Identifier> parse_identifier();
  148. NonnullRefPtr<ImportStatement> parse_import_statement(Program& program);
  149. NonnullRefPtr<ExportStatement> parse_export_statement(Program& program);
  150. RefPtr<FunctionExpression> try_parse_arrow_function_expression(bool expect_parens, bool is_async = false);
  151. RefPtr<LabelledStatement> try_parse_labelled_statement(AllowLabelledFunction allow_function);
  152. RefPtr<MetaProperty> try_parse_new_target_expression();
  153. RefPtr<MetaProperty> try_parse_import_meta_expression();
  154. NonnullRefPtr<ImportCall> parse_import_call();
  155. Vector<CallExpression::Argument> parse_arguments();
  156. bool has_errors() const { return m_state.errors.size(); }
  157. Vector<ParserError> const& errors() const { return m_state.errors; }
  158. void print_errors(bool print_hint = true) const
  159. {
  160. for (auto& error : m_state.errors) {
  161. if (print_hint) {
  162. auto hint = error.source_location_hint(m_state.lexer.source());
  163. if (!hint.is_empty())
  164. warnln("{}", hint);
  165. }
  166. warnln("SyntaxError: {}", error.to_deprecated_string());
  167. }
  168. }
  169. struct TokenMemoization {
  170. bool try_parse_arrow_function_expression_failed;
  171. };
  172. // Needs to mess with m_state, and we're not going to expose a non-const getter for that :^)
  173. friend ThrowCompletionOr<ECMAScriptFunctionObject*> FunctionConstructor::create_dynamic_function(VM&, FunctionObject&, FunctionObject*, FunctionKind, MarkedVector<Value> const&);
  174. private:
  175. friend class ScopePusher;
  176. void parse_script(Program& program, bool starts_in_strict_mode);
  177. void parse_module(Program& program);
  178. Associativity operator_associativity(TokenType) const;
  179. bool match_expression() const;
  180. bool match_unary_prefixed_expression() const;
  181. bool match_secondary_expression(ForbiddenTokens forbidden = {}) const;
  182. bool match_statement() const;
  183. bool match_export_or_import() const;
  184. bool match_assert_clause() const;
  185. enum class AllowUsingDeclaration {
  186. No,
  187. Yes
  188. };
  189. bool match_declaration(AllowUsingDeclaration allow_using = AllowUsingDeclaration::No) const;
  190. bool try_match_let_declaration() const;
  191. bool try_match_using_declaration() const;
  192. bool match_variable_declaration() const;
  193. bool match_identifier() const;
  194. bool token_is_identifier(Token const&) const;
  195. bool match_identifier_name() const;
  196. bool match_property_key() const;
  197. bool is_private_identifier_valid() const;
  198. bool match(TokenType type) const;
  199. bool done() const;
  200. void expected(char const* what);
  201. void syntax_error(DeprecatedString const& message, Optional<Position> = {});
  202. Token consume();
  203. Token consume_identifier();
  204. Token consume_identifier_reference();
  205. Token consume(TokenType type);
  206. Token consume_and_validate_numeric_literal();
  207. void consume_or_insert_semicolon();
  208. void save_state();
  209. void load_state();
  210. void discard_saved_state();
  211. Position position() const;
  212. RefPtr<BindingPattern> synthesize_binding_pattern(Expression const& expression);
  213. Token next_token(size_t steps = 1) const;
  214. void check_identifier_name_for_assignment_validity(DeprecatedFlyString const&, bool force_strict = false);
  215. bool try_parse_arrow_function_expression_failed_at_position(Position const&) const;
  216. void set_try_parse_arrow_function_expression_failed_at_position(Position const&, bool);
  217. bool match_invalid_escaped_keyword() const;
  218. bool parse_directive(ScopeNode& body);
  219. void parse_statement_list(ScopeNode& output_node, AllowLabelledFunction allow_labelled_functions = AllowLabelledFunction::No);
  220. DeprecatedFlyString consume_string_value();
  221. ModuleRequest parse_module_request();
  222. struct RulePosition {
  223. AK_MAKE_NONCOPYABLE(RulePosition);
  224. AK_MAKE_NONMOVABLE(RulePosition);
  225. public:
  226. RulePosition(Parser& parser, Position position)
  227. : m_parser(parser)
  228. , m_position(position)
  229. {
  230. m_parser.m_rule_starts.append(position);
  231. }
  232. ~RulePosition()
  233. {
  234. auto last = m_parser.m_rule_starts.take_last();
  235. VERIFY(last.line == m_position.line);
  236. VERIFY(last.column == m_position.column);
  237. }
  238. Position const& position() const { return m_position; }
  239. private:
  240. Parser& m_parser;
  241. Position m_position;
  242. };
  243. [[nodiscard]] RulePosition push_start() { return { *this, position() }; }
  244. struct ParserState {
  245. Lexer lexer;
  246. Token current_token;
  247. Vector<ParserError> errors;
  248. ScopePusher* current_scope_pusher { nullptr };
  249. HashMap<StringView, Optional<Position>> labels_in_scope;
  250. HashMap<size_t, Position> invalid_property_range_in_object_expression;
  251. HashTable<StringView>* referenced_private_names { nullptr };
  252. bool strict_mode { false };
  253. bool allow_super_property_lookup { false };
  254. bool allow_super_constructor_call { false };
  255. bool in_function_context { false };
  256. 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.
  257. bool in_formal_parameter_context { false };
  258. bool in_generator_function_context { false };
  259. bool await_expression_is_valid { false };
  260. bool in_arrow_function_context { false };
  261. bool in_break_context { false };
  262. bool in_continue_context { false };
  263. bool string_legacy_octal_escape_sequence_in_scope { false };
  264. bool in_class_field_initializer { false };
  265. bool in_class_static_init_block { false };
  266. bool function_might_need_arguments_object { false };
  267. ParserState(Lexer, Program::Type);
  268. };
  269. class PositionKeyTraits {
  270. public:
  271. static int hash(Position const& position)
  272. {
  273. return int_hash(position.line) ^ int_hash(position.column);
  274. }
  275. static bool equals(Position const& a, Position const& b)
  276. {
  277. return a.column == b.column && a.line == b.line;
  278. }
  279. };
  280. NonnullRefPtr<SourceCode> m_source_code;
  281. Vector<Position> m_rule_starts;
  282. ParserState m_state;
  283. DeprecatedFlyString m_filename;
  284. Vector<ParserState> m_saved_state;
  285. HashMap<Position, TokenMemoization, PositionKeyTraits> m_token_memoizations;
  286. Program::Type m_program_type;
  287. };
  288. }