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

@@ -22,27 +22,25 @@ class IRGenImpl {
public:
IRGenImpl(ir::Module& module, const SemanticContext& sema);
void Gen(SysYParser::CompUnitContext& cu);
void Gen(SysYParser::CompUnitContext& cu);
private:
void GenFuncDef(SysYParser::FuncDefContext& func);
void GenBlock(SysYParser::BlockContext& block);
void GenBlock(SysYParser::BlockStmtContext& block);
bool GenBlockItem(SysYParser::BlockItemContext& item);
void GenDecl(SysYParser::DeclContext& decl);
bool GenStmt(SysYParser::StmtContext& stmt);
void GenVarDecl(SysYParser::VarDeclContext& decl);
void GenVarDef(SysYParser::VarDefContext& decl);
void GenReturnStmt(SysYParser::ReturnStmtContext& ret);
ir::Value* GenExpr(SysYParser::ExpContext& expr);
ir::Value* GenAddExpr(SysYParser::AddExpContext& add);
ir::Value* GenPrimary(SysYParser::PrimaryContext& primary);
ir::Module& module_;
const SemanticContext& sema_;
ir::Function* func_;
ir::IRBuilder builder_;
// 名称绑定由 Sema 负责IRGen 只维护“声明 -> 存储槽位”的代码生成状态。
std::unordered_map<SysYParser::VarDeclContext*, ir::Value*> storage_map_;
std::unordered_map<SysYParser::VarDefContext*, ir::Value*> storage_map_;
};
std::unique_ptr<ir::Module> GenerateIR(SysYParser::CompUnitContext& tree,

View File

@@ -7,20 +7,20 @@
class SemanticContext {
public:
void BindVarUse(SysYParser::PrimaryContext* use,
SysYParser::VarDeclContext* decl) {
void BindVarUse(SysYParser::VarContext* use,
SysYParser::VarDefContext* decl) {
var_uses_[use] = decl;
}
SysYParser::VarDeclContext* ResolveVarUse(
const SysYParser::PrimaryContext* use) const {
SysYParser::VarDefContext* ResolveVarUse(
const SysYParser::VarContext* use) const {
auto it = var_uses_.find(use);
return it == var_uses_.end() ? nullptr : it->second;
}
private:
std::unordered_map<const SysYParser::PrimaryContext*,
SysYParser::VarDeclContext*>
std::unordered_map<const SysYParser::VarContext*,
SysYParser::VarDefContext*>
var_uses_;
};

View File

@@ -8,10 +8,10 @@
class SymbolTable {
public:
void Add(const std::string& name, SysYParser::VarDeclContext* decl);
void Add(const std::string& name, SysYParser::VarDefContext* decl);
bool Contains(const std::string& name) const;
SysYParser::VarDeclContext* Lookup(const std::string& name) const;
SysYParser::VarDefContext* Lookup(const std::string& name) const;
private:
std::unordered_map<std::string, SysYParser::VarDeclContext*> table_;
std::unordered_map<std::string, SysYParser::VarDefContext*> table_;
};