Parser.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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);
  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();
  38. struct PrimaryExpressionParseResult {
  39. NonnullRefPtr<Expression> result;
  40. bool should_continue_parsing_as_expression { true };
  41. };
  42. NonnullRefPtr<Declaration> parse_declaration();
  43. NonnullRefPtr<Statement> parse_statement();
  44. NonnullRefPtr<BlockStatement> parse_block_statement();
  45. NonnullRefPtr<BlockStatement> parse_block_statement(bool& is_strict);
  46. NonnullRefPtr<ReturnStatement> parse_return_statement();
  47. NonnullRefPtr<VariableDeclaration> parse_variable_declaration(bool for_loop_variable_declaration = false);
  48. NonnullRefPtr<Statement> parse_for_statement();
  49. NonnullRefPtr<Statement> parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs);
  50. NonnullRefPtr<IfStatement> parse_if_statement();
  51. NonnullRefPtr<ThrowStatement> parse_throw_statement();
  52. NonnullRefPtr<TryStatement> parse_try_statement();
  53. NonnullRefPtr<CatchClause> parse_catch_clause();
  54. NonnullRefPtr<SwitchStatement> parse_switch_statement();
  55. NonnullRefPtr<SwitchCase> parse_switch_case();
  56. NonnullRefPtr<BreakStatement> parse_break_statement();
  57. NonnullRefPtr<ContinueStatement> parse_continue_statement();
  58. NonnullRefPtr<DoWhileStatement> parse_do_while_statement();
  59. NonnullRefPtr<WhileStatement> parse_while_statement();
  60. NonnullRefPtr<WithStatement> parse_with_statement();
  61. NonnullRefPtr<DebuggerStatement> parse_debugger_statement();
  62. NonnullRefPtr<ConditionalExpression> parse_conditional_expression(NonnullRefPtr<Expression> test);
  63. NonnullRefPtr<Expression> parse_expression(int min_precedence, Associativity associate = Associativity::Right, const Vector<TokenType>& forbidden = {});
  64. PrimaryExpressionParseResult parse_primary_expression();
  65. NonnullRefPtr<Expression> parse_unary_prefixed_expression();
  66. NonnullRefPtr<RegExpLiteral> parse_regexp_literal();
  67. NonnullRefPtr<ObjectExpression> parse_object_expression();
  68. NonnullRefPtr<ArrayExpression> parse_array_expression();
  69. NonnullRefPtr<StringLiteral> parse_string_literal(const Token& token, bool in_template_literal = false);
  70. NonnullRefPtr<TemplateLiteral> parse_template_literal(bool is_tagged);
  71. NonnullRefPtr<Expression> parse_secondary_expression(NonnullRefPtr<Expression>, int min_precedence, Associativity associate = Associativity::Right);
  72. NonnullRefPtr<CallExpression> parse_call_expression(NonnullRefPtr<Expression>);
  73. NonnullRefPtr<NewExpression> parse_new_expression();
  74. NonnullRefPtr<ClassDeclaration> parse_class_declaration();
  75. NonnullRefPtr<ClassExpression> parse_class_expression(bool expect_class_name);
  76. NonnullRefPtr<YieldExpression> parse_yield_expression();
  77. NonnullRefPtr<Expression> parse_property_key();
  78. NonnullRefPtr<AssignmentExpression> parse_assignment_expression(AssignmentOp, NonnullRefPtr<Expression> lhs, int min_precedence, Associativity);
  79. NonnullRefPtr<Identifier> parse_identifier();
  80. RefPtr<FunctionExpression> try_parse_arrow_function_expression(bool expect_parens);
  81. RefPtr<Statement> try_parse_labelled_statement();
  82. RefPtr<MetaProperty> try_parse_new_target_expression();
  83. struct Error {
  84. String message;
  85. Optional<Position> position;
  86. String to_string() const
  87. {
  88. if (!position.has_value())
  89. return message;
  90. return String::formatted("{} (line: {}, column: {})", message, position.value().line, position.value().column);
  91. }
  92. String source_location_hint(const StringView& source, const char spacer = ' ', const char indicator = '^') const
  93. {
  94. if (!position.has_value())
  95. return {};
  96. // We need to modify the source to match what the lexer considers one line - normalizing
  97. // line terminators to \n is easier than splitting using all different LT characters.
  98. String source_string { source };
  99. source_string.replace("\r\n", "\n");
  100. source_string.replace("\r", "\n");
  101. source_string.replace(LINE_SEPARATOR, "\n");
  102. source_string.replace(PARAGRAPH_SEPARATOR, "\n");
  103. StringBuilder builder;
  104. builder.append(source_string.split_view('\n', true)[position.value().line - 1]);
  105. builder.append('\n');
  106. for (size_t i = 0; i < position.value().column - 1; ++i)
  107. builder.append(spacer);
  108. builder.append(indicator);
  109. return builder.build();
  110. }
  111. };
  112. bool has_errors() const { return m_state.errors.size(); }
  113. const Vector<Error>& errors() const { return m_state.errors; }
  114. void print_errors() const
  115. {
  116. for (auto& error : m_state.errors) {
  117. auto hint = error.source_location_hint(m_state.lexer.source());
  118. if (!hint.is_empty())
  119. warnln("{}", hint);
  120. warnln("SyntaxError: {}", error.to_string());
  121. }
  122. }
  123. struct TokenMemoization {
  124. bool try_parse_arrow_function_expression_failed;
  125. };
  126. private:
  127. friend class ScopePusher;
  128. Associativity operator_associativity(TokenType) const;
  129. bool match_expression() const;
  130. bool match_unary_prefixed_expression() const;
  131. bool match_secondary_expression(const Vector<TokenType>& forbidden = {}) const;
  132. bool match_statement() const;
  133. bool match_declaration() const;
  134. bool match_variable_declaration() const;
  135. bool match_identifier_name() const;
  136. bool match_property_key() const;
  137. bool match(TokenType type) const;
  138. bool done() const;
  139. void expected(const char* what);
  140. void syntax_error(const String& message, Optional<Position> = {});
  141. Token consume();
  142. Token consume(TokenType type);
  143. Token consume_and_validate_numeric_literal();
  144. void consume_or_insert_semicolon();
  145. void save_state();
  146. void load_state();
  147. void discard_saved_state();
  148. Position position() const;
  149. bool try_parse_arrow_function_expression_failed_at_position(const Position&) const;
  150. void set_try_parse_arrow_function_expression_failed_at_position(const Position&, bool);
  151. struct RulePosition {
  152. AK_MAKE_NONCOPYABLE(RulePosition);
  153. AK_MAKE_NONMOVABLE(RulePosition);
  154. public:
  155. RulePosition(Parser& parser, Position position)
  156. : m_parser(parser)
  157. , m_position(position)
  158. {
  159. m_parser.m_rule_starts.append(position);
  160. }
  161. ~RulePosition()
  162. {
  163. auto last = m_parser.m_rule_starts.take_last();
  164. VERIFY(last.line == m_position.line);
  165. VERIFY(last.column == m_position.column);
  166. }
  167. const Position& position() const { return m_position; }
  168. private:
  169. Parser& m_parser;
  170. Position m_position;
  171. };
  172. [[nodiscard]] RulePosition push_start() { return { *this, position() }; }
  173. struct Scope : public RefCounted<Scope> {
  174. enum Type {
  175. Function,
  176. Block,
  177. };
  178. struct HoistableDeclaration {
  179. NonnullRefPtr<FunctionDeclaration> declaration;
  180. NonnullRefPtr<Scope> scope; // where it is actually declared
  181. };
  182. Type type;
  183. RefPtr<Scope> parent;
  184. NonnullRefPtrVector<FunctionDeclaration> function_declarations;
  185. Vector<HoistableDeclaration> hoisted_function_declarations;
  186. HashTable<FlyString> lexical_declarations;
  187. explicit Scope(Type, RefPtr<Scope>);
  188. RefPtr<Scope> get_current_function_scope();
  189. };
  190. struct ParserState {
  191. Lexer lexer;
  192. Token current_token;
  193. Vector<Error> errors;
  194. Vector<NonnullRefPtrVector<VariableDeclaration>> var_scopes;
  195. Vector<NonnullRefPtrVector<VariableDeclaration>> let_scopes;
  196. RefPtr<Scope> current_scope;
  197. Vector<Vector<FunctionNode::Parameter>&> function_parameters;
  198. HashTable<StringView> labels_in_scope;
  199. bool strict_mode { false };
  200. bool allow_super_property_lookup { false };
  201. bool allow_super_constructor_call { false };
  202. bool in_function_context { false };
  203. bool in_generator_function_context { false };
  204. bool in_arrow_function_context { false };
  205. bool in_break_context { false };
  206. bool in_continue_context { false };
  207. bool string_legacy_octal_escape_sequence_in_scope { false };
  208. explicit ParserState(Lexer);
  209. };
  210. class PositionKeyTraits {
  211. public:
  212. static int hash(const Position& position)
  213. {
  214. return int_hash(position.line) ^ int_hash(position.column);
  215. }
  216. static bool equals(const Position& a, const Position& b)
  217. {
  218. return a.column == b.column && a.line == b.line;
  219. }
  220. };
  221. Vector<Position> m_rule_starts;
  222. ParserState m_state;
  223. FlyString m_filename;
  224. Vector<ParserState> m_saved_state;
  225. HashMap<Position, TokenMemoization, PositionKeyTraits> m_token_memoizations;
  226. };
  227. }