diff --git a/include/dragon/parser.h b/include/dragon/parser.h index e69de29..74a6b89 100644 --- a/include/dragon/parser.h +++ b/include/dragon/parser.h @@ -0,0 +1,40 @@ +#pragma once + +#include "token.h" +#include "ast.h" + +#include "ast/variable_declaration_node.h" +#include "ast/variable_assignment_node.h" +#include "ast/while_loop_node.h" +#include "ast/for_loop_node.h" +#include "ast/if_else_node.h" +#include "ast/function_call_node.h" + + +class Parser { +private: + std::vector tokens; + std::vector nodes; + size_t index; + + std::optional peek() const; + std::optional peek_next() const; + std::optional advance(TokenType type); + +public: + explicit Parser(std::vector tokens) : tokens(std::move(tokens)), index(0) {} + explicit Parser() : tokens(std::vector()), index(0) {} + + void reset(); + + std::vector parse(); + std::vector parse(const std::vector& tokens); + + std::unique_ptr parse_variable_declaration(); + std::unique_ptr parse_variable_assignment(); + std::unique_ptr parse_while_loop(); + std::unique_ptr parse_for_loop(); + std::unique_ptr parse_if_else(); + std::unique_ptr parse_function_call(); + std::unique_ptr parse_expression(); +}; \ No newline at end of file diff --git a/include/dragon/token.h b/include/dragon/token.h index 36c4b92..7bdac53 100644 --- a/include/dragon/token.h +++ b/include/dragon/token.h @@ -1,6 +1,8 @@ #pragma once #include +#include +#include enum class TokenType { // Keywords @@ -136,7 +138,7 @@ class Token { return this->type != other.type || this->value != other.value; } - inline std::string to_string() { + inline std::string to_string() const { std::stringstream ss; ss << "Token(" << token_type_to_string(this->type); if (!this->value.empty()) { diff --git a/src/parser.cpp b/src/parser.cpp index 3150749..7ace9e9 100644 --- a/src/parser.cpp +++ b/src/parser.cpp @@ -1 +1,32 @@ -#include "dragon/parser.h" \ No newline at end of file +#include "dragon/parser.h" + +std::optional Parser::peek() const { + if (index < tokens.size()) { + return tokens[index]; + } + + return std::nullopt; +} + +std::optional Parser::peek_next() const { + if (index + 1 < tokens.size()) { + return tokens[index + 1]; + } + + return std::nullopt; +} + +std::optional Parser::advance(TokenType type) { + if (index < tokens.size() && tokens[index].type == type) { + return tokens[index++]; + } + + return std::nullopt; +} + +void Parser::reset() { + index = 0; + tokens.clear(); + nodes.clear(); +} +