Make sure that a variable that references an enum has to be initialized.

This commit is contained in:
2023-03-16 00:01:31 +01:00
parent 2768b4429c
commit 55a5b8f54a
2 changed files with 21 additions and 1 deletions

View File

@@ -216,6 +216,11 @@ public class ContextAnalysis extends KlangBaseVisitor<Node> {
variableDeclaration = new VariableDeclaration(variableName, (Expression) expression);
variableDeclaration.initialized = true;
} else {
if (enumDefs.containsKey(declaredType.getName())) {
var error = "Variable " + variableName + " references an enum but is not initialized.";
throw new RuntimeException(Helper.getErrorPrefix(line, col) + error);
}
variableDeclaration = new VariableDeclaration(variableName);
}

View File

@@ -21,7 +21,7 @@ public class VariableDeclarationTest {
@Test
void shouldNotThrowIfDeclaredTypeIsAnEnum() {
// given
var tree = Helper.prepareParser("enum bar { A, B } function foo(): int { let a: bar; return 1; } foo();");
var tree = Helper.prepareParser("enum bar { A, B } function foo(): int { let a: bar = bar.A; return 1; } foo();");
var ctxAnal = new ContextAnalysis(
Helper.getFuncs(tree),
Helper.getStructs(tree),
@@ -91,4 +91,19 @@ public class VariableDeclarationTest {
var e = assertThrows(RuntimeException.class, () -> ctxAnal.visit(tree));
assertEquals("Error in line 1:34 Redeclaration of variable with name \"x\".", e.getMessage());
}
@Test
void shouldThrowExceptionIfVariableReferencesEnumButIsNotInitialized() {
// given
var tree = Helper.prepareParser("enum bar { A, B } function foo(): int { let x: bar; return 1; } foo();");
var ctxAnal = new ContextAnalysis(
Helper.getFuncs(tree),
Helper.getStructs(tree),
Helper.getEnums(tree)
);
// when / then
var e = assertThrows(RuntimeException.class, () -> ctxAnal.visit(tree));
assertEquals("Error in line 1:40 Variable x references an enum but is not initialized.", e.getMessage());
}
}