refactor: 优化全局变量声明的错误信息

-根据变量是否为常量,动态设置符号种类
-针对常量和变量分别定制重复声明的错误信息
This commit is contained in:
Luke 2025-08-26 01:17:47 +08:00
parent da7d7bbcaa
commit c4e9e541fb

View File

@ -57,13 +57,17 @@ public record FunctionChecker(Context ctx) {
// 先构建全局符号表 // 先构建全局符号表
SymbolTable globalScope = new SymbolTable(null); SymbolTable globalScope = new SymbolTable(null);
// 根据 isConst() 决定种类
for (DeclarationNode g : mod.globals()) { for (DeclarationNode g : mod.globals()) {
var t = ctx.parseType(g.getType()); var t = ctx.parseType(g.getType());
// 检查全局变量是否重复声明 SymbolKind k = g.isConst() ? SymbolKind.CONSTANT : SymbolKind.VARIABLE;
if (!globalScope.define(new Symbol(g.getName(), t, SymbolKind.VARIABLE))) {
// 错误信息按常量/变量区分
String dupType = g.isConst() ? "常量" : "变量";
if (!globalScope.define(new Symbol(g.getName(), t, k))) {
ctx.errors().add(new SemanticError( ctx.errors().add(new SemanticError(
g, g,
"全局变量重复声明: " + g.getName() dupType + "重复声明: " + g.getName()
)); ));
} }
} }