diff --git a/src/Parser.cpp b/src/Parser.cpp index 28736d6..cc24011 100644 --- a/src/Parser.cpp +++ b/src/Parser.cpp @@ -1,5 +1,4 @@ #include "Parser.h" -#include "Error.h" Parser::Parser(const TokenStream& tokens) : tokens(tokens) @@ -21,7 +20,7 @@ std::shared_ptr Parser::parse() if(result.is_error()) { - Error::throw_error(result.errtok().loc,result.errtok().line(),result.error()); + result.ethrow(); } return result.get(); diff --git a/src/Parser.h b/src/Parser.h index c85a9cd..b54c371 100644 --- a/src/Parser.h +++ b/src/Parser.h @@ -2,28 +2,36 @@ #include #include "Lexer.h" #include "AST/NumberNode.h" +#include "Error.h" +#include +/* Parser class for the Sapphire compiler. */ class Parser { + /* Struct to store a parsing result which can be either a parsing error or a success, in which case it contains a pointer to the result. */ template struct ErrorOr { - std::string error() - { - return m_error; - } + /* Return the stored pointer. */ std::shared_ptr get() { + assert(!m_is_error); return m_ptr; } - Token errtok() + + /* Call Error::throw_error() with the stored error's location, line text, and the error string provided to this struct instance. */ + void ethrow() { - return *(error_tok.get()); + assert(m_is_error); + Error::throw_error(error_tok->loc,error_tok->line(),m_error); } + /* Construct a new successful ErrorOr with a heap-allocated pointer to the result class. */ ErrorOr(T* ptr) : m_ptr(ptr), m_is_error(false) {} + /* Construct a new failed ErrorOr with the error details and the token where parsing failed. */ ErrorOr(const std::string& error, const Token& error_tok) : m_error(error), m_is_error(true), error_tok(error_tok) {} + /* Is this ErrorOr instance successful or failed? */ bool is_error() { return m_is_error; } private: @@ -47,6 +55,8 @@ private: public: ~Parser(); + /* Construct a new Parser with the given TokenStream. */ static std::shared_ptr new_parser(const TokenStream& tokens); + /* Parse the stored TokenStream and return the top-level node of the result Abstract Syntax Tree. */ std::shared_ptr parse(); };