Make sure that a variable that references an enum has to be initialized.
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user