Add Object.to_string method

This commit is contained in:
Abdelrahman Said 2025-06-29 00:19:18 +01:00
parent b3291a9e3a
commit 7b8903c19c
3 changed files with 22 additions and 17 deletions

View File

@ -19,23 +19,7 @@ std::string AstPrinter::print(const Expr &expr) {
case ExprType::LITERAL: {
std::shared_ptr<_Literal> literal = std::get<std::shared_ptr<_Literal>>(expr.value);
assert(literal != nullptr);
switch (literal->value.type) {
case ObjectType::NIL:
return "nil";
case ObjectType::BOOL: {
bool value = std::get<bool>(literal->value.value);
return (value ? "true" : "false");
}
case ObjectType::IDENTIFIER:
case ObjectType::STRING_LIT: {
std::string value = std::get<std::string>(literal->value.value);
return value;
}
case ObjectType::NUMBER: {
double value = std::get<double>(literal->value.value);
return std::to_string(value);
}
}
return literal->value.to_string();
}
case ExprType::UNARY: {
std::shared_ptr<_Unary> unary = std::get<std::shared_ptr<_Unary>>(expr.value);

View File

@ -1,6 +1,26 @@
#include "object.hh"
#include <string>
std::string Object::to_string() {
switch (type) {
case ObjectType::NIL:
return "nil";
case ObjectType::BOOL: {
bool val = std::get<bool>(value);
return (val ? "true" : "false");
}
case ObjectType::IDENTIFIER:
case ObjectType::STRING_LIT: {
std::string val = std::get<std::string>(value);
return val;
}
case ObjectType::NUMBER: {
double val = std::get<double>(value);
return std::to_string(val);
}
}
}
std::ostream &operator<<(std::ostream &os, const ObjectType &type) {
switch (type) {
case ObjectType::NIL:

View File

@ -29,6 +29,7 @@ struct Object {
ObjectType::STRING_LIT
},
value{std::move(value)} {};
std::string to_string();
ObjectType type;
std::variant<std::monostate, std::string, double, bool> value;