#include "sem/SymbolTable.h"
#include <antlr4-runtime.h>  // 用于访问父节点
#include <cctype>
#include <stdexcept>
#include <string>
#include <cmath>

//#define DEBUG_SYMBOL_TABLE
#define Sym_DEBUG 0

#ifdef DEBUG_SYMBOL_TABLE
#include <iostream>
#define DEBUG_MSG(msg) std::cerr << "[SymbolTable Debug] " << msg << std::endl
#else
#define DEBUG_MSG(msg)
#endif

// ---------- 构造函数 ----------
SymbolTable::SymbolTable() {
    scopes_.emplace_back(); // 初始化全局作用域
    registerBuiltinFunctions(); // 注册内置库函数
}

// ---------- 作用域管理 ----------
void SymbolTable::enterScope() {
    scopes_.emplace_back();
}

void SymbolTable::exitScope() {
    if (scopes_.size() > 1) {
        scopes_.pop_back();
    }
    // 不能退出全局作用域
}

// ---------- 符号添加与查找 ----------
bool SymbolTable::addSymbol(const Symbol& sym) {
    auto& current_scope = scopes_.back();
    if (current_scope.find(sym.name) != current_scope.end()) {
        return false;   // 重复定义
    }
    current_scope[sym.name] = sym;

    // 立即验证存储的符号
    const auto& stored = current_scope[sym.name];
    if (Sym_DEBUG) std::cout << "SymbolTable::addSymbol: stored " << sym.name
              << " with kind=" << (int)stored.kind
              << ", const_def_ctx=" << stored.const_def_ctx
              << std::endl;

    return true;
}

Symbol* SymbolTable::lookup(const std::string& name) {
    return const_cast<Symbol*>(static_cast<const SymbolTable*>(this)->lookup(name));
}

Symbol* SymbolTable::lookupCurrent(const std::string& name) {
    return const_cast<Symbol*>(static_cast<const SymbolTable*>(this)->lookupCurrent(name));
}

const Symbol* SymbolTable::lookup(const std::string& name) const {
    for (auto it = scopes_.rbegin(); it != scopes_.rend(); ++it) {
        const auto& scope = *it;
        auto found = scope.find(name);
        if (found != scope.end()) {
            if (Sym_DEBUG) std::cout << "SymbolTable::lookup: found " << name 
                      << " in scope level " << (scopes_.rend() - it - 1)
                      << ", kind=" << (int)found->second.kind
                      << ", const_def_ctx=" << found->second.const_def_ctx
                      << std::endl;
                      
            return &found->second;
        }
    }
    return nullptr;
}

const Symbol* SymbolTable::lookupCurrent(const std::string& name) const {
    const auto& current_scope = scopes_.back();
    auto it = current_scope.find(name);
    if (it != current_scope.end()) {
        return &it->second;
    }
    return nullptr;
}

// ---------- 兼容原接口 ----------
void SymbolTable::Add(const std::string& name, SysYParser::VarDefContext* decl) {
    Symbol sym;
    sym.name = name;
    sym.kind = SymbolKind::Variable;
    sym.type = getTypeFromVarDef(decl);
    sym.var_def_ctx = decl;
    sym.scope_level = currentScopeLevel();
    addSymbol(sym);
}

bool SymbolTable::Contains(const std::string& name) const {
    // const 方法不能修改 scopes_，我们模拟查找
    for (auto it = scopes_.rbegin(); it != scopes_.rend(); ++it) {
        if (it->find(name) != it->end()) {
            return true;
        }
    }
    return false;
}

SysYParser::VarDefContext* SymbolTable::Lookup(const std::string& name) const {
    for (auto it = scopes_.rbegin(); it != scopes_.rend(); ++it) {
        auto found = it->find(name);
        if (found != it->end()) {
            // 只返回变量定义的上下文（函数等其他符号返回 nullptr）
            if (found->second.kind == SymbolKind::Variable) {
                return found->second.var_def_ctx;
            }
            return nullptr;
        }
    }
    return nullptr;
}

// ---------- 辅助函数：从 VarDefContext 获取外层 VarDeclContext ----------
static SysYParser::VarDeclContext* getOuterVarDecl(SysYParser::VarDefContext* varDef) {
    auto parent = varDef->parent;
    while (parent) {
        if (auto varDecl = dynamic_cast<SysYParser::VarDeclContext*>(parent)) {
            return varDecl;
        }
        parent = parent->parent;
    }
    return nullptr;
}

// ---------- 辅助函数：从 VarDefContext 获取外层 ConstDeclContext（常量定义）----------
static SysYParser::ConstDeclContext* getOuterConstDecl(SysYParser::VarDefContext* varDef) {
    auto parent = varDef->parent;
    while (parent) {
        if (auto constDecl = dynamic_cast<SysYParser::ConstDeclContext*>(parent)) {
            return constDecl;
        }
        parent = parent->parent;
    }
    return nullptr;
}

// 从 VarDefContext 构造类型
// 原静态函数改为成员函数，并调用成员 EvaluateConstExp
std::shared_ptr<ir::Type> SymbolTable::getTypeFromVarDef(SysYParser::VarDefContext* ctx) const {
    // 获取基本类型（同原代码，但通过外层 Decl 确定）
    std::shared_ptr<ir::Type> base_type = nullptr;
    auto varDecl = getOuterVarDecl(ctx);
    if (varDecl) {
        auto bType = varDecl->bType();
        if (bType->Int()) base_type = ir::Type::GetInt32Type();
        else if (bType->Float()) base_type = ir::Type::GetFloatType();
    } else {
        auto constDecl = getOuterConstDecl(ctx);
        if (constDecl) {
            auto bType = constDecl->bType();
            if (bType->Int()) base_type = ir::Type::GetInt32Type();
            else if (bType->Float()) base_type = ir::Type::GetFloatType();
        }
    }
    if (!base_type) base_type = ir::Type::GetInt32Type();

    // 解析维度
    std::vector<int> dims;
    for (auto* dimExp : ctx->constExp()) {
        int dim = EvaluateConstExp(dimExp);  // 调用成员函数
        if (dim <= 0) {
            throw std::runtime_error("数组维度必须为正整数");
        }
        dims.push_back(dim);
    }

    if (!dims.empty()) {
        return ir::Type::GetArrayType(base_type, dims);
    }
    return base_type;
}
// 从 FuncDefContext 构造函数类型
std::shared_ptr<ir::Type> SymbolTable::getTypeFromFuncDef(SysYParser::FuncDefContext* ctx) {
    // 1. 返回类型
    std::shared_ptr<ir::Type> ret_type;
    auto funcType = ctx->funcType();
    if (funcType->Void()) {
        ret_type = ir::Type::GetVoidType();
    } else if (funcType->Int()) {
        ret_type = ir::Type::GetInt32Type();
    } else if (funcType->Float()) {
        ret_type = ir::Type::GetFloatType();
    } else {
        ret_type = ir::Type::GetInt32Type(); // fallback
    }

    // 2. 参数类型
    std::vector<std::shared_ptr<ir::Type>> param_types;
    auto fParams = ctx->funcFParams();
    if (fParams) {
        for (auto param : fParams->funcFParam()) {
            std::shared_ptr<ir::Type> param_type;
            auto bType = param->bType();
            if (bType->Int()) {
                param_type = ir::Type::GetInt32Type();
            } else if (bType->Float()) {
                param_type = ir::Type::GetFloatType();
            } else {
                param_type = ir::Type::GetInt32Type();
            }

            // 处理数组参数：如果存在 [ ] 或 [ exp ]，退化为指针
            if (param->L_BRACK().size() > 0) {
                if (param_type->IsInt32()) {
                    param_type = ir::Type::GetPtrInt32Type();
                } else if (param_type->IsFloat()) {
                    param_type = ir::Type::GetPtrFloatType();
                }
            }
            param_types.push_back(param_type);
        }
    }

    return ir::Type::GetFunctionType(ret_type, param_types);
}

// ----- 注册内置库函数-----
void SymbolTable::registerBuiltinFunctions() {
    // 确保当前处于全局作用域（scopes_ 只有一层）
    // 1. getint: int getint()
    Symbol getint;
    getint.name = "getint";
    getint.kind = SymbolKind::Function;
    getint.type = ir::Type::GetFunctionType(ir::Type::GetInt32Type(), {});  // 无参数
    getint.param_types = {};
    getint.scope_level = 0;
    getint.is_builtin = true;
    addSymbol(getint);

    // 2. getfloat: float getfloat()
    Symbol getfloat;
    getfloat.name = "getfloat";
    getfloat.kind = SymbolKind::Function;
    getfloat.type = ir::Type::GetFunctionType(ir::Type::GetFloatType(), {});
    getfloat.param_types = {};
    getfloat.scope_level = 0;
    getfloat.is_builtin = true;
    addSymbol(getfloat);

    // 3. getch: int getch()
    Symbol getch;
    getch.name = "getch";
    getch.kind = SymbolKind::Function;
    getch.type = ir::Type::GetFunctionType(ir::Type::GetInt32Type(), {});
    getch.param_types = {};
    getch.scope_level = 0;
    getch.is_builtin = true;
    addSymbol(getch);

    // 4. putint: void putint(int)
    std::vector<std::shared_ptr<ir::Type>> putint_params = { ir::Type::GetInt32Type() };
    Symbol putint;
    putint.name = "putint";
    putint.kind = SymbolKind::Function;
    putint.type = ir::Type::GetFunctionType(ir::Type::GetVoidType(), putint_params);
    putint.param_types = putint_params;
    putint.scope_level = 0;
    putint.is_builtin = true;
    addSymbol(putint);

    // 5. putfloat: void putfloat(float)
    std::vector<std::shared_ptr<ir::Type>> putfloat_params = { ir::Type::GetFloatType() };
    Symbol putfloat;
    putfloat.name = "putfloat";
    putfloat.kind = SymbolKind::Function;
    putfloat.type = ir::Type::GetFunctionType(ir::Type::GetVoidType(), putfloat_params);
    putfloat.param_types = putfloat_params;
    putfloat.scope_level = 0;
    putfloat.is_builtin = true;
    addSymbol(putfloat);

    // 6. putch: void putch(int)
    std::vector<std::shared_ptr<ir::Type>> putch_params = { ir::Type::GetInt32Type() };
    Symbol putch;
    putch.name = "putch";
    putch.kind = SymbolKind::Function;
    putch.type = ir::Type::GetFunctionType(ir::Type::GetVoidType(), putch_params);
    putch.param_types = putch_params;
    putch.scope_level = 0;
    putch.is_builtin = true;
    addSymbol(putch);

    // 7. getarray: int getarray(int a[])
    // 参数类型: int a[] 退化为 int* 即 PtrInt32
    std::vector<std::shared_ptr<ir::Type>> getarray_params = { ir::Type::GetPtrInt32Type() };
    Symbol getarray;
    getarray.name = "getarray";
    getarray.kind = SymbolKind::Function;
    getarray.type = ir::Type::GetFunctionType(ir::Type::GetInt32Type(), getarray_params);
    getarray.param_types = getarray_params;
    getarray.scope_level = 0;
    getarray.is_builtin = true;
    addSymbol(getarray);

    // 8. putarray: void putarray(int n, int a[])
    // 参数: int n, int a[] -> 实际类型: int, int*
    std::vector<std::shared_ptr<ir::Type>> putarray_params = { ir::Type::GetInt32Type(), ir::Type::GetPtrInt32Type() };
    Symbol putarray;
    putarray.name = "putarray";
    putarray.kind = SymbolKind::Function;
    putarray.type = ir::Type::GetFunctionType(ir::Type::GetVoidType(), putarray_params);
    putarray.param_types = putarray_params;
    putarray.scope_level = 0;
    putarray.is_builtin = true;
    addSymbol(putarray);

    // starttime: void starttime()
    Symbol starttime;
    starttime.name = "starttime";
    starttime.kind = SymbolKind::Function;
    starttime.type = ir::Type::GetFunctionType(ir::Type::GetVoidType(), {});  // 无参数，返回 void
    starttime.param_types = {};
    starttime.scope_level = 0;
    starttime.is_builtin = true;
    addSymbol(starttime);

    // stoptime: void stoptime()
    Symbol stoptime;
    stoptime.name = "stoptime";
    stoptime.kind = SymbolKind::Function;
    stoptime.type = ir::Type::GetFunctionType(ir::Type::GetVoidType(), {});  // 无参数，返回 void
    stoptime.param_types = {};
    stoptime.scope_level = 0;
    stoptime.is_builtin = true;
    addSymbol(stoptime);
    
    // getfarray: int getfarray(float arr[])
    std::vector<std::shared_ptr<ir::Type>> getfarray_params = { ir::Type::GetPtrFloatType() };
    Symbol getfarray;
    getfarray.name = "getfarray";
    getfarray.kind = SymbolKind::Function;
    getfarray.type = ir::Type::GetFunctionType(ir::Type::GetInt32Type(), getfarray_params);
    getfarray.param_types = getfarray_params;
    getfarray.scope_level = 0;
    getfarray.is_builtin = true;
    addSymbol(getfarray);

    // putfarray: void putfarray(int len, float arr[])
    std::vector<std::shared_ptr<ir::Type>> putfarray_params = { 
        ir::Type::GetInt32Type(), 
        ir::Type::GetPtrFloatType() 
    };
    Symbol putfarray;
    putfarray.name = "putfarray";
    putfarray.kind = SymbolKind::Function;
    putfarray.type = ir::Type::GetFunctionType(ir::Type::GetVoidType(), putfarray_params);
    putfarray.param_types = putfarray_params;
    putfarray.scope_level = 0;
    putfarray.is_builtin = true;
    addSymbol(putfarray);
}

// ==================== 常量表达式求值实现 ====================

static long long ParseIntegerLiteral(const std::string& text) {
    // 处理前缀：0x/0X 十六进制，0 八进制，否则十进制
    if (text.size() > 2 && (text[0] == '0' && (text[1] == 'x' || text[1] == 'X'))) {
        return std::stoll(text.substr(2), nullptr, 16);
    } else if (text.size() > 1 && text[0] == '0') {
        return std::stoll(text, nullptr, 8);
    } else {
        return std::stoll(text, nullptr, 10);
    }
}

static float ParseFloatLiteral(const std::string& text) {
    return std::stof(text);
}

SymbolTable::ConstValue SymbolTable::EvaluatePrimaryExp(SysYParser::PrimaryExpContext* ctx) const {
    if (!ctx) throw std::runtime_error("常量表达式求值：无效 PrimaryExp");

    if (ctx->lVal()) {
        auto lval = ctx->lVal();
        if (!lval->Ident()) throw std::runtime_error("常量表达式求值：无效左值");
        std::string name = lval->Ident()->getText();
        DEBUG_MSG("  左值标识符: " << name);
        const Symbol* sym = lookup(name);
        DEBUG_MSG("  找到符号: kind=" << (int)sym->kind << ", value=" 
                << (sym->is_int_const ? std::to_string(sym->const_value.i32) : std::to_string(sym->const_value.f32)));
        if (!sym) throw std::runtime_error("常量表达式求值：未定义的标识符 " + name);
        if (sym->kind != SymbolKind::Constant)
            throw std::runtime_error("常量表达式求值：标识符 " + name + " 不是常量");

        ConstValue val;
        if (sym->is_int_const) {
            val.kind = ConstValue::INT;
            val.int_val = sym->const_value.i32;
        } else {
            val.kind = ConstValue::FLOAT;
            val.float_val = sym->const_value.f32;
        }
        return val;
    }
    else if (ctx->HEX_FLOAT() || ctx->DEC_FLOAT()) {
        std::string text;
        if (ctx->HEX_FLOAT()) text = ctx->HEX_FLOAT()->getText();
        else text = ctx->DEC_FLOAT()->getText();
        ConstValue val;
        val.kind = ConstValue::FLOAT;
        val.float_val = ParseFloatLiteral(text);
        DEBUG_MSG("  浮点字面量: " << text << " -> " << val.float_val);
        return val;
    }
    else if (ctx->HEX_INT() || ctx->OCTAL_INT() || ctx->DECIMAL_INT() || ctx->ZERO()) {
        std::string text;
        if (ctx->HEX_INT()) text = ctx->HEX_INT()->getText();
        else if (ctx->OCTAL_INT()) text = ctx->OCTAL_INT()->getText();
        else if (ctx->DECIMAL_INT()) text = ctx->DECIMAL_INT()->getText();
        else text = ctx->ZERO()->getText();
        ConstValue val;
        val.kind = ConstValue::INT;
        val.int_val = static_cast<int>(ParseIntegerLiteral(text));
        DEBUG_MSG("  整数字面量: " << text << " -> " << val.int_val);
        return val;
    }
    else if (ctx->exp()) {
        return EvaluateAddExp(ctx->exp()->addExp());
    }
    else {
        throw std::runtime_error("常量表达式求值：不支持的 PrimaryExp 类型");
    }
}

SymbolTable::ConstValue SymbolTable::EvaluateUnaryExp(SysYParser::UnaryExpContext* ctx) const {
    if (!ctx) throw std::runtime_error("常量表达式求值：无效 UnaryExp");

    if (ctx->primaryExp()) {
        return EvaluatePrimaryExp(ctx->primaryExp());
    }
    else if (ctx->unaryOp()) {
        ConstValue operand = EvaluateUnaryExp(ctx->unaryExp());
        std::string op = ctx->unaryOp()->getText();
        DEBUG_MSG("EvaluateUnaryExp: 操作符=" << op);
        DEBUG_MSG("  操作数=" << (operand.kind==ConstValue::INT ? std::to_string(operand.int_val) : std::to_string(operand.float_val)));

        if (op == "+") {
            return operand;
        }
        else if (op == "-") {
            if (operand.kind == ConstValue::INT) {
                operand.int_val = -operand.int_val;
            } else {
                operand.float_val = -operand.float_val;
            }
            return operand;
        }
        else if (op == "!") {
            if (operand.kind != ConstValue::INT) {
                throw std::runtime_error("常量表达式求值：逻辑非操作数必须是整数");
            }
            ConstValue res;
            res.kind = ConstValue::INT;
            res.int_val = (operand.int_val == 0) ? 1 : 0;
            return res;
        }
        else {
            throw std::runtime_error("常量表达式求值：未知一元运算符 " + op);
        }
    }
    else {
        // 函数调用在常量表达式中不允许
        throw std::runtime_error("常量表达式求值：不允许函数调用");
    }
}

SymbolTable::ConstValue SymbolTable::EvaluateMulExp(SysYParser::MulExpContext* ctx) const {
    if (!ctx) throw std::runtime_error("常量表达式求值：无效 MulExp");

    if (ctx->mulExp()) {
        DEBUG_MSG("EvaluateMulExp: 左子表达式");
        ConstValue left = EvaluateMulExp(ctx->mulExp());
        DEBUG_MSG("  左值=" << (left.kind==ConstValue::INT ? std::to_string(left.int_val) : std::to_string(left.float_val)));
        ConstValue right = EvaluateUnaryExp(ctx->unaryExp());
        

        std::string op;
        DEBUG_MSG("  运算符=" << op);
        DEBUG_MSG("  右值=" << (right.kind==ConstValue::INT ? std::to_string(right.int_val) : std::to_string(right.float_val)));
        if (ctx->MulOp()) op = "*";
        else if (ctx->DivOp()) op = "/";
        else if (ctx->QuoOp()) op = "%";
        else throw std::runtime_error("常量表达式求值：未知乘法运算符");

        bool is_float = (left.kind == ConstValue::FLOAT || right.kind == ConstValue::FLOAT);
        if (is_float) {
            float l = (left.kind == ConstValue::INT) ? static_cast<float>(left.int_val) : left.float_val;
            float r = (right.kind == ConstValue::INT) ? static_cast<float>(right.int_val) : right.float_val;
            ConstValue res;
            res.kind = ConstValue::FLOAT;
            if (op == "*") res.float_val = l * r;
            else if (op == "/") res.float_val = l / r;
            else if (op == "%") throw std::runtime_error("常量表达式求值：浮点数不支持取模运算");
            return res;
        } else {
            int l = left.int_val;
            int r = right.int_val;
            ConstValue res;
            res.kind = ConstValue::INT;
            if (op == "*") res.int_val = l * r;
            else if (op == "/") {
                if (r == 0) throw std::runtime_error("常量表达式求值：除零错误");
                res.int_val = l / r;
            }
            else if (op == "%") {
                if (r == 0) throw std::runtime_error("常量表达式求值：模零错误");
                res.int_val = l % r;
            }
            return res;
        }
    }
    else {
        return EvaluateUnaryExp(ctx->unaryExp());
    }
}

SymbolTable::ConstValue SymbolTable::EvaluateAddExp(SysYParser::AddExpContext* ctx) const {
    if (!ctx) throw std::runtime_error("常量表达式求值：无效 AddExp");

    if (ctx->addExp()) {
        ConstValue left = EvaluateAddExp(ctx->addExp());
        ConstValue right = EvaluateMulExp(ctx->mulExp());

        std::string op;
        if (ctx->AddOp()) op = "+";
        else if (ctx->SubOp()) op = "-";
        else throw std::runtime_error("常量表达式求值：未知加法运算符");

        bool is_float = (left.kind == ConstValue::FLOAT || right.kind == ConstValue::FLOAT);
        if (is_float) {
            float l = (left.kind == ConstValue::INT) ? static_cast<float>(left.int_val) : left.float_val;
            float r = (right.kind == ConstValue::INT) ? static_cast<float>(right.int_val) : right.float_val;
            ConstValue res;
            res.kind = ConstValue::FLOAT;
            if (op == "+") res.float_val = l + r;
            else res.float_val = l - r;
            return res;
        } else {
            int l = left.int_val;
            int r = right.int_val;
            ConstValue res;
            res.kind = ConstValue::INT;
            if (op == "+") res.int_val = l + r;
            else res.int_val = l - r;
            return res;
        }
    }
    else {
        return EvaluateMulExp(ctx->mulExp());
    }
}

int SymbolTable::EvaluateConstExp(SysYParser::ConstExpContext* ctx) const {
    if (!ctx || !ctx->addExp())
        throw std::runtime_error("常量表达式求值：无效 ConstExp");
    DEBUG_MSG("EvaluateConstExp: 表达式文本=" << ctx->getText());
    ConstValue val = EvaluateAddExp(ctx->addExp());
    DEBUG_MSG("  求值结果: " << (val.kind==ConstValue::INT ? std::to_string(val.int_val) : std::to_string(val.float_val)));
    if (val.kind == ConstValue::INT) {
        return val.int_val;
    } else {
        float f = val.float_val;
        int i = static_cast<int>(f);
        if (std::abs(f - i) > 1e-6) {
            throw std::runtime_error("常量表达式求值：浮点常量不能隐式转换为整数");
        }
        return i;
    }
}

float SymbolTable::EvaluateConstExpFloat(SysYParser::ConstExpContext* ctx) const {
    if (!ctx || !ctx->addExp())
        throw std::runtime_error("常量表达式求值：无效 ConstExp");
    DEBUG_MSG("EvaluateConstExpFloat: 表达式文本=" << ctx->getText());
    ConstValue val = EvaluateAddExp(ctx->addExp());
    DEBUG_MSG("  求值结果: " << (val.kind==ConstValue::INT ? std::to_string(val.int_val) : std::to_string(val.float_val)));
    if (val.kind == ConstValue::INT) {
        return static_cast<float>(val.int_val);
    } else {
        return val.float_val;
    }
}

// 递归填充函数，按维度填充值
void SymbolTable::fillArray(
    std::vector<ConstValue>& values,               // 存储最终所有元素（行优先）
    size_t& index,                                 // 当前填充到的位置
    SysYParser::ConstInitValContext* ctx,          // 当前初始化列表节点
    const std::vector<int>& dims,                  // 剩余维度
    size_t dim_idx,                                // 当前维度索引
    std::shared_ptr<ir::Type> base_type) const     // 元素基本类型
{
    DEBUG_MSG("fillArray: 进入，dim_idx=" << dim_idx
              << ", 剩余维度=" << (dims.size() - dim_idx)
              << ", 当前index=" << index);

    // 如果已经是最内层（单个元素）
    if (dim_idx == dims.size()) {
        // 必须是单个表达式
        if (!ctx || !ctx->constExp()) {
            throw std::runtime_error("初始化值不是标量");
        }
        ConstValue val = EvaluateAddExp(ctx->constExp()->addExp());
        // 类型检查和转换...
        DEBUG_MSG("  填充标量值: index=" << index
                  << ", 值=" << (val.kind == ConstValue::INT ? std::to_string(val.int_val) : std::to_string(val.float_val)));
        values[index++] = val;
        return;
    }

    // 当前维度的元素个数
    size_t cur_dim_size = dims[dim_idx];
    DEBUG_MSG("  当前维度大小=" << cur_dim_size << ", 是否是花括号列表=" << (ctx && !ctx->constExp()));

    // 如果是花括号列表，则按子项填充
    if (ctx && !ctx->constExp()) {  // 花括号
        auto sub_vals = ctx->constInitVal();
        DEBUG_MSG("  花括号列表，子项数量=" << sub_vals.size());
        // 对于每个子项，填充一个子数组
        for (size_t i = 0; i < cur_dim_size; ++i) {
            DEBUG_MSG("    处理子项 " << i << " / " << cur_dim_size);
            if (i < sub_vals.size()) {
                fillArray(values, index, sub_vals[i], dims, dim_idx + 1, base_type);
            } else {
                // 子项不足，填充零
                DEBUG_MSG("    子项不足，填充零");
                fillZero(values, index, dims, dim_idx + 1, base_type);
            }
        }
    } else {
        // 不是花括号，即单个值，应视为对当前维度第一个元素的初始化，其余补零
        // 第一个子数组
        DEBUG_MSG("  单个值（非花括号），将填充第一个子数组，其余补零");
        if (ctx && ctx->constExp()) {
            fillArray(values, index, ctx, dims, dim_idx + 1, base_type);
        } else {
            DEBUG_MSG("    无初始化值，第一个子数组也补零");
            fillZero(values, index, dims, dim_idx + 1, base_type);
        }
        // 剩余子数组补零
        for (size_t i = 1; i < cur_dim_size; ++i) {
            DEBUG_MSG("    填充第" << i << "个子数组为零");
            fillZero(values, index, dims, dim_idx + 1, base_type);
        }
    }
    DEBUG_MSG("fillArray: 退出，index=" << index);
}

// 填充指定数量的零
void SymbolTable::fillZero(std::vector<ConstValue>& values, size_t& index,
                           const std::vector<int>& dims, size_t dim_idx,
                           std::shared_ptr<ir::Type> base_type) const 
{
    DEBUG_MSG("fillZero: 进入，dim_idx=" << dim_idx << ", 当前index=" << index);
    if (dim_idx == dims.size()) {
        ConstValue zero;
        if (base_type->IsInt32()) {
            zero.kind = ConstValue::INT;
            zero.int_val = 0;
        } else {
            zero.kind = ConstValue::FLOAT;
            zero.float_val = 0.0f;
        }
        DEBUG_MSG("  填充零值: index=" << index);
        values[index++] = zero;
        return;
    }
    size_t cur_dim_size = dims[dim_idx];
    DEBUG_MSG("  fillZero 当前维度大小=" << cur_dim_size);
    for (size_t i = 0; i < cur_dim_size; ++i) {
        DEBUG_MSG("    fillZero 子项 " << i);
        fillZero(values, index, dims, dim_idx + 1, base_type);
    }
    DEBUG_MSG("fillZero: 退出");
}

std::vector<SymbolTable::ConstValue> SymbolTable::EvaluateConstInitVal(
    SysYParser::ConstInitValContext* ctx,
    const std::vector<int>& dims,
    std::shared_ptr<ir::Type> base_type) const {
    
    // ========== 1. 标量常量（dims 为空）==========
    if (dims.empty()) {
        DEBUG_MSG("  标量常量初始化，表达式=" << ctx->getText());
        if (!ctx || !ctx->constExp()) {
            throw std::runtime_error("标量常量初始化必须使用单个表达式");
        }
        ConstValue val = EvaluateAddExp(ctx->constExp()->addExp());
        
        // 类型兼容性检查
        /*
        if (base_type->IsInt32() && val.kind == ConstValue::FLOAT) {
            throw std::runtime_error("整型常量不能使用浮点常量初始化");
        }
        */
        // 隐式类型转换
        if (base_type->IsInt32() && val.kind == ConstValue::FLOAT) {
            val.kind = ConstValue::INT;
            val.float_val = static_cast<int>(val.int_val);
        }
        if (base_type->IsFloat() && val.kind == ConstValue::INT) {
            val.kind = ConstValue::FLOAT;
            val.float_val = static_cast<float>(val.int_val);
        }
        return {val};  // 返回包含单个值的向量
    }
    
    // ========== 2. 数组常量（dims 非空）==========
    // 计算数组总元素个数
    DEBUG_MSG("EvaluateConstInitVal: 开始，维度=" << dims.size());
    size_t total = 1;
    for (int d : dims) total *= d;
    DEBUG_MSG("  数组常量初始化，总元素数=" << total);

    std::vector<ConstValue> values(total);
    size_t index = 0;
    fillArray(values, index, ctx, dims, 0, base_type);
    
    DEBUG_MSG("EvaluateConstInitVal: 填充完成，最终index=" << index);
    // 可选：打印所有填充的值
    for (size_t i = 0; i < values.size(); ++i) {
        DEBUG_MSG("  values[" << i << "] = " << (values[i].kind == ConstValue::INT ? std::to_string(values[i].int_val) : std::to_string(values[i].float_val)));
    }

    return values;
}

int SymbolTable::EvaluateConstExpression(SysYParser::ExpContext* ctx) const {
    if (!ctx || !ctx->addExp()) {
        throw std::runtime_error("常量表达式求值：无效 ExpContext");
    }
    ConstValue val = EvaluateAddExp(ctx->addExp());
    if (val.kind == ConstValue::INT) {
        return val.int_val;
    } else {
        float f = val.float_val;
        int i = static_cast<int>(f);
        if (std::abs(f - i) > 1e-6) {
            throw std::runtime_error("常量表达式求值：浮点常量不能隐式转换为整数");
        }
        return i;
    }
}