More ergonomic solution using macros, but still needs improvement

This commit is contained in:
Abdelrahman Said
2025-06-19 07:54:24 +01:00
parent 56e259d7ed
commit de85b0d93c
4 changed files with 35 additions and 47 deletions

View File

@@ -5,26 +5,6 @@
#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

@@ -6,33 +6,55 @@
#include <string>
#include <variant>
#define BinaryExpr(LEFT, OP, RIGHT) ( \
Expr{ \
.type = ExprType::BINARY, \
.value = Binary{.left = LEFT, .op = OP, .right = RIGHT} \
} \
)
#define GroupingExpr(EXPR) ( \
Expr{ \
.type = ExprType::GROUPING, \
.value = Grouping{.expression = EXPR} \
} \
)
#define LiteralExpr(VALUE) ( \
Expr{ \
.type = ExprType::LITERAL, \
.value = Literal{.value = VALUE} \
} \
)
#define UnaryExpr(OP, RIGHT) ( \
Expr{ \
.type = ExprType::UNARY, \
.value = Unary{.op = OP, .right = RIGHT} \
} \
)
#define BinaryExprPtr(LEFT, OP, RIGHT) (std::make_shared<Expr>(BinaryExpr(LEFT, OP, RIGHT)))
#define GroupingExprPtr(EXPR) (std::make_shared<Expr>(GroupingExpr(EXPR)))
#define LiteralExprPtr(VALUE) (std::make_shared<Expr>(LiteralExpr(VALUE)))
#define UnaryExprPtr(OP, RIGHT) (std::make_shared<Expr>(UnaryExpr(OP, RIGHT)))
struct Expr;
using ExprPtr = std::shared_ptr<Expr>;
struct Binary {
Binary(ExprPtr left, Token op, ExprPtr right) : left{left}, op{op}, right{right} {};
ExprPtr left;
Token op;
ExprPtr right;
};
struct Grouping {
Grouping(ExprPtr expr) : expression{expr} {};
ExprPtr expression;
};
struct Literal {
Literal(Object value) : value{value} {};
Object value;
};
struct Unary {
Unary(Token op, ExprPtr right) : op{op}, right{right} {};
Token op;
ExprPtr right;
};
@@ -47,14 +69,10 @@ enum class ExprType {
using Expression = std::variant<Binary, Grouping, Literal, Unary>;
struct Expr {
Expr(ExprType type, Expression value) : type{type}, value{value} {}
ExprType type;
Expression value;
};
template <typename T>
Expr make_expr(T value);
class AstPrinter {
public:
std::string print(const Expr &expr);