Parser.h 11 KB

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