Parser.h 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@gmx.de>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #pragma once
  27. #include <AK/NonnullRefPtr.h>
  28. #include <AK/StringBuilder.h>
  29. #include <LibJS/AST.h>
  30. #include <LibJS/Lexer.h>
  31. #include <stdio.h>
  32. namespace JS {
  33. enum class Associativity {
  34. Left,
  35. Right
  36. };
  37. class Parser {
  38. public:
  39. explicit Parser(Lexer lexer);
  40. NonnullRefPtr<Program> parse_program();
  41. template<typename FunctionNodeType>
  42. NonnullRefPtr<FunctionNodeType> parse_function_node(bool check_for_function_and_name = true);
  43. NonnullRefPtr<Statement> parse_statement();
  44. NonnullRefPtr<BlockStatement> parse_block_statement();
  45. NonnullRefPtr<ReturnStatement> parse_return_statement();
  46. NonnullRefPtr<VariableDeclaration> parse_variable_declaration(bool with_semicolon = true);
  47. NonnullRefPtr<Statement> parse_for_statement();
  48. NonnullRefPtr<Statement> parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs);
  49. NonnullRefPtr<IfStatement> parse_if_statement();
  50. NonnullRefPtr<ThrowStatement> parse_throw_statement();
  51. NonnullRefPtr<TryStatement> parse_try_statement();
  52. NonnullRefPtr<CatchClause> parse_catch_clause();
  53. NonnullRefPtr<SwitchStatement> parse_switch_statement();
  54. NonnullRefPtr<SwitchCase> parse_switch_case();
  55. NonnullRefPtr<BreakStatement> parse_break_statement();
  56. NonnullRefPtr<ContinueStatement> parse_continue_statement();
  57. NonnullRefPtr<DoWhileStatement> parse_do_while_statement();
  58. NonnullRefPtr<WhileStatement> parse_while_statement();
  59. NonnullRefPtr<DebuggerStatement> parse_debugger_statement();
  60. NonnullRefPtr<ConditionalExpression> parse_conditional_expression(NonnullRefPtr<Expression> test);
  61. NonnullRefPtr<Expression> parse_expression(int min_precedence, Associativity associate = Associativity::Right, Vector<TokenType> forbidden = {});
  62. NonnullRefPtr<Expression> parse_primary_expression();
  63. NonnullRefPtr<Expression> parse_unary_prefixed_expression();
  64. NonnullRefPtr<RegExpLiteral> parse_regexp_literal();
  65. NonnullRefPtr<ObjectExpression> parse_object_expression();
  66. NonnullRefPtr<ArrayExpression> parse_array_expression();
  67. NonnullRefPtr<StringLiteral> parse_string_literal(Token token);
  68. NonnullRefPtr<TemplateLiteral> parse_template_literal(bool is_tagged);
  69. NonnullRefPtr<Expression> parse_secondary_expression(NonnullRefPtr<Expression>, int min_precedence, Associativity associate = Associativity::Right);
  70. NonnullRefPtr<CallExpression> parse_call_expression(NonnullRefPtr<Expression>);
  71. NonnullRefPtr<NewExpression> parse_new_expression();
  72. RefPtr<FunctionExpression> try_parse_arrow_function_expression(bool expect_parens);
  73. RefPtr<Statement> try_parse_labelled_statement();
  74. struct Error {
  75. String message;
  76. size_t line;
  77. size_t column;
  78. String to_string() const
  79. {
  80. if (line == 0 || column == 0)
  81. return message;
  82. return String::format("%s (line: %zu, column: %zu)", message.characters(), line, column);
  83. }
  84. String source_location_hint(const StringView& source, const char spacer = ' ', const char indicator = '^') const
  85. {
  86. if (line == 0 || column == 0)
  87. return {};
  88. StringBuilder builder;
  89. builder.append(source.split_view('\n', true)[line - 1]);
  90. builder.append('\n');
  91. for (size_t i = 0; i < column - 1; ++i)
  92. builder.append(spacer);
  93. builder.append(indicator);
  94. return builder.build();
  95. }
  96. };
  97. bool has_errors() const { return m_parser_state.m_errors.size(); }
  98. const Vector<Error>& errors() const { return m_parser_state.m_errors; }
  99. void print_errors() const
  100. {
  101. for (auto& error : m_parser_state.m_errors)
  102. fprintf(stderr, "SyntaxError: %s\n", error.to_string().characters());
  103. }
  104. private:
  105. friend class ScopePusher;
  106. int operator_precedence(TokenType) const;
  107. Associativity operator_associativity(TokenType) const;
  108. bool match_expression() const;
  109. bool match_unary_prefixed_expression() const;
  110. bool match_secondary_expression(Vector<TokenType> forbidden = {}) const;
  111. bool match_statement() const;
  112. bool match_variable_declaration() const;
  113. bool match_identifier_name() const;
  114. bool match(TokenType type) const;
  115. bool done() const;
  116. void expected(const char* what);
  117. void syntax_error(const String& message, size_t line = 0, size_t column = 0);
  118. Token consume();
  119. Token consume(TokenType type);
  120. void consume_or_insert_semicolon();
  121. void save_state();
  122. void load_state();
  123. enum class UseStrictDirectiveState {
  124. None,
  125. Looking,
  126. Found,
  127. };
  128. struct ParserState {
  129. Lexer m_lexer;
  130. Token m_current_token;
  131. Vector<Error> m_errors;
  132. Vector<NonnullRefPtrVector<VariableDeclaration>> m_var_scopes;
  133. Vector<NonnullRefPtrVector<VariableDeclaration>> m_let_scopes;
  134. Vector<NonnullRefPtrVector<FunctionDeclaration>> m_function_scopes;
  135. UseStrictDirectiveState m_use_strict_directive { UseStrictDirectiveState::None };
  136. bool m_strict_mode { false };
  137. explicit ParserState(Lexer);
  138. };
  139. ParserState m_parser_state;
  140. Vector<ParserState> m_saved_state;
  141. };
  142. }