Check that a struct field name of a struct declaration does not shadow an enum or a struct definition.

This commit is contained in:
2023-03-15 23:48:57 +01:00
parent 30dfbbbbba
commit 2768b4429c
2 changed files with 42 additions and 0 deletions

View File

@@ -799,6 +799,16 @@ public class ContextAnalysis extends KlangBaseVisitor<Node> {
throw new RuntimeException(Helper.getErrorPrefix(line, col) + error); throw new RuntimeException(Helper.getErrorPrefix(line, col) + error);
} }
if (structDefs.containsKey(structFieldName)) {
var error = "Struct field name " + structFieldName + " shadows a struct of the same name.";
throw new RuntimeException(Helper.getErrorPrefix(line, col) + error);
}
if (enumDefs.containsKey(structFieldName)) {
var error = "Struct field name " + structFieldName + " shadows an enum of the same name.";
throw new RuntimeException(Helper.getErrorPrefix(line, col) + error);
}
var structField = new StructField(structFieldName); var structField = new StructField(structFieldName);
structField.type = structFieldType; structField.type = structFieldType;
structField.line = line; structField.line = line;

View File

@@ -27,6 +27,38 @@ public class StructDefinitionTest {
assertDoesNotThrow(() -> ctxAnal.visit(tree)); assertDoesNotThrow(() -> ctxAnal.visit(tree));
} }
@Test
void shouldNotThrowIfStructFieldTypeIsReferringToStruct() {
// given
var tree = Helper.prepareParser("struct a { hello: int; } struct b { world: a; } function foo(): int { return 1; } foo();");
var ctxAnal = new ContextAnalysis(Helper.getFuncs(tree), Helper.getStructs(tree), Helper.getEnums(tree));
// when / then
assertDoesNotThrow(() -> ctxAnal.visit(tree));
}
@Test
void shouldThrowExceptionIfStructFieldNameShadowsAStruct() {
// given
var tree = Helper.prepareParser("struct bar { a: int; } struct baz { bar: int; } function foo(): int { 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:36 Struct field name bar shadows a struct of the same name.", e.getMessage());
}
@Test
void shouldThrowExceptionIfStructFieldNameShadowsAnEnum() {
// given
var tree = Helper.prepareParser("enum bar { A, B } struct baz { bar: int; } function foo(): int { 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:31 Struct field name bar shadows an enum of the same name.", e.getMessage());
}
@Test @Test
void shouldThrowExceptionIfStructFieldTypeIsNotDefined() { void shouldThrowExceptionIfStructFieldTypeIsNotDefined() {
// given // given