You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2026/10/11 11:32:32 UTC

(groovy) branch GROOVY-12447 created (now c585b133af)

This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a change to branch GROOVY-12447
in repository https://gitbox.apache.org/repos/asf/groovy.git


      at c585b133af GROOVY-12447: STC: treat a complete native sealed type-case set as an exhaustive switch expression

This branch includes the following new commits:

     new c585b133af GROOVY-12447: STC: treat a complete native sealed type-case set as an exhaustive switch expression

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(groovy) 01/01: GROOVY-12447: STC: treat a complete native sealed type-case set as an exhaustive switch expression

Posted by su...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch GROOVY-12447
in repository https://gitbox.apache.org/repos/asf/groovy.git

commit c585b133afd71ed8a512a665f2a728e30240d159
Author: Daniel Sun <su...@apache.org>
AuthorDate: Sun Oct 11 18:34:45 2026 +0900

    GROOVY-12447: STC: treat a complete native sealed type-case set as an exhaustive switch expression
---
 .../transform/stc/StaticTypeCheckingVisitor.java   |  80 +++++-
 .../transform/stc/SwitchExpressionSTCTest.groovy   | 274 +++++++++++++++++++++
 2 files changed, 351 insertions(+), 3 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
index bc646de1f1..19fbca6bb7 100644
--- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
+++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
@@ -124,6 +124,7 @@ import org.codehaus.groovy.syntax.SyntaxException;
 import org.codehaus.groovy.syntax.Token;
 import org.codehaus.groovy.syntax.TokenUtil;
 import org.codehaus.groovy.transform.RecordTypeASTTransformation;
+import org.codehaus.groovy.transform.SealedASTTransformation;
 import org.codehaus.groovy.transform.StaticTypesTransformation;
 import org.codehaus.groovy.transform.trait.Traits;
 import org.objectweb.asm.Opcodes;
@@ -5229,9 +5230,10 @@ trying: for (ClassNode[] signature : signatures) {
      * forms cannot represent it at all, so it is rejected here, uniformly for
      * type-checked and statically-compiled code (GROOVY-12289, GROOVY-12406).
      * 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.
+     * String and enum constants, plus a {@code ClassExpression} naming a
+     * permitted subclass of a native sealed selector; 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
      */
@@ -5249,6 +5251,7 @@ trying: for (ClassNode[] signature : signatures) {
             }
             if (key == null) key = intConstant(label);
             if (key == null) key = stringConstant(label);
+            if (key == null) key = permittedSubclassLabelKey(selector, label);
             if (key != null && !seen.add(key)) {
                 addStaticTypeError("Duplicate case label: " + label.getText(), label);
             }
@@ -5301,9 +5304,80 @@ trying: for (ClassNode[] signature : signatures) {
         if (selectorType != null && selectorType.isEnum() && coversAllEnumConstants(expression, selectorType)) {
             return;
         }
+        if (coversAllPermittedSubclasses(expression, selectorType)) {
+            return;
+        }
         addError("the switch expression does not cover all possible input values", expression);
     }
 
+    /**
+     * True when {@code selectorType} is a closed native sealed hierarchy.
+     * Primary class nodes use {@link SealedASTTransformation#wouldBeNativeSealed}
+     * so the result does not depend on transform order. Class files use a
+     * non-empty permitted-subclass list; {@link ClassNode#isSealed()} is not
+     * consulted because emulated sealed types keep a runtime {@code @Sealed}.
+     */
+    private boolean nativeSealedClosed(final ClassNode selectorType) {
+        if (selectorType == null) {
+            return false;
+        }
+        ClassNode node = selectorType.redirect();
+        if (node.isPrimaryClassNode()) {
+            return SealedASTTransformation.wouldBeNativeSealed(node, getSourceUnit().getConfiguration().getTargetBytecode());
+        }
+        return !node.getPermittedSubclasses().isEmpty();
+    }
+
+    private Object permittedSubclassLabelKey(final Expression selector, final Expression label) {
+        if (!(label instanceof ClassExpression classExpression)) {
+            return null;
+        }
+        ClassNode selectorType = getType(selector);
+        if (!nativeSealedClosed(selectorType)) {
+            return null;
+        }
+        List<ClassNode> permitted = selectorType.getPermittedSubclasses();
+        if (permitted == null || permitted.isEmpty()) {
+            return null;
+        }
+        String labelName = classExpression.getType().redirect().getName();
+        for (ClassNode permittedType : permitted) {
+            if (permittedType.redirect().getName().equals(labelName)) {
+                // Namespaced like enum keys so a type case never collides
+                // with a string label of the same spelling.
+                return Map.entry(selectorType.redirect(), labelName);
+            }
+        }
+        return null;
+    }
+
+    private boolean coversAllPermittedSubclasses(final SwitchExpression expression, final ClassNode selectorType) {
+        if (!nativeSealedClosed(selectorType)) {
+            return false;
+        }
+        ClassNode sealedType = selectorType.redirect();
+        List<ClassNode> permitted = sealedType.getPermittedSubclasses();
+        if (permitted == null || permitted.isEmpty()) {
+            return false;
+        }
+        Set<ClassNode> remaining = new LinkedHashSet<>(permitted);
+        if (!sealedType.isInterface() && !sealedType.isAbstract()) {
+            remaining.add(sealedType);
+        }
+        for (CaseStatement caseStatement : expression.getCaseStatements()) {
+            Expression caseExpr = caseStatement.getExpression();
+            if (caseExpr instanceof ClassExpression classExpression) {
+                ClassNode caseType = classExpression.getType().redirect();
+                // A type case is a member of the sealed hierarchy. Unrelated
+                // labels (including a mis-resolved Object) stay ordinary isCase.
+                if (caseType.equals(sealedType) || implementsInterfaceOrIsSubclassOf(caseType, sealedType)) {
+                    remaining.removeIf(p -> implementsInterfaceOrIsSubclassOf(p.redirect(), caseType));
+                }
+            }
+        }
+        return remaining.isEmpty();
+    }
+
     private boolean coversAllEnumConstants(final SwitchExpression expression, final ClassNode enumType) {
         Set<String> remaining = new LinkedHashSet<>();
         for (FieldNode field : enumType.redirect().getFields()) {
diff --git a/src/test/groovy/groovy/transform/stc/SwitchExpressionSTCTest.groovy b/src/test/groovy/groovy/transform/stc/SwitchExpressionSTCTest.groovy
index 7d5ac12ce3..291adff781 100644
--- a/src/test/groovy/groovy/transform/stc/SwitchExpressionSTCTest.groovy
+++ b/src/test/groovy/groovy/transform/stc/SwitchExpressionSTCTest.groovy
@@ -18,8 +18,12 @@
  */
 package groovy.transform.stc
 
+import org.codehaus.groovy.control.CompilerConfiguration
+import org.codehaus.groovy.control.MultipleCompilationErrorsException
 import org.junit.jupiter.api.Test
 
+import static groovy.test.GroovyAssert.shouldFail
+
 /**
  * Static type checking for first-class switch expressions (GROOVY-12255 / JEP 361).
  */
@@ -150,4 +154,274 @@ class SwitchExpressionSTCTest extends StaticTypeCheckingTestCase {
             assert acc == 4
         '''
     }
+
+    @Test
+    void testNativeSealedInterfaceIsExhaustive() {
+        assertScript '''
+            sealed interface Shape permits Circle, Square {}
+            final class Circle implements Shape {}
+            final class Square implements Shape {}
+
+            String name(Shape s) {
+                return switch (s) {
+                    case Circle -> 'c'
+                    case Square -> 's'
+                }
+            }
+            assert name(new Circle()) == 'c'
+            assert name(new Square()) == 's'
+        '''
+    }
+
+    @Test
+    void testNativeSealedAbstractClassIsExhaustive() {
+        assertScript '''
+            abstract sealed class Shape permits Circle, Square {}
+            final class Circle extends Shape {}
+            final class Square extends Shape {}
+
+            @groovy.transform.CompileStatic
+            String name(Shape s) {
+                return switch (s) {
+                    case Circle -> 'c'
+                    case Square -> 's'
+                }
+            }
+            assert name(new Circle()) == 'c'
+        '''
+    }
+
+    @Test
+    void testNativeSealedMissingPermittedSubclassIsError() {
+        shouldFailWithMessages '''
+            sealed interface Shape permits Circle, Square {}
+            final class Circle implements Shape {}
+            final class Square implements Shape {}
+
+            String name(Shape s) {
+                return switch (s) {
+                    case Circle -> 'c'
+                }
+            }
+        ''', 'the switch expression does not cover all possible input values'
+    }
+
+    @Test
+    void testEmulatedSealedSwitchExpressionIsNotExhaustive() {
+        shouldFailWithMessages '''
+            import groovy.transform.SealedMode
+            import groovy.transform.SealedOptions
+
+            @SealedOptions(mode = SealedMode.EMULATE)
+            sealed interface Shape permits Circle, Square {}
+            final class Circle implements Shape {}
+            final class Square implements Shape {}
+
+            String name(Shape s) {
+                return switch (s) {
+                    case Circle -> 'c'
+                    case Square -> 's'
+                }
+            }
+        ''', 'the switch expression does not cover all possible input values'
+    }
+
+    @Test
+    void testDuplicatePermittedSubclassLabelIsError() {
+        shouldFailWithMessages '''
+            sealed interface Shape permits Circle, Square {}
+            final class Circle implements Shape {}
+            final class Square implements Shape {}
+
+            String name(Shape s) {
+                return switch (s) {
+                    case Circle -> 'c'
+                    case Circle -> 'again'
+                    case Square -> 's'
+                }
+            }
+        ''', '[Static type checking] - Duplicate case label: Circle'
+    }
+
+    @Test
+    void testObjectTypeCaseDoesNotMakeSealedSwitchExhaustive() {
+        shouldFailWithMessages '''
+            sealed interface Shape permits Circle, Square {}
+            final class Circle implements Shape {}
+            final class Square implements Shape {}
+
+            String name(Shape s) {
+                return switch (s) {
+                    case Object -> 'any'
+                }
+            }
+        ''', 'the switch expression does not cover all possible input values'
+    }
+
+    @Test
+    void testStringLabelDoesNotCollideWithPermittedSubclassType() {
+        assertScript '''
+            sealed interface Shape permits Circle, Square {}
+            final class Circle implements Shape {}
+            final class Square implements Shape {}
+
+            String name(Shape s) {
+                return switch (s) {
+                    case Circle -> 'c'
+                    case 'Circle' -> 'str'
+                    case Square -> 's'
+                }
+            }
+            assert name(new Circle()) == 'c'
+        '''
+    }
+
+    @Test
+    void testSealedSwitchStatementNeedNotBeExhaustive() {
+        assertScript '''
+            sealed interface Shape permits Circle, Square {}
+            final class Circle implements Shape {}
+            final class Square implements Shape {}
+
+            int n = 0
+            Shape s = new Circle()
+            switch (s) {
+                case Circle:
+                    n = 1
+            }
+            assert n == 1
+        '''
+    }
+
+    @Test
+    void testConcreteSealedClassRequiresCaseForTheTypeItself() {
+        shouldFailWithMessages '''
+            sealed class Shape permits Circle, Square {}
+            final class Circle extends Shape {}
+            final class Square extends Shape {}
+
+            String name(Shape s) {
+                return switch (s) {
+                    case Circle -> 'c'
+                    case Square -> 's'
+                }
+            }
+        ''', 'the switch expression does not cover all possible input values'
+    }
+
+    @Test
+    void testConcreteSealedClassCoveredByCaseOnTheType() {
+        assertScript '''
+            sealed class Shape permits Circle, Square {}
+            final class Circle extends Shape {}
+            final class Square extends Shape {}
+
+            String name(Shape s) {
+                return switch (s) {
+                    case Shape -> 'any'
+                }
+            }
+            assert name(new Shape()) == 'any'
+            assert name(new Circle()) == 'any'
+        '''
+    }
+
+    @Test
+    void testLeafCasesDoNotCoverPermittedParent() {
+        shouldFailWithMessages '''
+            sealed interface Shape permits Circle, Rect {}
+            final class Circle implements Shape {}
+            sealed class Rect implements Shape permits Square, Triangle {}
+            final class Square extends Rect {}
+            final class Triangle extends Rect {}
+
+            String name(Shape s) {
+                return switch (s) {
+                    case Circle -> 'c'
+                    case Square -> 's'
+                    case Triangle -> 't'
+                }
+            }
+        ''', 'the switch expression does not cover all possible input values'
+    }
+
+    @Test
+    void testPermittedParentCaseCoversItsSubtypes() {
+        assertScript '''
+            sealed interface Shape permits Circle, Rect {}
+            final class Circle implements Shape {}
+            sealed class Rect implements Shape permits Square, Triangle {}
+            final class Square extends Rect {}
+            final class Triangle extends Rect {}
+
+            String name(Shape s) {
+                return switch (s) {
+                    case Circle -> 'c'
+                    case Rect -> 'r'
+                }
+            }
+            assert name(new Square()) == 'r'
+        '''
+    }
+
+    @Test
+    void testNativeSealedFromClassFileIsExhaustive() {
+        File target = File.createTempDir()
+        try {
+            def loader = new GroovyClassLoader(this.class.classLoader, new CompilerConfiguration(targetDirectory: target))
+            loader.parseClass('''
+                package stc.sealed
+                sealed interface Shape permits Circle, Square {}
+                final class Circle implements Shape {}
+                final class Square implements Shape {}
+            ''')
+            def isolated = new GroovyClassLoader(loader, config)
+            def isolatedShell = new GroovyShell(isolated, config)
+            isolatedShell.evaluate('''
+                package stc.sealed
+                String name(Shape s) {
+                    return switch (s) {
+                        case Circle -> 'c'
+                        case Square -> 's'
+                    }
+                }
+                assert name(new Circle()) == 'c'
+            ''', 'SealedFromClassFile.groovy')
+        } finally {
+            target.deleteDir()
+        }
+    }
+
+    @Test
+    void testEmulatedSealedClassFileIsNotClosed() {
+        File target = File.createTempDir()
+        try {
+            def loader = new GroovyClassLoader(this.class.classLoader, new CompilerConfiguration(targetDirectory: target))
+            loader.parseClass('''
+                package stc.emulated
+                import groovy.transform.SealedMode
+                import groovy.transform.SealedOptions
+                @SealedOptions(mode = SealedMode.EMULATE)
+                sealed interface Shape permits Circle, Square {}
+                final class Circle implements Shape {}
+                final class Square implements Shape {}
+            ''')
+            def isolated = new GroovyClassLoader(loader, config)
+            def isolatedShell = new GroovyShell(isolated, config)
+            def err = shouldFail(MultipleCompilationErrorsException) {
+                isolatedShell.evaluate('''
+                    package stc.emulated
+                    String name(Shape s) {
+                        return switch (s) {
+                            case Circle -> 'c'
+                            case Square -> 's'
+                        }
+                    }
+                ''', 'EmulatedFromClassFile.groovy')
+            }
+            assert err.message.contains('the switch expression does not cover all possible input values')
+        } finally {
+            target.deleteDir()
+        }
+    }
 }