sapphirec
The Sapphire documentation
Parser.h
Go to the documentation of this file.
1 #pragma once
2 #include "AST/NumberNode.h"
3 #include "Error.h"
4 #include "Lexer.h"
5 #include "sapphirepch.h"
6 
7 /* Parser class for the Sapphire compiler. */
8 class Parser
9 {
10  /* Struct to store a parsing result which can be either a parsing error or a success, in which case it contains a
11  * pointer to the result. */
12  template<typename T> struct ErrorOr
13  {
14  /* Return the stored pointer. */
15  std::shared_ptr<T> get()
16  {
17  assert(!m_is_error);
18  return m_ptr;
19  }
20 
21  /* Call Error::throw_error() with the stored error's location, line text, and the error string provided to this
22  * struct instance. */
23  void ethrow()
24  {
25  assert(m_is_error);
26  Error::throw_error(error_tok->loc, error_tok->line(), m_error);
27  }
28 
29  /* Construct a new successful ErrorOr with a heap-allocated pointer to the result class. */
30  ErrorOr(T* ptr) : m_ptr(ptr), m_is_error(false)
31  {
32  }
33  /* Construct a new failed ErrorOr with the error details and the token where parsing failed. */
34  ErrorOr(const std::string& error, const Token& error_tok)
35  : m_error(error), m_is_error(true), error_tok(error_tok)
36  {
37  }
38 
39  /* Is this ErrorOr instance successful or failed? */
40  bool is_error()
41  {
42  return m_is_error;
43  }
44 
45  private:
46  bool m_is_error;
47  std::string m_error;
48  std::unique_ptr<Token> error_tok;
49  std::shared_ptr<T> m_ptr;
50  };
51 
52  private:
53  Parser(const TokenStream& tokens);
54  TokenStream tokens;
55 
56  ErrorOr<ExprNode> walk_expr();
57  ErrorOr<NumberNode> walk_number();
58 
59  int m_index;
60  int saved_m_index;
61 
62  void save_current_position();
63  void restore_current_position();
64 
65  public:
66  ~Parser();
67 
68  /* Construct a new Parser with the given TokenStream. */
69  static std::shared_ptr<Parser> new_parser(const TokenStream& tokens);
70  /* Parse the stored TokenStream and return the top-level node of the result Abstract Syntax Tree. */
71  std::shared_ptr<ASTNode> parse();
72 };
std::vector< Token > TokenStream
Definition: Lexer.h:7
Definition: Parser.h:9
~Parser()
Definition: Parser.cpp:7
static std::shared_ptr< Parser > new_parser(const TokenStream &tokens)
Definition: Parser.cpp:11
std::shared_ptr< ASTNode > parse()
Definition: Parser.cpp:17
void throw_error(const Location &loc, const std::string line_text, const std::string &details)
Definition: Error.cpp:41
Definition: Token.h:54