Skip to content

Commit

Permalink
GROOVY-11297: Fail to identify duplicate constructor declaration (por…
Browse files Browse the repository at this point in the history
…t to 2_5_X)
  • Loading branch information
paulk-asert committed Jan 25, 2024
1 parent c8a12f3 commit 7c86745
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/main/java/org/codehaus/groovy/classgen/Verifier.java
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ public void visitClass(final ClassNode node) {
node.getObjectInitializerStatements().clear();
node.visitContents(this);
checkForDuplicateMethods(node);
checkForDuplicateConstructors(node);
addCovariantMethods(node);

checkFinalVariables(node);
Expand Down Expand Up @@ -307,6 +308,18 @@ private static void checkForDuplicateMethods(ClassNode cn) {
}
}

private static void checkForDuplicateConstructors(final ClassNode cn) {
Set<String> descriptors = new HashSet<>();
for (ConstructorNode cons : cn.getDeclaredConstructors()) {
String mySig = methodDescriptorWithoutReturnType(cons);
if (descriptors.contains(mySig)) {
throw new RuntimeParserException("The constructor " + cons.getText() +
" duplicates another constructor of the same signature", sourceOf(cons));
}
descriptors.add(mySig);
}
}

private static String scriptBodySignatureWithoutReturnType(ClassNode cn) {
for (MethodNode mn : cn.getMethods()) {
if (mn.isScriptBody()) return methodDescriptorWithoutReturnType(mn);
Expand Down
10 changes: 10 additions & 0 deletions src/test/gls/classes/methods/RepetitiveMethodTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,14 @@ class RepetitiveMethodTest extends CompilableTestSupport {
}
'''
}

void testRepetitiveConstructor() {
def message = shouldNotCompile('''
class A {
A(int x) {}
A(int y) {}
}
''')
assert message.contains('duplicates another constructor of the same signature')
}
}

0 comments on commit 7c86745

Please sign in to comment.