test(test)修改调试输出语句

feature/ir^2
mxr 1 week ago
parent 327e7198b6
commit 0864bc6e73

@ -13,6 +13,8 @@
#include "ir/IR.h"
#include "sem/Sema.h"
#define IRGen_DEBUG 0
namespace ir {
class Module;
class Function;

@ -8,6 +8,8 @@
#include "SysYParser.h"
#include "ir/IR.h"
#define Sema_DEBUG 0
// 表达式信息结构
struct ExprInfo {
std::shared_ptr<ir::Type> type = nullptr;

File diff suppressed because it is too large Load Diff

@ -30,14 +30,14 @@ int TryGetConstInt(SysYParser::ConstExpContext* ctx) {
// 注意visitBlock 已经在 IRGenFunc.cpp 中实现,这里不要重复定义
std::any IRGenImpl::visitDecl(SysYParser::DeclContext* ctx) {
std::cerr << "[DEBUG] visitDecl: 开始处理声明" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitDecl: 开始处理声明" << std::endl;
if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少变量声明"));
}
// 处理 varDecl
if (auto* varDecl = ctx->varDecl()) {
std::cerr << "[DEBUG] visitDecl: 处理变量声明" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitDecl: 处理变量声明" << std::endl;
// 检查类型
if (varDecl->bType() && varDecl->bType()->Int()) {
for (auto* varDef : varDecl->varDef()) {
@ -50,7 +50,7 @@ std::any IRGenImpl::visitDecl(SysYParser::DeclContext* ctx) {
// 处理 constDecl
if (ctx->constDecl()) {
std::cerr << "[DEBUG] visitDecl: 处理常量声明" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitDecl: 处理常量声明" << std::endl;
auto* constDecl = ctx->constDecl();
if (constDecl->bType() && constDecl->bType()->Int()) {
@ -63,18 +63,18 @@ std::any IRGenImpl::visitDecl(SysYParser::DeclContext* ctx) {
throw std::runtime_error(FormatError("irgen", "未知的常量类型"));
}
}
std::cerr << "[DEBUG] visitDecl: 声明处理完成" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitDecl: 声明处理完成" << std::endl;
return {};
}
// 在 IRGenDecl.cpp 中确保有这个函数
std::any IRGenImpl::visitConstDecl(SysYParser::ConstDeclContext* ctx) {
std::cerr << "[DEBUG] visitConstDecl: 开始处理常量声明" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitConstDecl: 开始处理常量声明" << std::endl;
if (!ctx) {
throw std::runtime_error(FormatError("irgen", "非法常量声明"));
}
std::cerr << "[DEBUG] visitConstDecl: processing constant declaration" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitConstDecl: processing constant declaration" << std::endl;
// 检查类型
if (ctx->bType()) {
@ -95,7 +95,7 @@ std::any IRGenImpl::visitConstDecl(SysYParser::ConstDeclContext* ctx) {
throw std::runtime_error(FormatError("irgen", "常量声明缺少类型"));
}
std::cerr << "[DEBUG] visitConstDecl: 常量声明处理完成" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitConstDecl: 常量声明处理完成" << std::endl;
return {};
}
@ -115,7 +115,7 @@ std::any IRGenImpl::visitConstDef(SysYParser::ConstDefContext* ctx) {
if (constDecl && constDecl->bType()) {
if (constDecl->bType()->Float()) {
is_float = true;
std::cerr << "[DEBUG] visitConstDef: 常量 " << const_name << " 是 float 类型" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitConstDef: 常量 " << const_name << " 是 float 类型" << std::endl;
}
}
@ -243,7 +243,7 @@ std::any IRGenImpl::visitConstDef(SysYParser::ConstDefContext* ctx) {
// TO DO:visitVarDef来区分全局和局部变量并且正确处理数组变量的定义和初始化
std::any IRGenImpl::visitVarDef(SysYParser::VarDefContext* ctx) {
std::cerr << "[DEBUG] visitVarDef: 开始处理变量定义" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitVarDef: 开始处理变量定义" << std::endl;
if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少变量定义"));
}
@ -253,22 +253,22 @@ std::any IRGenImpl::visitVarDef(SysYParser::VarDefContext* ctx) {
}
std::string varName = ctx->Ident()->getText();
std::cerr << "[DEBUG] visitVarDef: 变量名称: " << varName << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitVarDef: 变量名称: " << varName << std::endl;
// 防止同一个变量被多次分配存储空间。
if (storage_map_.find(ctx) != storage_map_.end()) {
throw std::runtime_error(FormatError("irgen", "声明重复生成存储槽位: " + varName));
}
bool is_array = !ctx->constExp().empty();
std::cerr << "[DEBUG] visitVarDef: 是否为数组: " << (is_array ? "" : "") << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitVarDef: 是否为数组: " << (is_array ? "" : "") << std::endl;
// 使用 func_ 来判断func_ == nullptr 表示在全局作用域
if (func_ == nullptr) {
std::cerr << "[DEBUG] visitVarDef: 处理全局变量" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitVarDef: 处理全局变量" << std::endl;
// 全局变量处理
return HandleGlobalVariable(ctx, varName, is_array);
} else {
std::cerr << "[DEBUG] visitVarDef: 处理局部变量" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitVarDef: 处理局部变量" << std::endl;
// 局部变量处理
return HandleLocalVariable(ctx, varName, is_array);
}
@ -277,7 +277,7 @@ std::any IRGenImpl::visitVarDef(SysYParser::VarDefContext* ctx) {
std::any IRGenImpl::HandleGlobalVariable(SysYParser::VarDefContext* ctx,
const std::string& varName,
bool is_array) {
std::cerr << "[DEBUG] HandleGlobalVariable: 开始处理全局变量 " << varName << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleGlobalVariable: 开始处理全局变量 " << varName << std::endl;
// 获取变量类型int 或 float
bool is_float = false;
@ -285,9 +285,9 @@ std::any IRGenImpl::HandleGlobalVariable(SysYParser::VarDefContext* ctx,
if (varDecl && varDecl->bType()) {
if (varDecl->bType()->Float()) {
is_float = true;
std::cerr << "[DEBUG] HandleGlobalVariable: 变量 " << varName << " 是 float 类型" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleGlobalVariable: 变量 " << varName << " 是 float 类型" << std::endl;
} else if (varDecl->bType()->Int()) {
std::cerr << "[DEBUG] HandleGlobalVariable: 变量 " << varName << " 是 int 类型" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleGlobalVariable: 变量 " << varName << " 是 int 类型" << std::endl;
}
}
@ -307,7 +307,7 @@ std::any IRGenImpl::HandleGlobalVariable(SysYParser::VarDefContext* ctx,
total_size *= dim_size;
}
std::cerr << "[DEBUG] HandleGlobalVariable: 数组总大小: " << total_size << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleGlobalVariable: 数组总大小: " << total_size << std::endl;
// 创建数组类型
std::shared_ptr<ir::Type> element_type;
@ -319,17 +319,17 @@ std::any IRGenImpl::HandleGlobalVariable(SysYParser::VarDefContext* ctx,
auto array_type = ir::Type::GetArrayType(element_type, dimensions);
ir::GlobalValue* global_array = module_.CreateGlobal(varName, array_type);
std::cerr << "[DEBUG] HandleGlobalVariable: 创建全局数组: " << varName << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleGlobalVariable: 创建全局数组: " << varName << std::endl;
// 处理初始化值
std::vector<ir::ConstantValue*> init_consts;
if (auto* initVal = ctx->initVal()) {
std::cerr << "[DEBUG] HandleGlobalVariable: 处理初始化值" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleGlobalVariable: 处理初始化值" << std::endl;
auto result = initVal->accept(this);
if (result.has_value()) {
try {
auto init_vec = std::any_cast<std::vector<ir::Value*>>(result);
std::cerr << "[DEBUG] HandleGlobalVariable: 获取到初始化值列表, 大小: " << init_vec.size() << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleGlobalVariable: 获取到初始化值列表, 大小: " << init_vec.size() << std::endl;
for (auto* val : init_vec) {
if (auto* const_int = dynamic_cast<ir::ConstantInt*>(val)) {
init_consts.push_back(const_int);
@ -347,7 +347,7 @@ std::any IRGenImpl::HandleGlobalVariable(SysYParser::VarDefContext* ctx,
} catch (const std::bad_any_cast&) {
try {
ir::Value* single_val = std::any_cast<ir::Value*>(result);
std::cerr << "[DEBUG] HandleGlobalVariable: 获取到单个初始化值" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleGlobalVariable: 获取到单个初始化值" << std::endl;
if (auto* const_int = dynamic_cast<ir::ConstantInt*>(single_val)) {
init_consts.push_back(const_int);
} else if (auto* const_float = dynamic_cast<ir::ConstantFloat*>(single_val)) {
@ -378,7 +378,7 @@ std::any IRGenImpl::HandleGlobalVariable(SysYParser::VarDefContext* ctx,
// 设置全局数组的初始化器
if (!init_consts.empty()) {
global_array->SetInitializer(init_consts);
std::cerr << "[DEBUG] HandleGlobalVariable: 设置全局数组初始化器" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleGlobalVariable: 设置全局数组初始化器" << std::endl;
}
// 存储全局变量引用
@ -395,12 +395,12 @@ std::any IRGenImpl::HandleGlobalVariable(SysYParser::VarDefContext* ctx,
}
ir::GlobalValue* global_var = module_.CreateGlobal(varName, var_type);
std::cerr << "[DEBUG] HandleGlobalVariable: 创建全局标量变量: " << varName << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleGlobalVariable: 创建全局标量变量: " << varName << std::endl;
// 处理初始化值
ir::ConstantValue* init_value = nullptr;
if (auto* initVal = ctx->initVal()) {
std::cerr << "[DEBUG] HandleGlobalVariable: 处理标量初始化值" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleGlobalVariable: 处理标量初始化值" << std::endl;
auto result = initVal->accept(this);
if (result.has_value()) {
try {
@ -461,7 +461,7 @@ std::any IRGenImpl::HandleGlobalVariable(SysYParser::VarDefContext* ctx,
std::any IRGenImpl::HandleLocalVariable(SysYParser::VarDefContext* ctx,
const std::string& varName,
bool is_array) {
std::cerr << "[DEBUG] HandleLocalVariable: 开始处理局部变量 " << varName << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleLocalVariable: 开始处理局部变量 " << varName << std::endl;
// 获取变量类型
bool is_float = false;
@ -469,7 +469,7 @@ std::any IRGenImpl::HandleLocalVariable(SysYParser::VarDefContext* ctx,
if (varDecl && varDecl->bType()) {
if (varDecl->bType()->Float()) {
is_float = true;
std::cerr << "[DEBUG] HandleLocalVariable: 变量 " << varName << " 是 float 类型" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleLocalVariable: 变量 " << varName << " 是 float 类型" << std::endl;
}
}
@ -650,31 +650,31 @@ std::any IRGenImpl::HandleLocalVariable(SysYParser::VarDefContext* ctx,
std::any IRGenImpl::visitInitVal(SysYParser::InitValContext* ctx) {
std::cerr << "[DEBUG] visitInitVal: 开始处理初始化值" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitInitVal: 开始处理初始化值" << std::endl;
if (!ctx) {
throw std::runtime_error(FormatError("irgen", "非法初始化值"));
}
// 如果是单个表达式
if (ctx->exp()) {
std::cerr << "[DEBUG] visitInitVal: 处理表达式初始化" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitInitVal: 处理表达式初始化" << std::endl;
return EvalExpr(*ctx->exp());
}
// 如果是聚合初始化(花括号列表)
else if (!ctx->initVal().empty()) {
std::cerr << "[DEBUG] visitInitVal: 处理聚合初始化" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitInitVal: 处理聚合初始化" << std::endl;
// 处理嵌套聚合初始化
return ProcessNestedInitVals(ctx);
}
std::cerr << "[DEBUG] visitInitVal: 空初始化列表" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitInitVal: 空初始化列表" << std::endl;
// 空初始化列表
return std::vector<ir::Value*>{};
}
// 新增:处理嵌套聚合初始化的辅助函数
std::vector<ir::Value*> IRGenImpl::ProcessNestedInitVals(SysYParser::InitValContext* ctx) {
std::cerr << "[DEBUG] ProcessNestedInitVals: 开始处理嵌套初始化值" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] ProcessNestedInitVals: 开始处理嵌套初始化值" << std::endl;
std::vector<ir::Value*> all_values;
for (auto* init_val : ctx->initVal()) {
@ -684,13 +684,13 @@ std::vector<ir::Value*> IRGenImpl::ProcessNestedInitVals(SysYParser::InitValCont
// 尝试获取单个值
ir::Value* value = std::any_cast<ir::Value*>(result);
all_values.push_back(value);
std::cerr << "[DEBUG] ProcessNestedInitVals: 获取到单个值" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] ProcessNestedInitVals: 获取到单个值" << std::endl;
} catch (const std::bad_any_cast&) {
try {
// 尝试获取值列表(嵌套情况)
std::vector<ir::Value*> nested_values =
std::any_cast<std::vector<ir::Value*>>(result);
std::cerr << "[DEBUG] ProcessNestedInitVals: 获取到嵌套值列表, 大小: " << nested_values.size() << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] ProcessNestedInitVals: 获取到嵌套值列表, 大小: " << nested_values.size() << std::endl;
// 展平嵌套的值
all_values.insert(all_values.end(),
nested_values.begin(), nested_values.end());
@ -702,18 +702,18 @@ std::vector<ir::Value*> IRGenImpl::ProcessNestedInitVals(SysYParser::InitValCont
}
}
} else {
std::cerr << "[DEBUG] ProcessNestedInitVals: 无初始化值结果" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] ProcessNestedInitVals: 无初始化值结果" << std::endl;
}
}
std::cerr << "[DEBUG] ProcessNestedInitVals: 共获取 " << all_values.size() << " 个初始化值" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] ProcessNestedInitVals: 共获取 " << all_values.size() << " 个初始化值" << std::endl;
return all_values;
}
int IRGenImpl::TryEvaluateConstInt(SysYParser::ConstExpContext* ctx) {
std::cerr << "[DEBUG] TryEvaluateConstInt: 开始求值常量表达式" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] TryEvaluateConstInt: 开始求值常量表达式" << std::endl;
if (!ctx) {
std::cerr << "[DEBUG] TryEvaluateConstInt: ctx is null" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] TryEvaluateConstInt: ctx is null" << std::endl;
return 0;
}

@ -22,7 +22,7 @@
// - ...
ir::Value* IRGenImpl::EvalExpr(SysYParser::ExpContext& expr) {
std::cout << "[DEBUG IRGEN] EvalExpr: " << expr.getText() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] EvalExpr: " << expr.getText() << std::endl;
try {
auto result_any = expr.accept(this);
@ -33,7 +33,7 @@ ir::Value* IRGenImpl::EvalExpr(SysYParser::ExpContext& expr) {
try {
ir::Value* result = std::any_cast<ir::Value*>(result_any);
std::cerr << "[DEBUG] EvalExpr: success, result = " << (void*)result << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] EvalExpr: success, result = " << (void*)result << std::endl;
return result;
} catch (const std::bad_any_cast& e) {
std::cerr << "[ERROR] EvalExpr: bad any_cast - " << e.what() << std::endl;
@ -42,7 +42,7 @@ ir::Value* IRGenImpl::EvalExpr(SysYParser::ExpContext& expr) {
// 尝试其他可能的类型
try {
// 检查是否是无值的any可能来自visit函数返回{}
std::cerr << "[DEBUG] EvalExpr: Trying to handle empty any" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] EvalExpr: Trying to handle empty any" << std::endl;
return nullptr;
} catch (...) {
throw std::runtime_error(FormatError("irgen", "表达式求值返回了错误的类型"));
@ -63,18 +63,18 @@ ir::Value* IRGenImpl::EvalCond(SysYParser::CondContext& cond) {
// 基本表达式:数字、变量、括号表达式
std::any IRGenImpl::visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) {
std::cout << "[DEBUG IRGEN] visitPrimaryExp: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] visitPrimaryExp: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少基本表达式"));
}
std::cerr << "[DEBUG] visitPrimaryExp" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitPrimaryExp" << std::endl;
// 处理数字字面量
if (ctx->DECIMAL_INT()) {
int value = std::stoi(ctx->DECIMAL_INT()->getText());
ir::Value* const_int = builder_.CreateConstInt(value);
std::cerr << "[DEBUG] visitPrimaryExp: constant int " << value
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitPrimaryExp: constant int " << value
<< " created as " << (void*)const_int << std::endl;
return static_cast<ir::Value*>(const_int);
}
@ -92,7 +92,7 @@ std::any IRGenImpl::visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) {
value = 0.0f;
}
ir::Value* const_float = builder_.CreateConstFloat(value);
std::cerr << "[DEBUG] visitPrimaryExp: constant hex float " << value
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitPrimaryExp: constant hex float " << value
<< " created as " << (void*)const_float << std::endl;
return static_cast<ir::Value*>(const_float);
}
@ -109,7 +109,7 @@ std::any IRGenImpl::visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) {
value = 0.0f;
}
ir::Value* const_float = builder_.CreateConstFloat(value);
std::cerr << "[DEBUG] visitPrimaryExp: constant dec float " << value
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitPrimaryExp: constant dec float " << value
<< " created as " << (void*)const_float << std::endl;
return static_cast<ir::Value*>(const_float);
}
@ -135,13 +135,13 @@ std::any IRGenImpl::visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) {
// 处理变量
if (ctx->lVal()) {
std::cerr << "[DEBUG] visitPrimaryExp: visiting lVal" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitPrimaryExp: visiting lVal" << std::endl;
return ctx->lVal()->accept(this);
}
// 处理括号表达式
if (ctx->L_PAREN() && ctx->exp()) {
std::cerr << "[DEBUG] visitPrimaryExp: visiting parenthesized expression" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitPrimaryExp: visiting parenthesized expression" << std::endl;
return EvalExpr(*ctx->exp());
}
@ -160,13 +160,13 @@ std::any IRGenImpl::visitLVal(SysYParser::LValContext* ctx) {
}
std::string varName = ctx->Ident()->getText();
std::cerr << "[DEBUG] visitLVal: " << varName << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitLVal: " << varName << std::endl;
// 优先检查是否是常量
auto const_it = const_value_map_.find(varName);
if (const_it != const_value_map_.end()) {
// 常量直接返回值不需要load
std::cerr << "[DEBUG] visitLVal: constant " << varName << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitLVal: constant " << varName << std::endl;
return static_cast<ir::Value*>(const_it->second);
}
@ -254,7 +254,7 @@ std::any IRGenImpl::visitLVal(SysYParser::LValContext* ctx) {
}
std::any IRGenImpl::visitAddExp(SysYParser::AddExpContext* ctx) {
std::cout << "[DEBUG IRGEN] visitAddExp: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] visitAddExp: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (!ctx) {
throw std::runtime_error(FormatError("irgen", "非法加法表达式"));
}
@ -278,7 +278,7 @@ std::any IRGenImpl::visitAddExp(SysYParser::AddExpContext* ctx) {
}
ir::Value* right = std::any_cast<ir::Value*>(right_any);
std::cerr << "[DEBUG] visitAddExp: left=" << (void*)left
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitAddExp: left=" << (void*)left
<< ", type=" << (left->GetType()->IsFloat() ? "float" : "int")
<< ", right=" << (void*)right
<< ", type=" << (right->GetType()->IsFloat() ? "float" : "int") << std::endl;
@ -318,7 +318,7 @@ std::any IRGenImpl::visitAddExp(SysYParser::AddExpContext* ctx) {
std::any IRGenImpl::visitMulExp(SysYParser::MulExpContext* ctx) {
std::cout << "[DEBUG IRGEN] visitMulExp: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] visitMulExp: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (!ctx) {
throw std::runtime_error(FormatError("irgen", "非法乘法表达式"));
}
@ -342,7 +342,7 @@ std::any IRGenImpl::visitMulExp(SysYParser::MulExpContext* ctx) {
}
ir::Value* right = std::any_cast<ir::Value*>(right_any);
std::cerr << "[DEBUG] visitMulExp: left=" << (void*)left
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitMulExp: left=" << (void*)left
<< ", type=" << (left->GetType()->IsFloat() ? "float" : "int")
<< ", right=" << (void*)right
<< ", type=" << (right->GetType()->IsFloat() ? "float" : "int") << std::endl;
@ -438,14 +438,14 @@ std::any IRGenImpl::visitCallExp(SysYParser::UnaryExpContext* ctx) {
}
std::string funcName = ctx->Ident()->getText();
std::cout << "[DEBUG IRGEN] visitCallExp: 调用函数 " << funcName << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] visitCallExp: 调用函数 " << funcName << std::endl;
// 查找函数对象
ir::Function* callee = module_.FindFunction(funcName);
// 如果没找到,可能是运行时函数还没声明,尝试动态声明
if (!callee) {
std::cout << "[DEBUG IRGEN] 函数 " << funcName << " 未找到,尝试动态声明" << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] 函数 " << funcName << " 未找到,尝试动态声明" << std::endl;
// 根据函数名动态创建运行时函数声明
callee = CreateRuntimeFunctionDecl(funcName);
@ -460,7 +460,7 @@ std::any IRGenImpl::visitCallExp(SysYParser::UnaryExpContext* ctx) {
auto argList = ctx->funcRParams()->accept(this);
try {
args = std::any_cast<std::vector<ir::Value*>>(argList);
std::cout << "[DEBUG IRGEN] visitCallExp: 收集到 " << args.size() << " 个参数" << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] visitCallExp: 收集到 " << args.size() << " 个参数" << std::endl;
} catch (const std::bad_any_cast& e) {
std::cerr << "[ERROR] visitCallExp: 函数调用参数类型错误: " << e.what() << std::endl;
}
@ -475,13 +475,13 @@ std::any IRGenImpl::visitCallExp(SysYParser::UnaryExpContext* ctx) {
return static_cast<ir::Value*>(builder_.CreateConstInt(0));
}
std::cout << "[DEBUG IRGEN] visitCallExp: 函数调用完成,返回值 " << (void*)callResult << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] visitCallExp: 函数调用完成,返回值 " << (void*)callResult << std::endl;
return static_cast<ir::Value*>(callResult);
}
// 动态创建运行时函数声明的辅助函数
ir::Function* IRGenImpl::CreateRuntimeFunctionDecl(const std::string& funcName) {
std::cout << "[DEBUG IRGEN] CreateRuntimeFunctionDecl: " << funcName << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] CreateRuntimeFunctionDecl: " << funcName << std::endl;
// 根据常见运行时函数名创建对应的函数类型
if (funcName == "getint" || funcName == "getch") {
@ -718,7 +718,7 @@ std::any IRGenImpl::visitRelExp(SysYParser::RelExpContext* ctx) {
auto* lhs = std::any_cast<ir::Value*>(left_any);
auto* rhs = std::any_cast<ir::Value*>(right_any);
std::cerr << "[DEBUG] visitRelExp: left=" << (void*)lhs
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitRelExp: left=" << (void*)lhs
<< ", type=" << (lhs->GetType()->IsFloat() ? "float" : "int")
<< ", right=" << (void*)rhs
<< ", type=" << (rhs->GetType()->IsFloat() ? "float" : "int") << std::endl;
@ -792,7 +792,7 @@ std::any IRGenImpl::visitEqExp(SysYParser::EqExpContext* ctx) {
auto* lhs = std::any_cast<ir::Value*>(left_any);
auto* rhs = std::any_cast<ir::Value*>(right_any);
std::cerr << "[DEBUG] visitEqExp: left=" << (void*)lhs
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitEqExp: left=" << (void*)lhs
<< ", type=" << (lhs->GetType()->IsFloat() ? "float" : "int")
<< ", right=" << (void*)rhs
<< ", type=" << (rhs->GetType()->IsFloat() ? "float" : "int") << std::endl;
@ -839,7 +839,7 @@ std::any IRGenImpl::visitEqExp(SysYParser::EqExpContext* ctx) {
ir::Value* IRGenImpl::EvalAssign(SysYParser::StmtContext* ctx) {
std::cout << "[DEBUG IRGEN] visitCond: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] visitCond: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (!ctx || !ctx->lVal() || !ctx->exp()) {
throw std::runtime_error(FormatError("irgen", "非法赋值语句"));
}
@ -888,8 +888,8 @@ ir::Value* IRGenImpl::EvalAssign(SysYParser::StmtContext* ctx) {
} else {
// 普通标量赋值
// 调试输出指针类型
std::cerr << "[DEBUG] base_ptr type: " << base_ptr->GetType() << std::endl;
std::cerr << "[DEBUG] rhs type: " << rhs->GetType()<< std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] base_ptr type: " << base_ptr->GetType() << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] rhs type: " << rhs->GetType()<< std::endl;
// 如果 base_ptr 不是指针类型,可能需要特殊处理
if (!base_ptr->GetType()->IsPtrInt32()) {

@ -31,7 +31,7 @@ IRGenImpl::IRGenImpl(ir::Module& module, const SemanticContext& sema)
}
void IRGenImpl::AddRuntimeFunctions() {
std::cout << "[DEBUG IRGEN] 添加运行时库函数声明" << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] 添加运行时库函数声明" << std::endl;
// 输入函数(返回 int
module_.CreateFunction("getint",
@ -101,12 +101,12 @@ void IRGenImpl::AddRuntimeFunctions() {
ir::Type::GetInt32Type(),
ir::Type::GetInt32Type()}));
std::cout << "[DEBUG IRGEN] 运行时库函数声明完成" << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] 运行时库函数声明完成" << std::endl;
}
// 修正:没有 mainFuncDef通过函数名找到 main
std::any IRGenImpl::visitCompUnit(SysYParser::CompUnitContext* ctx) {
std::cout << "[DEBUG IRGEN] visitCompUnit" << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] visitCompUnit" << std::endl;
if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少编译单元"));
}
@ -129,7 +129,7 @@ std::any IRGenImpl::visitCompUnit(SysYParser::CompUnitContext* ctx) {
}
std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) {
std::cout << "[DEBUG IRGEN] visitFuncDef: " << (ctx && ctx->Ident() ? ctx->Ident()->getText() : "<null>") << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] visitFuncDef: " << (ctx && ctx->Ident() ? ctx->Ident()->getText() : "<null>") << std::endl;
if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少函数定义"));
}
@ -191,7 +191,7 @@ std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) {
auto func_type = ir::Type::GetFunctionType(ret_type, param_types);
// 调试输出
std::cerr << "[DEBUG] visitFuncDef: 创建函数 " << funcName
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitFuncDef: 创建函数 " << funcName
<< ",返回类型: " << (ret_type->IsVoid() ? "void" : ret_type->IsFloat() ? "float" : "int")
<< ",参数数量: " << param_types.size() << std::endl;
@ -204,7 +204,7 @@ std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) {
throw std::runtime_error(FormatError("irgen", "创建函数失败: " + funcName));
}
std::cerr << "[DEBUG] visitFuncDef: 函数对象地址: " << (void*)func_ << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitFuncDef: 函数对象地址: " << (void*)func_ << std::endl;
// 设置插入点
auto* entry_block = func_->GetEntry();
@ -251,7 +251,8 @@ std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) {
throw std::runtime_error(FormatError("irgen", "函数对象无效"));
}
std::cerr << "[DEBUG] visitFuncDef: 为函数 " << funcName
if (IRGen_DEBUG)
std::cerr << "[DEBUG] visitFuncDef: 为函数 " << funcName
<< " 添加参数 " << name << ",类型: "
<< (param_ty->IsInt32() ? "int32" : param_ty->IsFloat() ? "float" :
param_ty->IsPtrInt32() ? "ptr_int32" : param_ty->IsPtrFloat() ? "ptr_float" : "other")
@ -288,17 +289,18 @@ std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) {
builder_.CreateStore(added_arg, slot);
param_map_[name] = slot;
std::cerr << "[DEBUG] visitFuncDef: 参数 " << name << " 处理完成" << std::endl;
if (IRGen_DEBUG)
std::cerr << "[DEBUG] visitFuncDef: 参数 " << name << " 处理完成" << std::endl;
}
}
// 生成函数体
std::cerr << "[DEBUG] visitFuncDef: 开始生成函数体" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitFuncDef: 开始生成函数体" << std::endl;
ctx->block()->accept(this);
// 如果函数没有终止指令,添加默认返回
if (!func_->GetEntry()->HasTerminator()) {
std::cerr << "[DEBUG] visitFuncDef: 函数体没有终止指令,添加默认返回" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitFuncDef: 函数体没有终止指令,添加默认返回" << std::endl;
auto retVal = builder_.CreateConstInt(0);
builder_.CreateRet(retVal);
}
@ -311,14 +313,14 @@ std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) {
throw;
}
std::cerr << "[DEBUG] visitFuncDef: 函数 " << funcName << " 生成完成" << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] visitFuncDef: 函数 " << funcName << " 生成完成" << std::endl;
func_ = nullptr;
return {};
}
std::any IRGenImpl::visitBlock(SysYParser::BlockContext* ctx) {
std::cout << "[DEBUG IRGEN] visitBlock: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] visitBlock: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少语句块"));
}
@ -333,7 +335,7 @@ std::any IRGenImpl::visitBlock(SysYParser::BlockContext* ctx) {
}
auto* cur = builder_.GetInsertBlock();
std::cout << "[DEBUG] current insert block: "
if (IRGen_DEBUG) std::cout << "[DEBUG] current insert block: "
<< (cur ? cur->GetName() : "<null>") << std::endl;
if (cur && cur->HasTerminator()) {
break;
@ -351,7 +353,7 @@ IRGenImpl::BlockFlow IRGenImpl::VisitBlockItemResult(
}
// 用于遍历块内项,返回是否继续访问后续项(如遇到 return/break/continue 则终止访问)
std::any IRGenImpl::visitBlockItem(SysYParser::BlockItemContext* ctx) {
std::cout << "[DEBUG IRGEN] visitBlockItem: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] visitBlockItem: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少块内项"));
}

@ -16,7 +16,7 @@
// - 空语句、块语句嵌套分发之外的更多语句形态
std::any IRGenImpl::visitStmt(SysYParser::StmtContext* ctx) {
std::cout << "[DEBUG IRGEN] visitStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] visitStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少语句"));
}
@ -65,7 +65,7 @@ std::any IRGenImpl::visitStmt(SysYParser::StmtContext* ctx) {
// 修改 HandleReturnStmt 函数
IRGenImpl::BlockFlow IRGenImpl::HandleReturnStmt(SysYParser::StmtContext* ctx) {
std::cout << "[DEBUG IRGEN] HandleReturnStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] HandleReturnStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (!ctx) {
throw std::runtime_error(FormatError("irgen", "缺少 return 语句"));
}
@ -123,7 +123,7 @@ IRGenImpl::BlockFlow IRGenImpl::HandleReturnStmt(SysYParser::StmtContext* ctx) {
// if语句待实现
IRGenImpl::BlockFlow IRGenImpl::HandleIfStmt(SysYParser::StmtContext* ctx) {
std::cout << "[DEBUG IRGEN] HandleIfStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] HandleIfStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl;
auto* cond = ctx->cond();
auto* thenStmt = ctx->stmt(0);
@ -134,10 +134,10 @@ IRGenImpl::BlockFlow IRGenImpl::HandleIfStmt(SysYParser::StmtContext* ctx) {
auto* elseBlock = (ctx->Else() && elseStmt) ? func_->CreateBlock("else") : nullptr;
auto* mergeBlock = func_->CreateBlock("merge");
std::cout << "[DEBUG IF] thenBlock: " << thenBlock->GetName() << std::endl;
if (elseBlock) std::cout << "[DEBUG IF] elseBlock: " << elseBlock->GetName() << std::endl;
std::cout << "[DEBUG IF] mergeBlock: " << mergeBlock->GetName() << std::endl;
std::cout << "[DEBUG IF] current insert block before cond: "
if (IRGen_DEBUG) std::cout << "[DEBUG IF] thenBlock: " << thenBlock->GetName() << std::endl;
if (elseBlock) if (IRGen_DEBUG) std::cout << "[DEBUG IF] elseBlock: " << elseBlock->GetName() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IF] mergeBlock: " << mergeBlock->GetName() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IF] current insert block before cond: "
<< builder_.GetInsertBlock()->GetName() << std::endl;
// 生成条件
@ -145,66 +145,66 @@ IRGenImpl::BlockFlow IRGenImpl::HandleIfStmt(SysYParser::StmtContext* ctx) {
// 创建条件跳转
if (elseBlock) {
std::cout << "[DEBUG IF] Creating condbr: " << condValue->GetName()
if (IRGen_DEBUG) std::cout << "[DEBUG IF] Creating condbr: " << condValue->GetName()
<< " -> " << thenBlock->GetName() << ", " << elseBlock->GetName() << std::endl;
builder_.CreateCondBr(condValue, thenBlock, elseBlock);
} else {
std::cout << "[DEBUG IF] Creating condbr: " << condValue->GetName()
if (IRGen_DEBUG) std::cout << "[DEBUG IF] Creating condbr: " << condValue->GetName()
<< " -> " << thenBlock->GetName() << ", " << mergeBlock->GetName() << std::endl;
builder_.CreateCondBr(condValue, thenBlock, mergeBlock);
}
// 生成 then 分支
std::cout << "[DEBUG IF] Generating then branch in block: " << thenBlock->GetName() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IF] Generating then branch in block: " << thenBlock->GetName() << std::endl;
builder_.SetInsertPoint(thenBlock);
auto thenResult = thenStmt->accept(this);
bool thenTerminated = (std::any_cast<BlockFlow>(thenResult) == BlockFlow::Terminated);
std::cout << "[DEBUG IF] then branch terminated: " << thenTerminated << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IF] then branch terminated: " << thenTerminated << std::endl;
if (!thenTerminated) {
std::cout << "[DEBUG IF] Adding br to merge block from then" << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IF] Adding br to merge block from then" << std::endl;
builder_.CreateBr(mergeBlock);
}
std::cout << "[DEBUG IF] then block has terminator: " << thenBlock->HasTerminator() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IF] then block has terminator: " << thenBlock->HasTerminator() << std::endl;
// 生成 else 分支
bool elseTerminated = false;
if (elseBlock) {
std::cout << "[DEBUG IF] Generating else branch in block: " << elseBlock->GetName() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IF] Generating else branch in block: " << elseBlock->GetName() << std::endl;
builder_.SetInsertPoint(elseBlock);
auto elseResult = elseStmt->accept(this);
elseTerminated = (std::any_cast<BlockFlow>(elseResult) == BlockFlow::Terminated);
std::cout << "[DEBUG IF] else branch terminated: " << elseTerminated << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IF] else branch terminated: " << elseTerminated << std::endl;
if (!elseTerminated) {
std::cout << "[DEBUG IF] Adding br to merge block from else" << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IF] Adding br to merge block from else" << std::endl;
builder_.CreateBr(mergeBlock);
}
std::cout << "[DEBUG IF] else block has terminator: " << elseBlock->HasTerminator() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IF] else block has terminator: " << elseBlock->HasTerminator() << std::endl;
}
// 决定后续插入点
std::cout << "[DEBUG IF] thenTerminated=" << thenTerminated
if (IRGen_DEBUG) std::cout << "[DEBUG IF] thenTerminated=" << thenTerminated
<< ", elseTerminated=" << elseTerminated << std::endl;
if (elseBlock) {
if (thenTerminated && elseTerminated) {
auto* afterIfBlock = func_->CreateBlock("after.if");
std::cout << "[DEBUG IF] Both branches terminated, creating new block: "
if (IRGen_DEBUG) std::cout << "[DEBUG IF] Both branches terminated, creating new block: "
<< afterIfBlock->GetName() << std::endl;
builder_.SetInsertPoint(afterIfBlock);
} else {
std::cout << "[DEBUG IF] Setting insert point to merge block: "
if (IRGen_DEBUG) std::cout << "[DEBUG IF] Setting insert point to merge block: "
<< mergeBlock->GetName() << std::endl;
builder_.SetInsertPoint(mergeBlock);
}
} else {
std::cout << "[DEBUG IF] No else, setting insert point to merge block: "
if (IRGen_DEBUG) std::cout << "[DEBUG IF] No else, setting insert point to merge block: "
<< mergeBlock->GetName() << std::endl;
builder_.SetInsertPoint(mergeBlock);
}
std::cout << "[DEBUG IF] Final insert block: "
if (IRGen_DEBUG) std::cout << "[DEBUG IF] Final insert block: "
<< builder_.GetInsertBlock()->GetName() << std::endl;
return BlockFlow::Continue;
@ -212,56 +212,56 @@ IRGenImpl::BlockFlow IRGenImpl::HandleIfStmt(SysYParser::StmtContext* ctx) {
// while语句待实现IRGenImpl::BlockFlow IRGenImpl::HandleWhileStmt(SysYParser::StmtContext* ctx) {
IRGenImpl::BlockFlow IRGenImpl::HandleWhileStmt(SysYParser::StmtContext* ctx) {
std::cout << "[DEBUG IRGEN] HandleWhileStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] HandleWhileStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (!ctx || !ctx->cond() || !ctx->stmt(0)) {
throw std::runtime_error(FormatError("irgen", "非法 while 语句"));
}
std::cout << "[DEBUG WHILE] Current insert block before while: "
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] Current insert block before while: "
<< builder_.GetInsertBlock()->GetName() << std::endl;
auto* condBlock = func_->CreateBlock("while.cond");
auto* bodyBlock = func_->CreateBlock("while.body");
auto* exitBlock = func_->CreateBlock("while.exit");
std::cout << "[DEBUG WHILE] condBlock: " << condBlock->GetName() << std::endl;
std::cout << "[DEBUG WHILE] bodyBlock: " << bodyBlock->GetName() << std::endl;
std::cout << "[DEBUG WHILE] exitBlock: " << exitBlock->GetName() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] condBlock: " << condBlock->GetName() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] bodyBlock: " << bodyBlock->GetName() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] exitBlock: " << exitBlock->GetName() << std::endl;
std::cout << "[DEBUG WHILE] Adding br to condBlock from current block" << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] Adding br to condBlock from current block" << std::endl;
builder_.CreateBr(condBlock);
loopStack_.push_back({condBlock, bodyBlock, exitBlock});
std::cout << "[DEBUG WHILE] loopStack size: " << loopStack_.size() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] loopStack size: " << loopStack_.size() << std::endl;
// 条件块
std::cout << "[DEBUG WHILE] Generating condition in block: " << condBlock->GetName() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] Generating condition in block: " << condBlock->GetName() << std::endl;
builder_.SetInsertPoint(condBlock);
auto* condValue = EvalCond(*ctx->cond());
builder_.CreateCondBr(condValue, bodyBlock, exitBlock);
std::cout << "[DEBUG WHILE] condBlock has terminator: " << condBlock->HasTerminator() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] condBlock has terminator: " << condBlock->HasTerminator() << std::endl;
// 循环体
std::cout << "[DEBUG WHILE] Generating body in block: " << bodyBlock->GetName() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] Generating body in block: " << bodyBlock->GetName() << std::endl;
builder_.SetInsertPoint(bodyBlock);
auto bodyResult = ctx->stmt(0)->accept(this);
bool bodyTerminated = (std::any_cast<BlockFlow>(bodyResult) == BlockFlow::Terminated);
std::cout << "[DEBUG WHILE] body terminated: " << bodyTerminated << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] body terminated: " << bodyTerminated << std::endl;
if (!bodyTerminated) {
std::cout << "[DEBUG WHILE] Adding br to condBlock from body" << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] Adding br to condBlock from body" << std::endl;
builder_.CreateBr(condBlock);
}
std::cout << "[DEBUG WHILE] bodyBlock has terminator: " << bodyBlock->HasTerminator() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] bodyBlock has terminator: " << bodyBlock->HasTerminator() << std::endl;
loopStack_.pop_back();
std::cout << "[DEBUG WHILE] loopStack size after pop: " << loopStack_.size() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] loopStack size after pop: " << loopStack_.size() << std::endl;
// 设置插入点为 exitBlock
std::cout << "[DEBUG WHILE] Setting insert point to exitBlock: " << exitBlock->GetName() << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] Setting insert point to exitBlock: " << exitBlock->GetName() << std::endl;
builder_.SetInsertPoint(exitBlock);
std::cout << "[DEBUG WHILE] exitBlock has terminator before return: "
if (IRGen_DEBUG) std::cout << "[DEBUG WHILE] exitBlock has terminator before return: "
<< exitBlock->HasTerminator() << std::endl;
return BlockFlow::Continue;
@ -269,15 +269,15 @@ IRGenImpl::BlockFlow IRGenImpl::HandleWhileStmt(SysYParser::StmtContext* ctx) {
// break语句待实现
IRGenImpl::BlockFlow IRGenImpl::HandleBreakStmt(SysYParser::StmtContext* ctx) {
std::cout << "[DEBUG IRGEN] HandleBreakStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] HandleBreakStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (loopStack_.empty()) {
throw std::runtime_error(FormatError("irgen", "break 语句不在循环中"));
}
std::cout << "[DEBUG BREAK] Current insert block before break: "
if (IRGen_DEBUG) std::cout << "[DEBUG BREAK] Current insert block before break: "
<< builder_.GetInsertBlock()->GetName() << std::endl;
std::cout << "[DEBUG BREAK] Breaking to exitBlock: "
if (IRGen_DEBUG) std::cout << "[DEBUG BREAK] Breaking to exitBlock: "
<< loopStack_.back().exitBlock->GetName() << std::endl;
// 跳转到循环退出块
@ -288,15 +288,15 @@ IRGenImpl::BlockFlow IRGenImpl::HandleBreakStmt(SysYParser::StmtContext* ctx) {
}
IRGenImpl::BlockFlow IRGenImpl::HandleContinueStmt(SysYParser::StmtContext* ctx) {
std::cout << "[DEBUG IRGEN] HandleContinueStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] HandleContinueStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (loopStack_.empty()) {
throw std::runtime_error(FormatError("irgen", "continue 语句不在循环中"));
}
std::cout << "[DEBUG CONTINUE] Current insert block before continue: "
if (IRGen_DEBUG) std::cout << "[DEBUG CONTINUE] Current insert block before continue: "
<< builder_.GetInsertBlock()->GetName() << std::endl;
std::cout << "[DEBUG CONTINUE] Continuing to condBlock: "
if (IRGen_DEBUG) std::cout << "[DEBUG CONTINUE] Continuing to condBlock: "
<< loopStack_.back().condBlock->GetName() << std::endl;
// 跳转到循环条件块
@ -310,7 +310,7 @@ IRGenImpl::BlockFlow IRGenImpl::HandleContinueStmt(SysYParser::StmtContext* ctx)
// 赋值语句
// 赋值语句
IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
std::cout << "[DEBUG IRGEN] HandleAssignStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (IRGen_DEBUG) std::cout << "[DEBUG IRGEN] HandleAssignStmt: " << (ctx ? ctx->getText() : "<null>") << std::endl;
if (!ctx || !ctx->lVal() || !ctx->exp()) {
throw std::runtime_error(FormatError("irgen", "非法赋值语句"));
@ -324,7 +324,7 @@ IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
auto* lval = ctx->lVal();
std::string varName = lval->Ident()->getText();
std::cerr << "[DEBUG] HandleAssignStmt: assigning to " << varName << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleAssignStmt: assigning to " << varName << std::endl;
// 1. 检查是否为常量(不能给常量赋值)
auto* const_decl = sema_.ResolveConstUse(lval);
@ -342,7 +342,7 @@ IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
auto it = storage_map_.find(var_decl);
if (it != storage_map_.end()) {
base_ptr = it->second;
std::cerr << "[DEBUG] HandleAssignStmt: found in storage_map_ for " << varName
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleAssignStmt: found in storage_map_ for " << varName
<< ", ptr = " << (void*)base_ptr << std::endl;
}
}
@ -352,7 +352,7 @@ IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
auto it2 = param_map_.find(varName);
if (it2 != param_map_.end()) {
base_ptr = it2->second;
std::cerr << "[DEBUG] HandleAssignStmt: found in param_map_ for " << varName
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleAssignStmt: found in param_map_ for " << varName
<< ", ptr = " << (void*)base_ptr << std::endl;
}
}
@ -362,7 +362,7 @@ IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
auto it3 = global_map_.find(varName);
if (it3 != global_map_.end()) {
base_ptr = it3->second;
std::cerr << "[DEBUG] HandleAssignStmt: found in global_map_ for " << varName
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleAssignStmt: found in global_map_ for " << varName
<< ", ptr = " << (void*)base_ptr << std::endl;
}
}
@ -372,7 +372,7 @@ IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
auto it4 = local_var_map_.find(varName);
if (it4 != local_var_map_.end()) {
base_ptr = it4->second;
std::cerr << "[DEBUG] HandleAssignStmt: found in local_var_map_ for " << varName
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleAssignStmt: found in local_var_map_ for " << varName
<< ", ptr = " << (void*)base_ptr << std::endl;
}
}
@ -401,21 +401,21 @@ IRGenImpl::BlockFlow IRGenImpl::HandleAssignStmt(SysYParser::StmtContext* ctx) {
builder_.CreateStore(rhs, elem_ptr);
} else {
// 普通标量赋值
std::cerr << "[DEBUG] HandleAssignStmt: scalar assignment to " << varName
if (IRGen_DEBUG) std::cerr << "[DEBUG] HandleAssignStmt: scalar assignment to " << varName
<< ", ptr = " << (void*)base_ptr
<< ", rhs = " << (void*)rhs << std::endl;
// 在 HandleAssignStmt 中,存储前添加类型调试
if (base_ptr && base_ptr->GetType()) {
std::cerr << "[DEBUG] Is int32: " << base_ptr->GetType()->IsInt32() << std::endl;
std::cerr << "[DEBUG] Is float: " << base_ptr->GetType()->IsFloat() << std::endl;
std::cerr << "[DEBUG] Is ptr int32: " << base_ptr->GetType()->IsPtrInt32() << std::endl;
std::cerr << "[DEBUG] Is ptr float: " << base_ptr->GetType()->IsPtrFloat() << std::endl;
std::cerr << "[DEBUG] Is array: " << base_ptr->GetType()->IsArray() << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] Is int32: " << base_ptr->GetType()->IsInt32() << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] Is float: " << base_ptr->GetType()->IsFloat() << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] Is ptr int32: " << base_ptr->GetType()->IsPtrInt32() << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] Is ptr float: " << base_ptr->GetType()->IsPtrFloat() << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] Is array: " << base_ptr->GetType()->IsArray() << std::endl;
}
if (rhs && rhs->GetType()) {
std::cerr << "[DEBUG] Value is int32: " << rhs->GetType()->IsInt32() << std::endl;
if (IRGen_DEBUG) std::cerr << "[DEBUG] Value is int32: " << rhs->GetType()->IsInt32() << std::endl;
}
builder_.CreateStore(rhs, base_ptr);
}

@ -69,7 +69,7 @@ public:
} else {
return_type = ir::Type::GetInt32Type();
}
std::cout << "[DEBUG] 进入函数: " << name
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 进入函数: " << name
<< " 返回类型: " << (return_type->IsInt32() ? "int" :
return_type->IsFloat() ? "float" : "void")
<< std::endl;
@ -85,7 +85,7 @@ public:
if (ctx->block()) { // 处理函数体
ctx->block()->accept(this);
}
std::cout << "[DEBUG] 函数 " << name
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 函数 " << name
<< " has_return: " << current_func_has_return_
<< " return_type_is_void: " << return_type->IsVoid()
<< std::endl;
@ -172,7 +172,7 @@ public:
std::vector<int> dims;
bool is_array = !ctx->constExp().empty();
// 调试输出
std::cout << "[DEBUG] CheckVarDef: " << name
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] CheckVarDef: " << name
<< " base_type: " << (base_type->IsInt32() ? "int" : base_type->IsFloat() ? "float" : "unknown")
<< " is_array: " << is_array
<< " dim_count: " << ctx->constExp().size() << std::endl;
@ -187,23 +187,23 @@ public:
throw std::runtime_error(FormatError("sema", "数组维度必须为正整数"));
}
dims.push_back(dim);
std::cout << "[DEBUG] dim[" << dims.size() - 1 << "] = " << dim << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] dim[" << dims.size() - 1 << "] = " << dim << std::endl;
}
// 创建数组类型
type = ir::Type::GetArrayType(base_type, dims);
std::cout << "[DEBUG] 创建数组类型完成" << std::endl;
std::cout << "[DEBUG] type->IsArray(): " << type->IsArray() << std::endl;
std::cout << "[DEBUG] type->GetKind(): " << (int)type->GetKind() << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 创建数组类型完成" << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] type->IsArray(): " << type->IsArray() << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] type->GetKind(): " << (int)type->GetKind() << std::endl;
// 验证数组类型
if (type->IsArray()) {
auto* arr_type = dynamic_cast<ir::ArrayType*>(type.get());
if (arr_type) {
std::cout << "[DEBUG] ArrayType dimensions: ";
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] ArrayType dimensions: ";
for (int d : arr_type->GetDimensions()) {
std::cout << d << " ";
if (Sema_DEBUG) std::cout << d << " ";
}
std::cout << std::endl;
std::cout << "[DEBUG] Element type: "
if (Sema_DEBUG) std::cout << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] Element type: "
<< (arr_type->GetElementType()->IsInt32() ? "int" :
arr_type->GetElementType()->IsFloat() ? "float" : "unknown")
<< std::endl;
@ -232,7 +232,7 @@ public:
sym.param_types.clear(); // 确保不混淆
}
table_.addSymbol(sym); // 添加到符号表
std::cout << "[DEBUG] 符号添加完成: " << name
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 符号添加完成: " << name
<< " type_kind: " << (int)sym.type->GetKind()
<< " is_array: " << sym.type->IsArray()
<< std::endl;
@ -265,7 +265,7 @@ public:
std::shared_ptr<ir::Type> type = base_type;
std::vector<int> dims;
bool is_array = !ctx->constExp().empty();
std::cout << "[DEBUG] CheckConstDef: " << name
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] CheckConstDef: " << name
<< " base_type: " << (base_type->IsInt32() ? "int" : base_type->IsFloat() ? "float" : "unknown")
<< " is_array: " << is_array
<< " dim_count: " << ctx->constExp().size() << std::endl;
@ -276,10 +276,10 @@ public:
throw std::runtime_error(FormatError("sema", "数组维度必须为正整数"));
}
dims.push_back(dim);
std::cout << "[DEBUG] dim[" << dims.size() - 1 << "] = " << dim << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] dim[" << dims.size() - 1 << "] = " << dim << std::endl;
}
type = ir::Type::GetArrayType(base_type, dims);
std::cout << "[DEBUG] 创建数组类型完成IsArray: " << type->IsArray() << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 创建数组类型完成IsArray: " << type->IsArray() << std::endl;
}
// ========== 绑定维度表达式 ==========
@ -294,14 +294,14 @@ public:
BindConstInitVal(ctx->constInitVal());
init_values = table_.EvaluateConstInitVal(ctx->constInitVal(), dims, base_type);
std::cout << "[DEBUG] 初始化值数量: " << init_values.size() << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 初始化值数量: " << init_values.size() << std::endl;
}
// 检查初始化值数量
size_t expected_count = 1;
if (is_array) {
expected_count = 1;
for (int d : dims) expected_count *= d;
std::cout << "[DEBUG] 期望元素数量: " << expected_count << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 期望元素数量: " << expected_count << std::endl;
}
if (init_values.size() > expected_count) {
throw std::runtime_error(FormatError("sema", "初始化值过多"));
@ -309,14 +309,14 @@ public:
Symbol sym;
sym.name = name;
sym.kind = SymbolKind::Constant;
std::cout << "CheckConstDef: before addSymbol, sym.kind = " << (int)sym.kind << std::endl;
if (Sema_DEBUG) std::cout << "CheckConstDef: before addSymbol, sym.kind = " << (int)sym.kind << std::endl;
sym.type = type;
sym.scope_level = table_.currentScopeLevel();
sym.is_initialized = true;
sym.var_def_ctx = nullptr;
sym.const_def_ctx = ctx;
sym.const_def_ctx = ctx;
std::cout << "保存常量定义上下文: " << name << ", ctx: " << ctx << std::endl;
if (Sema_DEBUG) std::cout << "保存常量定义上下文: " << name << ", ctx: " << ctx << std::endl;
// 存储常量值(仅对非数组有效)
if (!is_array && !init_values.empty()) {
if (base_type->IsInt32() && init_values[0].kind == SymbolTable::ConstValue::INT) {
@ -327,14 +327,14 @@ public:
sym.const_value.f32 = init_values[0].float_val;
}
} else if (is_array) {
std::cout << "[DEBUG] 数组常量,不存储单个常量值" << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 数组常量,不存储单个常量值" << std::endl;
}
table_.addSymbol(sym);
std::cout << "CheckConstDef: after addSymbol, sym.kind = " << (int)sym.kind << std::endl;
if (Sema_DEBUG) std::cout << "CheckConstDef: after addSymbol, sym.kind = " << (int)sym.kind << std::endl;
auto* stored = table_.lookup(name);
std::cout << "CheckConstDef: after addSymbol, stored const_def_ctx = " << stored->const_def_ctx << std::endl;
if (Sema_DEBUG) std::cout << "CheckConstDef: after addSymbol, stored const_def_ctx = " << stored->const_def_ctx << std::endl;
std::cout << "[DEBUG] 常量符号添加完成" << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 常量符号添加完成" << std::endl;
}
// ==================== 语句语义检查 ====================
@ -343,20 +343,20 @@ public:
std::any visitStmt(SysYParser::StmtContext* ctx) override {
if (!ctx) return {};
// 调试输出
std::cout << "[DEBUG] visitStmt: ";
if (ctx->Return()) std::cout << "Return ";
if (ctx->If()) std::cout << "If ";
if (ctx->While()) std::cout << "While ";
if (ctx->Break()) std::cout << "Break ";
if (ctx->Continue()) std::cout << "Continue ";
if (ctx->lVal() && ctx->Assign()) std::cout << "Assign ";
if (ctx->exp() && ctx->Semi()) std::cout << "ExpStmt ";
if (ctx->block()) std::cout << "Block ";
std::cout << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] visitStmt: ";
if (ctx->Return()) if (Sema_DEBUG) std::cout << "Return ";
if (ctx->If()) if (Sema_DEBUG) std::cout << "If ";
if (ctx->While()) if (Sema_DEBUG) std::cout << "While ";
if (ctx->Break()) if (Sema_DEBUG) std::cout << "Break ";
if (ctx->Continue()) if (Sema_DEBUG) std::cout << "Continue ";
if (ctx->lVal() && ctx->Assign()) if (Sema_DEBUG) std::cout << "Assign ";
if (ctx->exp() && ctx->Semi()) if (Sema_DEBUG) std::cout << "ExpStmt ";
if (ctx->block()) if (Sema_DEBUG) std::cout << "Block ";
if (Sema_DEBUG) std::cout << std::endl;
// 判断语句类型 - 注意Return() 返回的是 TerminalNode*
if (ctx->Return() != nullptr) {
// return 语句
std::cout << "[DEBUG] 检测到 return 语句" << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 检测到 return 语句" << std::endl;
return visitReturnStmtInternal(ctx);
} else if (ctx->lVal() != nullptr && ctx->Assign() != nullptr) {
// 赋值语句
@ -385,14 +385,14 @@ public:
// return 语句内部实现
std::any visitReturnStmtInternal(SysYParser::StmtContext* ctx) {
std::cout << "[DEBUG] visitReturnStmtInternal 被调用" << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] visitReturnStmtInternal 被调用" << std::endl;
std::shared_ptr<ir::Type> expected = current_func_return_type_;
if (!expected) {
throw std::runtime_error(FormatError("sema", "return 语句不在函数体内"));
}
if (ctx->exp() != nullptr) {
// 有返回值的 return
std::cout << "[DEBUG] 有返回值的 return" << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 有返回值的 return" << std::endl;
ExprInfo ret_val = CheckExp(ctx->exp());
if (expected->IsVoid()) {
throw std::runtime_error(FormatError("sema", "void 函数不能返回值"));
@ -405,23 +405,23 @@ public:
}
// 设置 has_return 标志
current_func_has_return_ = true;
std::cout << "[DEBUG] 设置 current_func_has_return_ = true" << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 设置 current_func_has_return_ = true" << std::endl;
} else {
// 无返回值的 return
std::cout << "[DEBUG] 无返回值的 return" << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 无返回值的 return" << std::endl;
if (!expected->IsVoid()) {
throw std::runtime_error(FormatError("sema", "非 void 函数必须返回值"));
}
// 设置 has_return 标志
current_func_has_return_ = true;
std::cout << "[DEBUG] 设置 current_func_has_return_ = true" << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 设置 current_func_has_return_ = true" << std::endl;
}
return {};
}
// 左值表达式(变量引用)
std::any visitLVal(SysYParser::LValContext* ctx) override {
std::cout << "[DEBUG] visitLVal: " << ctx->getText() << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] visitLVal: " << ctx->getText() << std::endl;
if (!ctx || !ctx->Ident()) {
throw std::runtime_error(FormatError("sema", "非法变量引用"));
}
@ -432,7 +432,7 @@ public:
}
// 检查数组访问
bool is_array_access = !ctx->exp().empty();
std::cout << "[DEBUG] name: " << name
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] name: " << name
<< ", is_array_access: " << is_array_access
<< ", subscript_count: " << ctx->exp().size() << std::endl;
ExprInfo result;
@ -440,7 +440,7 @@ public:
bool is_array_or_ptr = false;
if (sym->type) {
is_array_or_ptr = sym->type->IsArray() || sym->type->IsPtrInt32() || sym->type->IsPtrFloat();
std::cout << "[DEBUG] type_kind: " << (int)sym->type->GetKind()
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] type_kind: " << (int)sym->type->GetKind()
<< ", is_array: " << sym->type->IsArray()
<< ", is_ptr: " << (sym->type->IsPtrInt32() || sym->type->IsPtrFloat()) << std::endl;
}
@ -453,7 +453,7 @@ public:
if (auto* arr_type = dynamic_cast<ir::ArrayType*>(sym->type.get())) {
dim_count = arr_type->GetDimensions().size();
elem_type = arr_type->GetElementType();
std::cout << "[DEBUG] 数组维度: " << dim_count << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 数组维度: " << dim_count << std::endl;
}
} else if (sym->type->IsPtrInt32() || sym->type->IsPtrFloat()) {
dim_count = 1;
@ -462,11 +462,11 @@ public:
} else if (sym->type->IsPtrFloat()) {
elem_type = ir::Type::GetFloatType();
}
std::cout << "[DEBUG] 指针类型, dim_count: 1" << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 指针类型, dim_count: 1" << std::endl;
}
if (is_array_access) {
std::cout << "[DEBUG] 有下标访问,期望维度: " << dim_count
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 有下标访问,期望维度: " << dim_count
<< ", 实际下标数: " << ctx->exp().size() << std::endl;
if (ctx->exp().size() != dim_count) {
throw std::runtime_error(FormatError("sema", "数组下标个数不匹配"));
@ -481,9 +481,9 @@ public:
result.is_lvalue = true;
result.is_const = false;
} else {
std::cout << "[DEBUG] 无下标访问" << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 无下标访问" << std::endl;
if (sym->type->IsArray()) {
std::cout << "[DEBUG] 数组名作为地址,转换为指针" << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 数组名作为地址,转换为指针" << std::endl;
if (auto* arr_type = dynamic_cast<ir::ArrayType*>(sym->type.get())) {
if (arr_type->GetElementType()->IsInt32()) {
result.type = ir::Type::GetPtrInt32Type();
@ -605,7 +605,7 @@ public:
// 主表达式
std::any visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) override {
std::cout << "[DEBUG] visitPrimaryExp: " << ctx->getText() << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] visitPrimaryExp: " << ctx->getText() << std::endl;
ExprInfo result;
if (ctx->lVal()) { // 左值表达式
result = CheckLValue(ctx->lVal());
@ -637,14 +637,14 @@ public:
// 一元表达式
std::any visitUnaryExp(SysYParser::UnaryExpContext* ctx) override {
std::cout << "[DEBUG] visitUnaryExp: " << ctx->getText() << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] visitUnaryExp: " << ctx->getText() << std::endl;
ExprInfo result;
if (ctx->primaryExp()) {
ctx->primaryExp()->accept(this);
auto* info = sema_.GetExprType(ctx->primaryExp());
if (info) result = *info;
} else if (ctx->Ident() && ctx->L_PAREN()) { // 函数调用
std::cout << "[DEBUG] 函数调用: " << ctx->Ident()->getText() << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 函数调用: " << ctx->Ident()->getText() << std::endl;
result = CheckFuncCall(ctx);
} else if (ctx->unaryOp()) { // 一元运算
ctx->unaryExp()->accept(this);
@ -1025,7 +1025,7 @@ private:
if (!ctx || !ctx->addExp()) {
throw std::runtime_error(FormatError("sema", "无效表达式"));
}
std::cout << "[DEBUG] CheckExp: " << ctx->getText() << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] CheckExp: " << ctx->getText() << std::endl;
ctx->addExp()->accept(this);
auto* info = sema_.GetExprType(ctx->addExp());
if (!info) {
@ -1076,18 +1076,18 @@ private:
if (!sym) {
throw std::runtime_error(FormatError("sema", "未定义的变量: " + name));
}
std::cout << "CheckLValue: found sym->name = " << sym->name
if (Sema_DEBUG) std::cout << "CheckLValue: found sym->name = " << sym->name
<< ", sym->kind = " << (int)sym->kind << std::endl;
if (sym->kind == SymbolKind::Variable && sym->var_def_ctx) {
sema_.BindVarUse(ctx, sym->var_def_ctx);
std::cout << "绑定变量: " << name << " -> VarDefContext" << std::endl;
if (Sema_DEBUG) std::cout << "绑定变量: " << name << " -> VarDefContext" << std::endl;
}
else if (sym->kind == SymbolKind::Constant && sym->const_def_ctx) {
sema_.BindConstUse(ctx, sym->const_def_ctx);
std::cout << "绑定常量: " << name << " -> ConstDefContext" << std::endl;
if (Sema_DEBUG) std::cout << "绑定常量: " << name << " -> ConstDefContext" << std::endl;
}
std::cout << "CheckLValue 绑定变量: " << name
if (Sema_DEBUG) std::cout << "CheckLValue 绑定变量: " << name
<< ", sym->kind: " << (int)sym->kind
<< ", sym->var_def_ctx: " << sym->var_def_ctx
<< ", sym->const_def_ctx: " << sym->const_def_ctx << std::endl;
@ -1122,9 +1122,9 @@ private:
} else if (sym->type->IsPtrFloat()) {
elem_type = ir::Type::GetFloatType();
}
std::cout << "数组参数维度: " << dim_count << " 维, dims: ";
for (int d : dims) std::cout << d << " ";
std::cout << std::endl;
if (Sema_DEBUG) std::cout << "数组参数维度: " << dim_count << " 维, dims: ";
for (int d : dims) if (Sema_DEBUG) std::cout << d << " ";
if (Sema_DEBUG) std::cout << std::endl;
} else if (sym->type && (sym->type->IsPtrInt32() || sym->type->IsPtrFloat())) {
// 普通指针,只能有一个下标
dim_count = 1;
@ -1137,7 +1137,7 @@ private:
size_t subscript_count = ctx->exp().size();
std::cout << "dim_count: " << dim_count << ", subscript_count: " << subscript_count << std::endl;
if (Sema_DEBUG) std::cout << "dim_count: " << dim_count << ", subscript_count: " << subscript_count << std::endl;
if (dim_count > 0 || sym->is_array_param || sym->type->IsArray() ||
sym->type->IsPtrInt32() || sym->type->IsPtrFloat()) {
@ -1158,11 +1158,11 @@ private:
if (subscript_count == dim_count) {
// 完全索引,返回元素类型
std::cout << "完全索引,返回元素类型" << std::endl;
if (Sema_DEBUG) std::cout << "完全索引,返回元素类型" << std::endl;
return {elem_type, true, false};
} else {
// 部分索引,返回子数组的指针类型
std::cout << "部分索引,返回指针类型" << std::endl;
if (Sema_DEBUG) std::cout << "部分索引,返回指针类型" << std::endl;
// 计算剩余维度的指针类型
if (elem_type->IsInt32()) {
return {ir::Type::GetPtrInt32Type(), false, false};
@ -1176,7 +1176,7 @@ private:
// 没有下标访问
if (sym->type && sym->type->IsArray()) {
// 数组名作为地址
std::cout << "数组名作为地址" << std::endl;
if (Sema_DEBUG) std::cout << "数组名作为地址" << std::endl;
if (auto* arr_type = dynamic_cast<ir::ArrayType*>(sym->type.get())) {
if (arr_type->GetElementType()->IsInt32()) {
return {ir::Type::GetPtrInt32Type(), false, true};
@ -1187,7 +1187,7 @@ private:
return {ir::Type::GetPtrInt32Type(), false, true};
} else if (sym->is_array_param) {
// 数组参数名作为地址
std::cout << "数组参数名作为地址" << std::endl;
if (Sema_DEBUG) std::cout << "数组参数名作为地址" << std::endl;
if (sym->type->IsPtrInt32()) {
return {ir::Type::GetPtrInt32Type(), false, true};
} else {
@ -1211,14 +1211,14 @@ private:
throw std::runtime_error(FormatError("sema", "非法函数调用"));
}
std::string func_name = ctx->Ident()->getText();
std::cout << "[DEBUG] CheckFuncCall: " << func_name << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] CheckFuncCall: " << func_name << std::endl;
auto* func_sym = table_.lookup(func_name);
if (!func_sym || func_sym->kind != SymbolKind::Function) {
throw std::runtime_error(FormatError("sema", "未定义的函数: " + func_name));
}
std::vector<ExprInfo> args;
if (ctx->funcRParams()) {
std::cout << "[DEBUG] 处理函数调用参数:" << std::endl;
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 处理函数调用参数:" << std::endl;
for (auto* exp : ctx->funcRParams()->exp()) {
if (exp) {
args.push_back(CheckExp(exp));
@ -1229,7 +1229,7 @@ private:
throw std::runtime_error(FormatError("sema", "参数个数不匹配"));
}
for (size_t i = 0; i < std::min(args.size(), func_sym->param_types.size()); ++i) {
std::cout << "[DEBUG] 检查参数 " << i << ": 实参类型 " << (int)args[i].type->GetKind()
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 检查参数 " << i << ": 实参类型 " << (int)args[i].type->GetKind()
<< " 形参类型 " << (int)func_sym->param_types[i]->GetKind() << std::endl;
if (!IsTypeCompatible(args[i].type, func_sym->param_types[i])) {
throw std::runtime_error(FormatError("sema", "参数类型不匹配"));
@ -1430,10 +1430,10 @@ private:
sym.array_dims = dims;
table_.addSymbol(sym);
std::cout << "[DEBUG] 添加参数: " << name << " type_kind: " << (int)param_type->GetKind()
if (Sema_DEBUG) if (Sema_DEBUG) std::cout << "[DEBUG] 添加参数: " << name << " type_kind: " << (int)param_type->GetKind()
<< " is_array: " << is_array << " dims: ";
for (int d : dims) std::cout << d << " ";
std::cout << std::endl;
for (int d : dims) if (Sema_DEBUG) std::cout << d << " ";
if (Sema_DEBUG) std::cout << std::endl;
}
}

@ -5,7 +5,8 @@
#include <string>
#include <cmath>
#define DEBUG_SYMBOL_TABLE
//#define DEBUG_SYMBOL_TABLE
#define Sym_DEBUG 0
#ifdef DEBUG_SYMBOL_TABLE
#include <iostream>
@ -42,7 +43,7 @@ bool SymbolTable::addSymbol(const Symbol& sym) {
// 立即验证存储的符号
const auto& stored = current_scope[sym.name];
std::cout << "SymbolTable::addSymbol: stored " << 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;
@ -63,7 +64,7 @@ const Symbol* SymbolTable::lookup(const std::string& name) const {
const auto& scope = *it;
auto found = scope.find(name);
if (found != scope.end()) {
std::cout << "SymbolTable::lookup: found " << name
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

Loading…
Cancel
Save