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:23 UTC

(groovy) 04/20: GROOVY-12399: a switch nested in an arrow arm follows its own switch

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 812dd4a636bb50afdafa50b57b4caf0faf932a7a
Author: Paul King <pa...@asert.com.au>
AuthorDate: Sat Sep 12 10:23:37 2026 +1000

    GROOVY-12399: a switch nested in an arrow arm follows its own switch
    
    A switch written as the sole expression of an arrow arm was always
    treated as the arm value, so it kept the strict expression rules even
    when the switch owning that arm was itself a statement. An unmatched
    selector then threw where Groovy 5.1.2 did nothing:
    
        def f(int i, int j) {
            switch (i) {
                case 1 -> switch (j) { case 9 -> 'nine' }
                default -> 'other'
            }
            'done'
        }
        f(1, 5)   // IllegalStateException, expected 'done'
    
    The arms were visited before the position of the enclosing switch was
    known, so isSwitchValueUsed could only see that its group used arrows.
    It now asks the owning switch the same question, and leniency
    propagates the same way: an arm value of a switch in implicit-return
    position yields null when unmatched rather than throwing, as the switch
    containing it does. The recursion ends at a switch that is a real
    expression, whose arm values stay strict.
    
    isSwitchUsedAsStatement, which decides whether arrow arms may omit
    yield, is expressed in terms of the same predicates, so a nested arm
    switch that is a statement no longer demands a yield from the arms of
    the switch above it. It also no longer mistakes foo(switch (x) {...})
    for a whole statement, since the value there is used whatever the
    enclosing statement does with it.
---
 .../apache/groovy/parser/antlr4/AstBuilder.java    | 87 ++++++++++++++++------
 .../codehaus/groovy/classgen/Groovy12399.groovy    | 62 +++++++++++++++
 2 files changed, 126 insertions(+), 23 deletions(-)

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 a666805d92..d8e0e70922 100644
--- a/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
+++ b/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
@@ -1162,24 +1162,15 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
     }
 
     /**
-     * True when this {@code switch} is a statement (value discarded), not the
-     * value of an enclosing switch-expression arm. Nested
-     * {@code case L -> switch (...)} is the latter: the inner switch is an
-     * expression even though the parser sees it as an expression-statement.
+     * True when the arms of this {@code switch} need not yield: it makes up a
+     * whole statement whose value is either discarded or an implicit return,
+     * so an incomplete arm rewrites it to a {@code SwitchStatement}. Nested
+     * {@code case L -> switch (...)} follows its own switch: the inner one is
+     * an expression only where the outer produces a value.
      */
     private boolean isSwitchUsedAsStatement(final SwitchExpressionContext ctx) {
-        ParserRuleContext p = ctx;
-        while (p != null && !(p instanceof CommandExprAltContext)) {
-            p = p.getParent();
-        }
-        if (!(p instanceof CommandExprAltContext command)
-                || !(command.getParent() instanceof ExpressionStmtAltContext stmtAlt)) {
-            return false;
-        }
-        ParserRuleContext blockStatement = stmtAlt.getParent();
-        ParserRuleContext blockStatements = blockStatement != null ? blockStatement.getParent() : null;
-        ParserRuleContext group = blockStatements != null ? blockStatements.getParent() : null;
-        return !(group instanceof SwitchBlockStatementExpressionGroupContext g && isArrowGroup(g));
+        StatementContext statement = switchAsStatement(ctx);
+        return statement != null && (!isSwitchValueUsed(statement) || isLenientPosition(statement));
     }
 
     /** Whether a switch-expression group uses arrow labels, making its sole statement the arm value. */
@@ -2466,7 +2457,7 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
             if (switchExpressionHasIncompleteArm(se) || !isSwitchValueUsed(statement)) {
                 return configureAST(switchExpressionAsStatement(se), ctx);
             }
-            if (isImplicitReturnPosition(statement)) {
+            if (isLenientPosition(statement)) {
                 se.putNodeMetaData(UNMATCHED_YIELDS_NULL, Boolean.TRUE);
             }
         }
@@ -2474,16 +2465,66 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
     }
 
     /**
-     * Whether the value of a switch expression statement is used: it is the
-     * expression of an arrow arm of an enclosing switch expression, or it is
-     * in implicit-return position.
+     * Whether the value of a switch expression statement is used: it is in
+     * implicit-return position, or it is the expression of an arrow arm whose
+     * own switch produces a value. An arm of a switch that is itself a
+     * statement produces nothing, so a switch nested there is a statement too.
      */
     private boolean isSwitchValueUsed(final StatementContext statement) {
+        SwitchExpressionContext arm = enclosingArrowArmSwitch(statement);
+        if (arm != null) {
+            StatementContext owner = switchAsStatement(arm);
+            return owner == null || isSwitchValueUsed(owner);
+        }
+        return !isColonArm(statement) && isImplicitReturnPosition(statement);
+    }
+
+    /**
+     * Whether an unmatched selector completes the switch with {@code null}
+     * instead of throwing: implicit-return position, or an arrow arm of a
+     * switch that is itself lenient (GROOVY-12399).
+     */
+    private boolean isLenientPosition(final StatementContext statement) {
+        SwitchExpressionContext arm = enclosingArrowArmSwitch(statement);
+        if (arm != null) {
+            StatementContext owner = switchAsStatement(arm);
+            return owner != null && isLenientPosition(owner);
+        }
+        return !isColonArm(statement) && isImplicitReturnPosition(statement);
+    }
+
+    /** The switch expression whose arrow arm consists of {@code statement}, else null. */
+    private static SwitchExpressionContext enclosingArrowArmSwitch(final StatementContext statement) {
         ParserRuleContext blockStatements = statement.getParent() instanceof BlockStatementContext bs ? bs.getParent() : null;
-        if (blockStatements != null && blockStatements.getParent() instanceof SwitchBlockStatementExpressionGroupContext group) {
-            return isArrowGroup(group); // a colon arm's statements are discarded; its value comes from `yield`
+        if (blockStatements == null || !(blockStatements.getParent() instanceof SwitchBlockStatementExpressionGroupContext group)
+                || !isArrowGroup(group)) {
+            return null;
+        }
+        for (ParserRuleContext p = group.getParent(); p != null; p = p.getParent()) {
+            if (p instanceof SwitchExpressionContext se) return se;
+        }
+        return null;
+    }
+
+    /** Whether {@code statement} is in a colon arm, whose statements are discarded; its value comes from {@code yield}. */
+    private static boolean isColonArm(final StatementContext statement) {
+        ParserRuleContext blockStatements = statement.getParent() instanceof BlockStatementContext bs ? bs.getParent() : null;
+        return blockStatements != null && blockStatements.getParent() instanceof SwitchBlockStatementExpressionGroupContext group
+                && !isArrowGroup(group);
+    }
+
+    /**
+     * The statement that {@code ctx} alone makes up, or null when the switch is
+     * part of a larger expression such as {@code foo(switch (x) {...})}, whose
+     * value is used whatever the enclosing statement does with it.
+     */
+    private static StatementContext switchAsStatement(final SwitchExpressionContext ctx) {
+        ParserRuleContext p = ctx.getParent();
+        while (p != null && !(p instanceof StatementContext)) {
+            p = p.getParent();
         }
-        return isImplicitReturnPosition(statement);
+        return p instanceof ExpressionStmtAltContext statement
+                && statement.getStart() == ctx.getStart() && statement.getStop() == ctx.getStop() ? statement : null;
     }
 
     /**
diff --git a/src/test/groovy/org/codehaus/groovy/classgen/Groovy12399.groovy b/src/test/groovy/org/codehaus/groovy/classgen/Groovy12399.groovy
index 48a4797c41..b5086917d5 100644
--- a/src/test/groovy/org/codehaus/groovy/classgen/Groovy12399.groovy
+++ b/src/test/groovy/org/codehaus/groovy/classgen/Groovy12399.groovy
@@ -300,6 +300,68 @@ final class Groovy12399 {
         }
     }
 
+    @Test
+    void statementSwitchNestedInArrowArmOfStatementSwitch() {
+        assertBoth """
+            def f(int i, int j) {
+                switch (i) {
+                    case 1 -> switch (j) { case 9 -> 'nine' }
+                    default -> 'other'
+                }
+                'done'
+            }
+            assert f(1, 9) == 'done'
+            assert f(1, 5) == 'done'
+            assert f(2, 5) == 'done'
+        """
+    }
+
+    @Test
+    void statementSwitchNestedThreeDeepInArrowArms() {
+        assertBoth """
+            def f(int i, int j, int k) {
+                switch (i) {
+                    case 1 -> switch (j) { case 1 -> switch (k) { case 9 -> 'nine' } }
+                }
+                'done'
+            }
+            assert f(1, 1, 9) == 'done'
+            assert f(1, 1, 5) == 'done'
+        """
+    }
+
+    @Test
+    void implicitReturnSwitchNestedInArrowArmYieldsNullWhenUnmatched() {
+        assertBoth """
+            def f(int i, int j) {
+                switch (i) {
+                    case 1 -> switch (j) { case 9 -> 'nine' }
+                    default -> 'other'
+                }
+            }
+            assert f(1, 9) == 'nine'
+            assert f(1, 5) == null
+            assert f(2, 5) == 'other'
+        """
+    }
+
+    @Test
+    void arrowArmOfExpressionPositionSwitchStaysStrict() {
+        // the outer switch produces a value, so its arm value does too
+        for (outer in ['return switch (i)', 'def unused = switch (i)']) {
+            def err = shouldFail IllegalStateException, """
+                def f(int i, int j) {
+                    $outer {
+                        case 1 -> switch (j) { case 9 -> 'nine' }
+                        default -> 'other'
+                    }
+                }
+                f(1, 5)
+            """
+            assert err.message.contains('does not cover the value')
+        }
+    }
+
     @Test
     void implicitReturnCompleteEnumYieldsNullForNullSelector() {
         assertBoth '''