Parser.h 12 KB

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