#include "expr.hh" #include "../tokenizer.hh" #include #include #include #include #include std::string AstPrinter::print(const Expression &expr) { return std::visit([this](auto &&node) -> std::string { using T = std::decay_t; if constexpr(std::is_same_v) { return parenthesize(node.op.lexeme, {node.left, node.right}); } else if constexpr(std::is_same_v) { return parenthesize("group", {node.expression}); } else if constexpr(std::is_same_v) { switch (node.value.type) { case ObjectType::NIL: return "nil"; case ObjectType::IDENTIFIER: case ObjectType::STRING_LIT: { std::string value = std::get(node.value.value); return value; } case ObjectType::NUMBER: { double value = std::get(node.value.value); return std::to_string(value); } } } else if constexpr(std::is_same_v) { return parenthesize(node.op.lexeme, {node.right}); } return ""; }, expr); } std::string AstPrinter::parenthesize(const std::string &name, std::vector exprs) { std::stringstream ss{}; ss << '(' << name; for (auto &expr : exprs) { std::string value = std::visit([this](auto &&node) -> std::string { return print(node); }, expr); ss << ' ' << value; } ss << ')'; return ss.str(); }