Check that a variable name of variable declaration does not shadow an enum definition.

This commit is contained in:
2023-03-15 23:33:12 +01:00
parent f77d6a002d
commit 30dfbbbbba
2 changed files with 111 additions and 40 deletions

View File

@@ -179,43 +179,54 @@ public class ContextAnalysis extends KlangBaseVisitor<Node> {
@Override
public Node visitVariable_declaration(KlangParser.Variable_declarationContext ctx) {
String name = ctx.IDENT().getText();
int line = ctx.start.getLine();
int col = ctx.start.getCharPositionInLine();
Type declaredType = Type.getByName(ctx.type_annotation().type().getText());
var variableName = ctx.IDENT().getText();
var declaredType = Type.getByName(ctx.type_annotation().type().getText());
var line = ctx.start.getLine();
var col = ctx.start.getCharPositionInLine();
if (!declaredType.isPrimitiveType() && this.structDefs.get(declaredType.getName()) == null) {
String error = "Type " + declaredType.getName() + " not defined.";
if (!declaredType.isPrimitiveType() && !structDefs.containsKey(declaredType.getName()) && !enumDefs.containsKey(declaredType.getName())) {
var error = "Type " + declaredType.getName() + " not defined.";
throw new RuntimeException(Helper.getErrorPrefix(line, col) + error);
}
if (this.vars.get(name) != null) {
String error = "Redeclaration of variable with name \"" + name + "\".";
if (structDefs.containsKey(variableName)) {
var error = "Variable name " + variableName + " shadows a struct of the same name.";
throw new RuntimeException(Helper.getErrorPrefix(line, col) + error);
}
if (enumDefs.containsKey(variableName)) {
var error = "Variable name " + variableName + " shadows an enum of the same name.";
throw new RuntimeException(Helper.getErrorPrefix(line, col) + error);
}
if (vars.get(variableName) != null) {
var error = "Redeclaration of variable with name \"" + variableName + "\".";
throw new RuntimeException(Helper.getErrorPrefix(line, col) + error);
}
// Create the appropriate instance
VariableDeclaration result;
VariableDeclaration variableDeclaration;
if (ctx.expression() != null) {
Node expression = this.visit(ctx.expression());
var expression = visit(ctx.expression());
try {
declaredType.combine(expression.type);
} catch (Exception e) {
throw new RuntimeException(Helper.getErrorPrefix(line, col) + e.getMessage());
}
result = new VariableDeclaration(name, (Expression) expression);
result.initialized = true;
variableDeclaration = new VariableDeclaration(variableName, (Expression) expression);
variableDeclaration.initialized = true;
} else {
result = new VariableDeclaration(name);
variableDeclaration = new VariableDeclaration(variableName);
}
// Add it to the global map of variable declarations
this.vars.put(name, result);
vars.put(variableName, variableDeclaration);
result.line = line;
result.col = col;
result.type = declaredType;
return result;
variableDeclaration.line = line;
variableDeclaration.col = col;
variableDeclaration.type = declaredType;
return variableDeclaration;
}
@Override