Parser.h 11 KB

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