From 7b8903c19cd68c212785259e2b8f40013c252247 Mon Sep 17 00:00:00 2001 From: Abdelrahman Date: Sun, 29 Jun 2025 00:19:18 +0100 Subject: [PATCH] Add Object.to_string method --- cclox_src/parser/printer.cc | 18 +----------------- cclox_src/scanner/object.cc | 20 ++++++++++++++++++++ cclox_src/scanner/object.hh | 1 + 3 files changed, 22 insertions(+), 17 deletions(-) diff --git a/cclox_src/parser/printer.cc b/cclox_src/parser/printer.cc index 01ac3ab..2376cf2 100644 --- a/cclox_src/parser/printer.cc +++ b/cclox_src/parser/printer.cc @@ -19,23 +19,7 @@ std::string AstPrinter::print(const Expr &expr) { case ExprType::LITERAL: { std::shared_ptr<_Literal> literal = std::get>(expr.value); assert(literal != nullptr); - switch (literal->value.type) { - case ObjectType::NIL: - return "nil"; - case ObjectType::BOOL: { - bool value = std::get(literal->value.value); - return (value ? "true" : "false"); - } - case ObjectType::IDENTIFIER: - case ObjectType::STRING_LIT: { - std::string value = std::get(literal->value.value); - return value; - } - case ObjectType::NUMBER: { - double value = std::get(literal->value.value); - return std::to_string(value); - } - } + return literal->value.to_string(); } case ExprType::UNARY: { std::shared_ptr<_Unary> unary = std::get>(expr.value); diff --git a/cclox_src/scanner/object.cc b/cclox_src/scanner/object.cc index e38659c..006d661 100644 --- a/cclox_src/scanner/object.cc +++ b/cclox_src/scanner/object.cc @@ -1,6 +1,26 @@ #include "object.hh" #include +std::string Object::to_string() { + switch (type) { + case ObjectType::NIL: + return "nil"; + case ObjectType::BOOL: { + bool val = std::get(value); + return (val ? "true" : "false"); + } + case ObjectType::IDENTIFIER: + case ObjectType::STRING_LIT: { + std::string val = std::get(value); + return val; + } + case ObjectType::NUMBER: { + double val = std::get(value); + return std::to_string(val); + } + } +} + std::ostream &operator<<(std::ostream &os, const ObjectType &type) { switch (type) { case ObjectType::NIL: diff --git a/cclox_src/scanner/object.hh b/cclox_src/scanner/object.hh index e32e85f..76511d2 100644 --- a/cclox_src/scanner/object.hh +++ b/cclox_src/scanner/object.hh @@ -29,6 +29,7 @@ struct Object { ObjectType::STRING_LIT }, value{std::move(value)} {}; + std::string to_string(); ObjectType type; std::variant value;