A simple scripting language in C++
Ferenc Szontágh
2025-04-18 d092df5264f6e48f9d59650c092b8297382b1316
src/Interpreter/DeclareVariableStatementNode.hpp
@@ -33,25 +33,27 @@
        ns(ns) {}
    void interpret(Interpreter & interpreter) const override {
        // Evaluate the expression and enforce declared type matches actual value type
        Symbols::Value value = expression_->evaluate(interpreter);
        // Check for duplicate declaration
        if (Symbols::SymbolContainer::instance()->exists(variableName_)) {
            throw Exception("Variable already declared: " + variableName_, filename_, line_, column_);
        try {
            Symbols::Value value = expression_->evaluate(interpreter);
            if (Symbols::SymbolContainer::instance()->exists(variableName_)) {
                throw Exception("Variable already declared: " + variableName_, filename_, line_, column_);
            }
            if (value.getType() != variableType_) {
                using namespace Symbols::Variables;
                std::string expected = TypeToString(variableType_);
                std::string actual   = TypeToString(value.getType());
                throw Exception(
                    "Type mismatch for variable '" + variableName_ +
                    "': expected '" + expected + "' but got '" + actual + "'",
                    filename_, line_, column_);
            }
            const auto variable = Symbols::SymbolFactory::createVariable(variableName_, value, ns, variableType_);
            Symbols::SymbolContainer::instance()->add(variable);
        } catch (const Exception &) {
            throw;
        } catch (const std::exception &e) {
            throw Exception(e.what(), filename_, line_, column_);
        }
        // Enforce type correctness: the evaluated value must match the declared type
        if (value.getType() != variableType_) {
            using namespace Symbols::Variables;
            std::string expected = TypeToString(variableType_);
            std::string actual   = TypeToString(value.getType());
            throw Exception(
                "Type mismatch for variable '" + variableName_ +
                "': expected '" + expected + "' but got '" + actual + "'",
                filename_, line_, column_);
        }
        // Create and add the variable symbol
        const auto variable = Symbols::SymbolFactory::createVariable(variableName_, value, ns, variableType_);
        Symbols::SymbolContainer::instance()->add(variable);
    }
    std::string toString() const override {