Skip to content

Commit

Permalink
GROOVY-11297: Fail to identify duplicate constructor declaration
Browse files Browse the repository at this point in the history
  • Loading branch information
paulk-asert committed Jan 25, 2024
1 parent 8f668bd commit f0f62d6
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 @@ -268,6 +268,7 @@ public void visitClass(final ClassNode node) {
node.getObjectInitializerStatements().clear();
node.visitContents(this);
checkForDuplicateMethods(node);
checkForDuplicateConstructors(node);
addCovariantMethods(node);
detectNonSealedClasses(node);
checkFinalVariables(node);
Expand Down Expand Up @@ -393,6 +394,18 @@ private static void checkForDuplicateMethods(final 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(final 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 f0f62d6

Please sign in to comment.