fix(frontend): 规范一下前端实现
This commit is contained in:
@@ -48,14 +48,27 @@ void RunSema(SysYParser::CompUnitContext& comp_unit) {
|
||||
if (!func || !func->block()) {
|
||||
throw std::runtime_error("[sema] 缺少 main 函数定义");
|
||||
}
|
||||
if (!func->Ident() || func->Ident()->getText() != "main") {
|
||||
throw std::runtime_error("[sema] 入口函数必须命名为 main");
|
||||
}
|
||||
|
||||
SymbolTable table;
|
||||
bool seen_return = false;
|
||||
|
||||
for (auto* stmt : func->block()->stmt()) {
|
||||
if (!stmt) {
|
||||
const auto& items = func->block()->blockItem();
|
||||
if (items.empty()) {
|
||||
throw std::runtime_error("[sema] main 函数不能为空,且必须以 return 结束");
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < items.size(); ++i) {
|
||||
auto* item = items[i];
|
||||
if (!item) {
|
||||
continue;
|
||||
}
|
||||
if (auto* decl = stmt->varDecl()) {
|
||||
if (seen_return) {
|
||||
throw std::runtime_error("[sema] return 必须是 main 函数中的最后一条语句");
|
||||
}
|
||||
if (auto* decl = item->decl() ? item->decl()->varDecl() : nullptr) {
|
||||
const std::string name = decl->Ident()->getText();
|
||||
if (table.Contains(name)) {
|
||||
throw std::runtime_error("[sema] 重复定义变量: " + name);
|
||||
@@ -66,10 +79,19 @@ void RunSema(SysYParser::CompUnitContext& comp_unit) {
|
||||
table.Add(name);
|
||||
continue;
|
||||
}
|
||||
if (auto* ret = stmt->returnStmt()) {
|
||||
if (auto* stmt = item->stmt(); stmt && stmt->returnStmt()) {
|
||||
auto* ret = stmt->returnStmt();
|
||||
CheckExpr(*ret->exp(), table);
|
||||
break;
|
||||
seen_return = true;
|
||||
if (i + 1 != items.size()) {
|
||||
throw std::runtime_error("[sema] return 必须是 main 函数中的最后一条语句");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
throw std::runtime_error("[sema] 暂不支持的语句类型");
|
||||
throw std::runtime_error("[sema] 暂不支持的 blockItem 类型");
|
||||
}
|
||||
|
||||
if (!seen_return) {
|
||||
throw std::runtime_error("[sema] main 函数必须包含 return 语句");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user