You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2026/09/14 11:21:21 UTC
(groovy) 02/20: GROOVY-12399: address review comments (complete enum, colon arms, void methods)
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch GROOVY_6_0_X
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 4be724dcfa615d137e421ed909ba8e8e9d7d9cb1
Author: Paul King <pa...@asert.com.au>
AuthorDate: Fri Sep 11 19:29:39 2026 +1000
GROOVY-12399: address review comments (complete enum, colon arms, void methods)
- A complete enum switch in implicit-return position under @CompileStatic
still threw for a null selector (the name-dispatch null target called
throwUnmatchedSelector directly) and for a constant added after
compilation (IncompatibleClassChangeError). It is no longer treated as
complete there, so both reach the default handling and yield null like
any other unmatched value.
- A switch nested in a colon arm of a switch expression was treated as the
arm value, so it kept the expression rules: an unmatched selector threw,
and an arrow block arm that did not yield was a parse error. Only an
arrow arm's sole statement is the arm value; colon arms yield
explicitly. This applies to the new position check and to
isSwitchUsedAsStatement.
- The last statement of a void method, constructor or compact constructor
is not an implicit-return position (ReturnAdder adds no return there),
so a switch there is a SwitchStatement like any other statement.
---
COMPATIBILITY.md | 9 +-
.../groovy/ast/tools/SwitchExpressionUtils.java | 5 +-
.../apache/groovy/parser/antlr4/AstBuilder.java | 47 ++++++---
.../classgen/asm/SwitchExpressionWriter.java | 12 ++-
.../asm/sc/StaticTypesSwitchExpressionWriter.java | 5 +-
src/spec/doc/core-semantics.adoc | 8 +-
.../codehaus/groovy/classgen/Groovy12399.groovy | 110 +++++++++++++++++++++
7 files changed, 173 insertions(+), 23 deletions(-)
diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md
index 65cb6caf54..fc7a95fcd1 100644
--- a/COMPATIBILITY.md
+++ b/COMPATIBILITY.md
@@ -361,10 +361,11 @@ only decides fall-through; the position decides whether a value is produced
(GROOVY-12399). A `switch` whose value is not used is a `SwitchStatement`,
whatever its arm shape, and does nothing when unmatched. In expression
position it is a `SwitchExpression` (every path must `yield` or `throw`).
-A switch in implicit-return position (the last statement of a method,
-closure or script body) keeps its value, but an unmatched selector yields
-`null` rather than throwing and no exhaustiveness is required, as in 4.x /
-5.x; write `return switch (...) {...}` for the strict expression rules.
+A switch in implicit-return position (the last statement of a closure, a
+script or a method that returns a value) keeps its value, but an unmatched
+selector yields `null` rather than throwing and no exhaustiveness is
+required, as in 4.x / 5.x; write `return switch (...) {...}` for the strict
+expression rules.
**Who is affected (runtime behaviour).** A dynamic switch expression whose
selector matches no arm now throws `IllegalStateException`. Previously the
diff --git a/src/main/java/org/apache/groovy/ast/tools/SwitchExpressionUtils.java b/src/main/java/org/apache/groovy/ast/tools/SwitchExpressionUtils.java
index 50f1842ca7..e9922929e6 100644
--- a/src/main/java/org/apache/groovy/ast/tools/SwitchExpressionUtils.java
+++ b/src/main/java/org/apache/groovy/ast/tools/SwitchExpressionUtils.java
@@ -43,8 +43,9 @@ public final class SwitchExpressionUtils {
/**
* Node metadata key on a {@code SwitchExpression} in implicit-return position
- * (the last statement of a method, closure or script body): the switch keeps
- * its value, but an unmatched selector yields {@code null} instead of throwing
+ * (the last statement of a closure, a script or a method that returns a
+ * value): the switch keeps its value, but an unmatched selector yields
+ * {@code null} instead of throwing
* and the type checker does not require exhaustiveness (GROOVY-12399).
*
* @since 6.0.0
diff --git a/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java b/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
index 525ef0da5b..a666805d92 100644
--- a/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
+++ b/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
@@ -1179,7 +1179,12 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
ParserRuleContext blockStatement = stmtAlt.getParent();
ParserRuleContext blockStatements = blockStatement != null ? blockStatement.getParent() : null;
ParserRuleContext group = blockStatements != null ? blockStatements.getParent() : null;
- return !(group instanceof SwitchBlockStatementExpressionGroupContext);
+ return !(group instanceof SwitchBlockStatementExpressionGroupContext g && isArrowGroup(g));
+ }
+
+ /** Whether a switch-expression group uses arrow labels, making its sole statement the arm value. */
+ private static boolean isArrowGroup(final SwitchBlockStatementExpressionGroupContext group) {
+ return group.switchExpressionLabel(0).ac.getType() == ARROW;
}
private boolean isEnclosingSwitchUsedAsStatement() {
@@ -2454,9 +2459,9 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
// colon-only), but as in Java (JEP 361) the arrow only decides fall-through;
// the position decides whether a value is produced. A switch whose value is
// not used, or whose arrow block arms do not yield, is a SwitchStatement.
- // In implicit-return position (the last statement of a method, closure or
- // script body) the value is used, but an unmatched selector yields null
- // rather than throwing, as it did in 4.x/5.x (GROOVY-12399).
+ // In implicit-return position (the last statement of a closure, a script or
+ // a method that returns a value) the value is used, but an unmatched selector
+ // yields null rather than throwing, as it did in 4.x/5.x (GROOVY-12399).
if (expr instanceof SwitchExpression se && ctx.getParent() instanceof ExpressionStmtAltContext statement) {
if (switchExpressionHasIncompleteArm(se) || !isSwitchValueUsed(statement)) {
return configureAST(switchExpressionAsStatement(se), ctx);
@@ -2473,24 +2478,25 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
* expression of an arrow arm of an enclosing switch expression, or it is
* in implicit-return position.
*/
- private static boolean isSwitchValueUsed(final StatementContext statement) {
+ private boolean isSwitchValueUsed(final StatementContext statement) {
ParserRuleContext blockStatements = statement.getParent() instanceof BlockStatementContext bs ? bs.getParent() : null;
- if (blockStatements != null && blockStatements.getParent() instanceof SwitchBlockStatementExpressionGroupContext) {
- return true;
+ if (blockStatements != null && blockStatements.getParent() instanceof SwitchBlockStatementExpressionGroupContext group) {
+ return isArrowGroup(group); // a colon arm's statements are discarded; its value comes from `yield`
}
return isImplicitReturnPosition(statement);
}
/**
* Whether {@code statement} is where the compiler would add an implicit
- * {@code return} (see {@code ReturnAdder}): the last statement of a method,
- * lambda, closure or script body, followed through nested blocks, the
+ * {@code return} (see {@code ReturnAdder}): the last statement of a lambda,
+ * closure or script body, or of a method that returns a value (not a
+ * {@code void} method or a constructor), followed through nested blocks, the
* branches of an {@code if}, the try and catch blocks of a {@code try}, a
* {@code synchronized} block and the arms of a colon-form switch statement
* (allowing for a trailing {@code break}). Loop bodies and {@code finally}
* blocks are not return positions.
*/
- private static boolean isImplicitReturnPosition(final ParserRuleContext statement) {
+ private boolean isImplicitReturnPosition(final ParserRuleContext statement) {
ParserRuleContext parent = statement.getParent();
if (parent instanceof LabeledStmtAltContext || parent instanceof ConditionalStmtAltContext
|| parent instanceof TryCatchStmtAltContext) {
@@ -2503,7 +2509,10 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
if (parent instanceof CatchClauseContext) {
return isImplicitReturnPosition(parent.getParent());
}
- if (parent instanceof MethodBodyContext || parent instanceof LambdaBodyContext || parent instanceof ClosureContext) {
+ if (parent instanceof MethodBodyContext) {
+ return returnsValue(parent.getParent());
+ }
+ if (parent instanceof LambdaBodyContext || parent instanceof ClosureContext) {
return true;
}
if (parent instanceof BlockStmtAltContext || parent instanceof SynchronizedStmtAltContext) {
@@ -2536,6 +2545,22 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
return false;
}
+ /**
+ * Whether the method or constructor declaring a body returns a value: not a
+ * {@code void} method, a constructor or a compact constructor, whose bodies
+ * get no implicit {@code return} (see {@code ReturnAdder}).
+ */
+ private boolean returnsValue(final ParserRuleContext declaration) {
+ if (!(declaration instanceof MethodDeclarationContext method)) {
+ return false; // compact constructor
+ }
+ if (asBoolean(method.returnType())) {
+ return method.returnType().VOID() == null;
+ }
+ ClassNode classNode = classNodeStack.peek();
+ return classNode == null || !this.visitMethodName(method.methodName()).equals(classNode.getNodeMetaData(CLASS_NAME));
+ }
+
/** Whether {@code blockStatement} is the last one of {@code blockStatements}, allowing for a trailing {@code break}. */
private static boolean isLastStatement(final BlockStatementsContext blockStatements, final ParserRuleContext blockStatement) {
List<? extends BlockStatementContext> list = blockStatements.blockStatement();
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/SwitchExpressionWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/SwitchExpressionWriter.java
index 4950ae17a2..194ecfc7de 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/SwitchExpressionWriter.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/SwitchExpressionWriter.java
@@ -226,13 +226,23 @@ public class SwitchExpressionWriter {
}
}
+ /**
+ * Whether an unmatched selector completes the expression with {@code null}
+ * rather than throwing: a switch in implicit-return position (GROOVY-12399).
+ *
+ * @since 6.0.0
+ */
+ protected static boolean unmatchedYieldsNull(final SwitchExpression expression) {
+ return Boolean.TRUE.equals(expression.getNodeMetaData(UNMATCHED_YIELDS_NULL));
+ }
+
/**
* Completes the expression for an unmatched selector: {@code null} (cast
* to the result type) for a switch in implicit-return position, otherwise
* an {@code IllegalStateException} (GROOVY-12399).
*/
private void writeUnmatchedSelector(final SwitchExpression expression, final int selectorIndex, final ClassNode selectorType) {
- if (Boolean.TRUE.equals(expression.getNodeMetaData(UNMATCHED_YIELDS_NULL))) {
+ if (unmatchedYieldsNull(expression)) {
CompileStack.SwitchExpressionContext context = controller.getCompileStack().requireSwitchExpressionContext();
OperandStack operandStack = controller.getOperandStack();
controller.getMethodVisitor().visitInsn(ACONST_NULL);
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesSwitchExpressionWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesSwitchExpressionWriter.java
index 95589344cd..2bc909cca5 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesSwitchExpressionWriter.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesSwitchExpressionWriter.java
@@ -265,7 +265,10 @@ public class StaticTypesSwitchExpressionWriter extends SwitchExpressionWriter {
CompileStack compileStack = controller.getCompileStack();
boolean hasDefault = expression.getDefaultStatement() != null && !expression.getDefaultStatement().isEmpty();
- boolean complete = !hasDefault && group.keys.size() == enumConstantCount(enumType);
+ // in implicit-return position an unmatched selector, null or a constant
+ // added after compilation, yields null like any other (GROOVY-12399)
+ boolean complete = !hasDefault && !unmatchedYieldsNull(expression)
+ && group.keys.size() == enumConstantCount(enumType);
// a null selector matches no constant label; with no default it must
// throw ISE, never the complete-enum ICCE
diff --git a/src/spec/doc/core-semantics.adoc b/src/spec/doc/core-semantics.adoc
index c9b8130fee..cd31974002 100644
--- a/src/spec/doc/core-semantics.adoc
+++ b/src/spec/doc/core-semantics.adoc
@@ -221,10 +221,10 @@ statement or an expression is decided by its position
(link:https://issues.apache.org/jira/browse/GROOVY-12399[GROOVY-12399]).
A `switch` whose value is not used is a statement, whatever its arm shape,
and simply does nothing when unmatched. A `switch` that is the last statement
-of a method, closure or script body is that body's implicit return value: it
-keeps its value, but an unmatched selector yields `null` rather than throwing
-and no exhaustiveness is required. Use `return switch (...) {...}` there for
-the strict expression rules.
+of a closure, a script or a method that returns a value is that body's implicit
+return value: it keeps its value, but an unmatched selector yields `null`
+rather than throwing and no exhaustiveness is required. Use
+`return switch (...) {...}` there for the strict expression rules.
[source,groovy]
----
diff --git a/src/test/groovy/org/codehaus/groovy/classgen/Groovy12399.groovy b/src/test/groovy/org/codehaus/groovy/classgen/Groovy12399.groovy
index 622178af3a..48a4797c41 100644
--- a/src/test/groovy/org/codehaus/groovy/classgen/Groovy12399.groovy
+++ b/src/test/groovy/org/codehaus/groovy/classgen/Groovy12399.groovy
@@ -19,6 +19,7 @@
package org.codehaus.groovy.classgen
import groovy.transform.CompileStatic
+import org.codehaus.groovy.control.CompilationUnit
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer
import org.junit.jupiter.api.Test
@@ -277,4 +278,113 @@ final class Groovy12399 {
assert f(42) == null
'''
}
+
+ @Test
+ void statementSwitchNestedInColonArmDoesNothingWhenUnmatched() {
+ for (arm in ["log << 'two'", "{ log << 'two' }"]) {
+ assertBoth """
+ def f(int x, int y) {
+ def log = []
+ def r = switch (x) {
+ case 1:
+ switch (y) { case 2 -> $arm }
+ yield 'one'
+ default:
+ yield 'other'
+ }
+ [r, log]
+ }
+ assert f(1, 2) == ['one', ['two']]
+ assert f(1, 3) == ['one', []]
+ """
+ }
+ }
+
+ @Test
+ void implicitReturnCompleteEnumYieldsNullForNullSelector() {
+ assertBoth '''
+ enum Flag { ON, OFF }
+ String m(Flag f) {
+ switch (f) {
+ case Flag.ON -> 'on'
+ case Flag.OFF -> 'off'
+ }
+ }
+ assert m(Flag.ON) == 'on'
+ assert m(null) == null
+ '''
+ }
+
+ @Test
+ void implicitReturnCompleteEnumYieldsNullForConstantAddedLater() {
+ File v1 = File.createTempDir()
+ File v2 = File.createTempDir()
+ try {
+ compileTo(v1, 'enum Flag { ON, OFF }', '''
+ @groovy.transform.CompileStatic
+ class User {
+ static String lenient(Flag f) {
+ switch (f) {
+ case Flag.ON -> 'on'
+ case Flag.OFF -> 'off'
+ }
+ }
+ static String strict(Flag f) {
+ return switch (f) {
+ case Flag.ON -> 'on'
+ case Flag.OFF -> 'off'
+ }
+ }
+ }
+ ''')
+ compileTo(v2, 'enum Flag { ON, OFF, MAYBE }')
+ def loader = new URLClassLoader([v2, v1]*.toURI()*.toURL() as URL[], getClass().classLoader)
+ def user = loader.loadClass('User')
+ def maybe = Enum.valueOf(loader.loadClass('Flag'), 'MAYBE')
+ assert user.lenient(maybe) == null
+ shouldFail(IncompatibleClassChangeError) { user.strict(maybe) }
+ } finally {
+ v1.deleteDir()
+ v2.deleteDir()
+ }
+ }
+
+ @Test
+ void voidMethodAndConstructorEndWithAStatement() {
+ assertScript '''
+ import groovy.transform.ASTTest
+ import org.codehaus.groovy.ast.expr.SwitchExpression
+ import org.codehaus.groovy.ast.stmt.ExpressionStatement
+ import org.codehaus.groovy.ast.stmt.SwitchStatement
+ import static org.codehaus.groovy.control.CompilePhase.SEMANTIC_ANALYSIS
+
+ class C {
+ @ASTTest(phase=SEMANTIC_ANALYSIS, value={
+ assert node.code.statements[-1] instanceof SwitchStatement
+ })
+ C(int i) { switch (i) { case 1 -> println 'one' } }
+
+ @ASTTest(phase=SEMANTIC_ANALYSIS, value={
+ assert node.code.statements[-1] instanceof SwitchStatement
+ })
+ void v(int i) { switch (i) { case 1 -> println 'one' } }
+
+ @ASTTest(phase=SEMANTIC_ANALYSIS, value={
+ def last = node.code.statements[-1]
+ assert last instanceof ExpressionStatement && last.expression instanceof SwitchExpression
+ })
+ def value(int i) { switch (i) { case 1 -> 'one' } }
+ }
+ def c = new C(2)
+ c.v(2)
+ assert c.value(1) == 'one'
+ assert c.value(2) == null
+ '''
+ }
+
+ private static void compileTo(final File dir, final String... sources) {
+ def unit = new CompilationUnit(new CompilerConfiguration(targetDirectory: dir))
+ sources.eachWithIndex { String source, int i -> unit.addSource("Source${i}.groovy", source) }
+ unit.compile()
+ }
}