Parser.h 10 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);
  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. StringBuilder builder;
  97. String source_string { source };
  98. GenericLexer lexer(source_string);
  99. // Skip to the line we want
  100. size_t current_line = 0;
  101. while (current_line < position.value().line - 1) {
  102. if (lexer.consume_specific("\n") || lexer.consume_specific("\r\n") || lexer.consume_specific(LINE_SEPARATOR) || lexer.consume_specific(PARAGRAPH_SEPARATOR))
  103. current_line++;
  104. else
  105. lexer.ignore();
  106. VERIFY(!lexer.is_eof());
  107. }
  108. // We are at the line, now add the chars to the string
  109. while (!lexer.is_eof()) {
  110. if (lexer.consume_specific("\n") || lexer.consume_specific("\r\n") || lexer.consume_specific(LINE_SEPARATOR) || lexer.consume_specific(PARAGRAPH_SEPARATOR))
  111. break;
  112. else
  113. builder.append(lexer.consume());
  114. }
  115. builder.append('\n');
  116. for (size_t i = 0; i < position.value().column - 1; ++i)
  117. builder.append(spacer);
  118. builder.append(indicator);
  119. return builder.build();
  120. }
  121. };
  122. bool has_errors() const { return m_state.errors.size(); }
  123. const Vector<Error>& errors() const { return m_state.errors; }
  124. void print_errors(bool print_hint = true) const
  125. {
  126. for (auto& error : m_state.errors) {
  127. if (print_hint) {
  128. auto hint = error.source_location_hint(m_state.lexer.source());
  129. if (!hint.is_empty())
  130. warnln("{}", hint);
  131. }
  132. warnln("SyntaxError: {}", error.to_string());
  133. }
  134. }
  135. struct TokenMemoization {
  136. bool try_parse_arrow_function_expression_failed;
  137. };
  138. private:
  139. friend class ScopePusher;
  140. Associativity operator_associativity(TokenType) const;
  141. bool match_expression() const;
  142. bool match_unary_prefixed_expression() const;
  143. bool match_secondary_expression(const Vector<TokenType>& forbidden = {}) const;
  144. bool match_statement() const;
  145. bool match_declaration() const;
  146. bool match_variable_declaration() const;
  147. bool match_identifier() const;
  148. bool match_identifier_name() const;
  149. bool match_property_key() const;
  150. bool match(TokenType type) const;
  151. bool done() const;
  152. void expected(const char* what);
  153. void syntax_error(const String& message, Optional<Position> = {});
  154. Token consume();
  155. Token consume_identifier();
  156. Token consume_identifier_reference();
  157. Token consume(TokenType type);
  158. Token consume_and_validate_numeric_literal();
  159. void consume_or_insert_semicolon();
  160. void save_state();
  161. void load_state();
  162. void discard_saved_state();
  163. Position position() const;
  164. void check_identifier_name_for_assignment_validity(StringView);
  165. bool try_parse_arrow_function_expression_failed_at_position(const Position&) const;
  166. void set_try_parse_arrow_function_expression_failed_at_position(const Position&, bool);
  167. struct RulePosition {
  168. AK_MAKE_NONCOPYABLE(RulePosition);
  169. AK_MAKE_NONMOVABLE(RulePosition);
  170. public:
  171. RulePosition(Parser& parser, Position position)
  172. : m_parser(parser)
  173. , m_position(position)
  174. {
  175. m_parser.m_rule_starts.append(position);
  176. }
  177. ~RulePosition()
  178. {
  179. auto last = m_parser.m_rule_starts.take_last();
  180. VERIFY(last.line == m_position.line);
  181. VERIFY(last.column == m_position.column);
  182. }
  183. const Position& position() const { return m_position; }
  184. private:
  185. Parser& m_parser;
  186. Position m_position;
  187. };
  188. [[nodiscard]] RulePosition push_start() { return { *this, position() }; }
  189. struct Scope : public RefCounted<Scope> {
  190. enum Type {
  191. Function,
  192. Block,
  193. };
  194. struct HoistableDeclaration {
  195. NonnullRefPtr<FunctionDeclaration> declaration;
  196. NonnullRefPtr<Scope> scope; // where it is actually declared
  197. };
  198. Type type;
  199. RefPtr<Scope> parent;
  200. NonnullRefPtrVector<FunctionDeclaration> function_declarations;
  201. Vector<HoistableDeclaration> hoisted_function_declarations;
  202. HashTable<FlyString> lexical_declarations;
  203. explicit Scope(Type, RefPtr<Scope>);
  204. RefPtr<Scope> get_current_function_scope();
  205. };
  206. struct ParserState {
  207. Lexer lexer;
  208. Token current_token;
  209. Vector<Error> errors;
  210. Vector<NonnullRefPtrVector<VariableDeclaration>> var_scopes;
  211. Vector<NonnullRefPtrVector<VariableDeclaration>> let_scopes;
  212. RefPtr<Scope> current_scope;
  213. Vector<Vector<FunctionNode::Parameter>&> function_parameters;
  214. HashTable<StringView> labels_in_scope;
  215. bool strict_mode { false };
  216. bool allow_super_property_lookup { false };
  217. bool allow_super_constructor_call { false };
  218. bool in_function_context { false };
  219. bool in_generator_function_context { false };
  220. bool in_arrow_function_context { false };
  221. bool in_break_context { false };
  222. bool in_continue_context { false };
  223. bool string_legacy_octal_escape_sequence_in_scope { false };
  224. explicit ParserState(Lexer);
  225. };
  226. class PositionKeyTraits {
  227. public:
  228. static int hash(const Position& position)
  229. {
  230. return int_hash(position.line) ^ int_hash(position.column);
  231. }
  232. static bool equals(const Position& a, const Position& b)
  233. {
  234. return a.column == b.column && a.line == b.line;
  235. }
  236. };
  237. Vector<Position> m_rule_starts;
  238. ParserState m_state;
  239. FlyString m_filename;
  240. Vector<ParserState> m_saved_state;
  241. HashMap<Position, TokenMemoization, PositionKeyTraits> m_token_memoizations;
  242. };
  243. }