Slightly improved version of the parser

This commit is contained in:
Abdelrahman Said 2025-06-18 22:57:52 +01:00
parent ae87a3b4a3
commit 56e259d7ed
3 changed files with 36 additions and 4 deletions

View File

@ -17,13 +17,22 @@ int main(int argc, char *argv[]) {
//
// run_interpreter(argc, argv);
ExprPtr literal = std::make_shared<Expr>(ExprType::LITERAL, Literal{123});
ExprPtr left = std::make_shared<Expr>(ExprType::UNARY, Unary{Token{TokenType::MINUS, "-", Object{}, 1}, literal});
ExprPtr left = std::make_shared<Expr>(
make_expr(
Unary{
Token{TokenType::MINUS, "-", Object{}, 1},
std::make_shared<Expr>(make_expr(Literal{123}))
}
)
);
Token op{TokenType::STAR, "*", Object{}, 1};
ExprPtr gliteral = std::make_shared<Expr>(ExprType::LITERAL, Literal{45.67});
ExprPtr right = std::make_shared<Expr>(ExprType::GROUPING, gliteral);
ExprPtr right = std::make_shared<Expr>(
make_expr(
Grouping{std::make_shared<Expr>(make_expr(Literal{45.67}))}
)
);
Expr expr = {ExprType::BINARY, Binary{left, op, right}};

View File

@ -5,6 +5,26 @@
#include <vector>
#include <sstream>
template <>
Expr make_expr<Binary>(Binary value) {
return Expr(ExprType::BINARY, value);
}
template <>
Expr make_expr<Grouping>(Grouping value) {
return Expr(ExprType::GROUPING, value);
}
template <>
Expr make_expr<Literal>(Literal value) {
return Expr(ExprType::LITERAL, value);
}
template <>
Expr make_expr<Unary>(Unary value) {
return Expr(ExprType::UNARY, value);
}
std::string AstPrinter::print(const Expr &expr) {
switch (expr.type) {
case ExprType::BINARY: {

View File

@ -52,6 +52,9 @@ struct Expr {
Expression value;
};
template <typename T>
Expr make_expr(T value);
class AstPrinter {
public:
std::string print(const Expr &expr);