Copilot commented on code in PR #2826:
URL: https://github.com/apache/groovy/pull/2826#discussion_r3837895503
##########
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java:
##########
@@ -4981,6 +4986,32 @@ && isOptimizedIntSwitch(selectorType,
expression.getCaseStatements())) {
}
}
+ /**
+ * Reports a repeated constant case label in a switch expression.
Sequential
+ * {@code isCase} semantics make the second arm dead code, and the
optimized
+ * {@code tableswitch}/{@code lookupswitch} forms cannot represent it at
all,
+ * so it is rejected here, uniformly for type-checked and
statically-compiled
+ * code (GROOVY-12289). Labels compared are the same ones the optimizers
key
+ * on: int-family, String and enum constants; anything else (GStrings,
calls,
+ * regex or collection labels) cannot be proven duplicated statically and
is
+ * left to sequential first-match-wins dispatch.
+ *
+ * @since 6.0.0
+ */
+ private void checkSwitchExpressionDuplicateLabels(final SwitchExpression
expression) {
+ ClassNode enumType =
unwrapEnumType(getType(expression.getExpression()));
+ Set<Object> seen = new HashSet<>();
+ for (CaseStatement caseStatement : expression.getCaseStatements()) {
+ Expression label = caseStatement.getExpression();
+ Object key = (enumType != null && enumType.isEnum()) ?
enumConstantName(label, enumType) : null;
+ if (key == null) key = intConstant(label);
+ if (key == null) key = stringConstant(label);
+ if (key != null && !seen.add(key)) {
Review Comment:
`enumConstantName` and `stringConstant` both produce `String` keys, so an
enum label like `E.X` (key "X") can collide with a string label `"X"` in the
same switch expression, incorrectly triggering a "Duplicate case label" error
even though the labels are different expressions and the presence of a non-enum
label already forces sequential `isCase` dispatch. Use a distinct key type for
enum constants (e.g., pair enum type + name) to avoid cross-type collisions
while still catching duplicates among enum constants.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]