Parser.h 11 KB

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