refactor(irgen): 完善irgen代码和文档,提升扩展兼容性

This commit is contained in:
jing
2026-03-17 19:03:49 +08:00
parent a091d9108a
commit f19d23c656
8 changed files with 115 additions and 72 deletions

View File

@@ -6,7 +6,18 @@
#include "ir/IR.h"
#include "utils/Log.h"
void IRGenImpl::GenBlock(SysYParser::BlockContext& block) {
namespace {
std::string GetLValueName(SysYParser::LValueContext& lvalue) {
if (!lvalue.ID()) {
throw std::runtime_error(FormatError("irgen", "非法左值"));
}
return lvalue.ID()->getText();
}
} // namespace
void IRGenImpl::GenBlock(SysYParser::BlockStmtContext& block) {
for (auto* item : block.blockItem()) {
if (item) {
if (GenBlockItem(*item)) {
@@ -29,14 +40,21 @@ bool IRGenImpl::GenBlockItem(SysYParser::BlockItemContext& item) {
}
void IRGenImpl::GenDecl(SysYParser::DeclContext& decl) {
if (decl.varDecl()) {
GenVarDecl(*decl.varDecl());
return;
if (!decl.btype() || !decl.btype()->INT()) {
throw std::runtime_error(FormatError("irgen", "当前仅支持局部 int 变量声明"));
}
throw std::runtime_error(FormatError("irgen", "暂不支持的声明类型"));
auto* var_def = decl.varDef();
if (!var_def) {
throw std::runtime_error(FormatError("irgen", "非法变量声明"));
}
GenVarDef(*var_def);
}
void IRGenImpl::GenVarDecl(SysYParser::VarDeclContext& decl) {
void IRGenImpl::GenVarDef(SysYParser::VarDefContext& decl) {
if (!decl.lValue()) {
throw std::runtime_error(FormatError("irgen", "变量声明缺少名称"));
}
GetLValueName(*decl.lValue());
if (storage_map_.find(&decl) != storage_map_.end()) {
throw std::runtime_error(FormatError("irgen", "声明重复生成存储槽位"));
}
@@ -44,8 +62,11 @@ void IRGenImpl::GenVarDecl(SysYParser::VarDeclContext& decl) {
storage_map_[&decl] = slot;
ir::Value* init = nullptr;
if (decl.exp()) {
init = GenExpr(*decl.exp());
if (auto* init_value = decl.initValue()) {
if (!init_value->exp()) {
throw std::runtime_error(FormatError("irgen", "当前不支持聚合初始化"));
}
init = GenExpr(*init_value->exp());
} else {
init = builder_.CreateConstInt(0);
}