可以处理生成加法的IR

This commit is contained in:
jing
2025-12-28 18:44:48 +08:00
parent 77bee889d7
commit e941cced9b
42 changed files with 919 additions and 158 deletions

View File

@@ -1,5 +1,52 @@
// 语义分析主流程
// - 符号解析与绑定、类型检查、控制流规则检查
// - 记录/插入必要的隐式转换(或在节点上标注)
// - 输出为“带类型 / 符号 / 常量信息”的 AST
// 极简语义分析:只检查变量是否先声明再使用。
#include "sem/Sema.h"
#include <stdexcept>
#include <string>
#include <unordered_set>
#include "ast/AstNodes.h"
#include "sem/SymbolTable.h"
namespace {
class SemaVisitor {
public:
explicit SemaVisitor(SymbolTable& table) : table_(table) {}
void CheckBlock(const ast::Block& block) {
for (const auto& decl : block.varDecls) {
table_.Add(decl->name);
if (decl->init) CheckExpr(*decl->init);
}
for (const auto& stmt : block.stmts) {
if (auto ret = dynamic_cast<ast::ReturnStmt*>(stmt.get())) {
CheckExpr(*ret->value);
}
}
}
void CheckExpr(const ast::Expr& expr) {
if (auto var = dynamic_cast<const ast::VarExpr*>(&expr)) {
if (!table_.Contains(var->name)) {
throw std::runtime_error("使用了未定义的变量: " + var->name);
}
} else if (auto bin = dynamic_cast<const ast::BinaryExpr*>(&expr)) {
CheckExpr(*bin->lhs);
CheckExpr(*bin->rhs);
}
}
private:
SymbolTable& table_;
};
} // namespace
std::shared_ptr<ast::CompUnit> RunSema(std::shared_ptr<ast::CompUnit> ast) {
if (!ast || !ast->func || !ast->func->body) return ast;
SymbolTable table;
SemaVisitor visitor(table);
visitor.CheckBlock(*ast->func->body);
return ast;
}