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/08/10 15:46:53 UTC

(groovy) branch GROOVY-12242 updated: GROOVY-12242: support type patterns on native !instanceof

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

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


The following commit(s) were added to refs/heads/GROOVY-12242 by this push:
     new 9aa4dedfb0 GROOVY-12242: support type patterns on native !instanceof
9aa4dedfb0 is described below

commit 9aa4dedfb00019bd0593d00389b07144058a2624
Author: Daniel Sun <su...@apache.org>
AuthorDate: Tue Aug 11 00:44:17 2026 +0900

    GROOVY-12242: support type patterns on native !instanceof
    
    Parse e !instanceof T t via matchingType (keeping parenthesised (T) form),
    isolate pattern declare for COMPARE_NOT_INSTANCEOF and short-circuit &&,
    and cover runtime, AST scope, flow analysis, and parser cases.
---
 COMPATIBILITY.md                                   |  7 +-
 src/antlr/GroovyParser.g4                          | 11 ++-
 .../apache/groovy/parser/antlr4/AstBuilder.java    | 28 ++++---
 .../groovy/classgen/VariableScopeVisitor.java      | 28 +++++--
 .../classgen/asm/BinaryExpressionHelper.java       | 13 +++
 src/spec/doc/core-semantics.adoc                   | 21 +++--
 .../groovy/InstanceofFlowBindingsTest.groovy       | 24 ++++++
 src/test/groovy/groovy/InstanceofScopeTest.groovy  | 97 ++++++++++++++++++++++
 src/test/groovy/groovy/InstanceofTest.groovy       | 89 ++++++++++++++++++++
 .../antlr4/IntersectionCastParserTest.groovy       |  8 ++
 10 files changed, 299 insertions(+), 27 deletions(-)

diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md
index 584cb703ba..8f026ab81b 100644
--- a/COMPATIBILITY.md
+++ b/COMPATIBILITY.md
@@ -209,9 +209,10 @@ indy remains acceptable for those use cases.
 ### Groovy 6 — `instanceof` pattern variable flow scoping (GROOVY-12242)
 
 Groovy 6 aligns JEP 394 / JLS §6.3-style *pattern variable* scoping for
-`e instanceof T t` (and `!instanceof`) with Java for the common shapes:
-`if`/`else` (including abrupt-completion survivors), short-circuit
-`&&` / `||`, ternary/Elvis arms, and true-path bindings in `while` bodies.
+`e instanceof T t` and `e !instanceof T t` (equivalent to
+`!(e instanceof T t)`) with Java for the common shapes: `if`/`else`
+(including abrupt-completion survivors), short-circuit `&&` / `||`,
+ternary/Elvis arms, and true-path bindings in `while` bodies.
 
 **Who is affected (silent behaviour change in dynamic Groovy).** Code that
 previously treated a pattern variable as a local outside its JLS live range
diff --git a/src/antlr/GroovyParser.g4 b/src/antlr/GroovyParser.g4
index 7384daca9e..41b3c078bc 100644
--- a/src/antlr/GroovyParser.g4
+++ b/src/antlr/GroovyParser.g4
@@ -352,10 +352,16 @@ referenceType
     :   qualifiedClassName typeArguments?
     ;
 
-matchingType // see: instanceof
+matchingType // see: instanceof / !instanceof type patterns (JEP 394)
     :   standardType identifier?
     ;
 
+// RHS of !instanceof: Type / Type name (pattern), or parenthesised (T) / rejected (A & B)
+notInstanceofType
+    :   matchingType
+    |   castParExpression
+    ;
+
 standardType // see: returnType
 options { baseContext = type; }
     :   annotationsOpt
@@ -846,7 +852,8 @@ expression
 
     // boolean relational expressions (level 7)
     |   left=expression nls op=INSTANCEOF nls matchingType                                  #relationalExprAlt
-    |   left=expression nls op=(AS | NOT_INSTANCEOF) nls coercionType                       #relationalExprAlt
+    |   left=expression nls op=NOT_INSTANCEOF nls notInstanceofType                         #relationalExprAlt
+    |   left=expression nls op=AS nls coercionType                                          #relationalExprAlt
     |   left=expression nls op=(LE | GE | GT | LT | IN | NOT_IN) nls right=expression       #relationalExprAlt
 
     // equality/inequality (==/!=) (level 8)
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 5152b960ed..e0d05dd7fd 100644
--- a/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
+++ b/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
@@ -3232,22 +3232,30 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
                     ctx);
 
           case NOT_INSTANCEOF: {
-            CoercionTypeContext coercionCtx = ctx.coercionType();
-            if (coercionCtx.castParExpression() != null
-                    && coercionCtx.castParExpression().intersectionType().type().size() > 1) {
+            // GROOVY-12242: !instanceof Type name (JEP 394 pattern) via matchingType;
+            // parenthesised (T) / rejected intersection (A & B) via castParExpression.
+            NotInstanceofTypeContext nit = ctx.notInstanceofType();
+            if (nit.matchingType() != null) {
+                nit.matchingType().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, Boolean.TRUE);
+                return configureAST(
+                        new BinaryExpression(
+                                (Expression) this.visit(ctx.left),
+                                this.createGroovyToken(ctx.op),
+                                this.visitMatchingType(nit.matchingType())),
+                        ctx);
+            }
+            CastParExpressionContext castCtx = nit.castParExpression();
+            if (castCtx.intersectionType().type().size() > 1) {
                 throw this.createParsingFailedException("Intersection types are not supported as the right-hand side of !instanceof", ctx);
             }
-            ClassNode notInstType = this.visitCoercionType(coercionCtx);
-            // GROOVY-11998: keep IS_INSIDE_INSTANCEOF_EXPR on the parser context for the resolver
-            (coercionCtx.type() != null
-                    ? coercionCtx.type()
-                    : coercionCtx.castParExpression().intersectionType().type(0)
-            ).putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, Boolean.TRUE);
+            // GROOVY-11998: mark the type context for the resolver (parameterized RHS)
+            castCtx.intersectionType().type(0).putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, Boolean.TRUE);
+            ClassNode notInstType = this.visitCastParExpression(castCtx);
             return configureAST(
                     new BinaryExpression(
                             (Expression) this.visit(ctx.left),
                             this.createGroovyToken(ctx.op),
-                            configureAST(new ClassExpression(notInstType), coercionCtx)),
+                            configureAST(new ClassExpression(notInstType), castCtx)),
                     ctx);
           }
 
diff --git a/src/main/java/org/codehaus/groovy/classgen/VariableScopeVisitor.java b/src/main/java/org/codehaus/groovy/classgen/VariableScopeVisitor.java
index 83b41387e3..330200c4c5 100644
--- a/src/main/java/org/codehaus/groovy/classgen/VariableScopeVisitor.java
+++ b/src/main/java/org/codehaus/groovy/classgen/VariableScopeVisitor.java
@@ -798,19 +798,28 @@ public class VariableScopeVisitor extends ClassCodeVisitorSupport {
      *   <li>{@code a && b} — true-path bindings of {@code a} are in scope in {@code b}</li>
      *   <li>{@code a || b} — true-path bindings of {@code a} are <em>not</em> in scope in {@code b};
      *       false-path bindings of {@code a} are</li>
+     *   <li>{@code e !instanceof T t} / {@code !(e instanceof T t)} — pattern declare is
+     *       isolated on the left of short-circuit ops; only flow-live sets are re-introduced</li>
      * </ul>
      */
     @Override
     public void visitBinaryExpression(final BinaryExpression expression) {
         int op = expression.getOperation().getType();
         if (op == Types.LOGICAL_AND) {
-            // Left first; its true-path pattern vars stay in the current scope for the right.
+            // Symmetric to ||: isolate left's declares, then expose only whenTrue on the right.
+            // Fixes `e !instanceof T t && t.m()` and `!(e instanceof T t) && t.m()` (whenTrue={}).
+            InstanceofFlowBindings leftBindings = InstanceofFlowBindings.of(expression.getLeftExpression());
+            pushState();
             expression.getLeftExpression().visit(this);
+            popState();
+            pushState();
+            declarePatternVariables(leftBindings.whenTrue());
             expression.getRightExpression().visit(this);
+            popState();
         } else if (op == Types.LOGICAL_OR) {
             // Left's true-path bindings must not leak into the right (Java rejects
             // `o instanceof String s || s.isEmpty()`). False-path bindings of the
-            // left are in scope on the right (`!(o instanceof String s) || s.isEmpty()`).
+            // left are in scope on the right (`o !instanceof String s || s.isEmpty()`).
             InstanceofFlowBindings leftBindings = InstanceofFlowBindings.of(expression.getLeftExpression());
             pushState();
             expression.getLeftExpression().visit(this);
@@ -819,6 +828,14 @@ public class VariableScopeVisitor extends ClassCodeVisitorSupport {
             declarePatternVariables(leftBindings.whenFalse());
             expression.getRightExpression().visit(this);
             popState();
+        } else if (op == Types.COMPARE_NOT_INSTANCEOF) {
+            // Defence in depth: pattern declare on the RHS must not stick to the
+            // enclosing scope (whenTrue of !instanceof is empty). Live paths
+            // re-introduce via declarePatternVariables / short-circuit handlers.
+            expression.getLeftExpression().visit(this);
+            pushState();
+            expression.getRightExpression().visit(this);
+            popState();
         } else {
             super.visitBinaryExpression(expression);
         }
@@ -1064,9 +1081,10 @@ public class VariableScopeVisitor extends ClassCodeVisitorSupport {
      * metadata ({@link #put}/{@link #get}). Later phases must use
      * {@link #get} only — never re-call {@link #of} on the condition.
      * <p>
-     * Covered shapes: {@code e instanceof T t}, {@code e !instanceof T t},
-     * {@code !expr}, {@code a && b}, {@code a || b}. All other shapes yield
-     * {@link #EMPTY} (conservative: no definite bindings).
+     * Covered shapes: {@code e instanceof T t}, {@code e !instanceof T t}
+     * (native form and {@code !(e instanceof T t)}), {@code !expr},
+     * {@code a && b}, {@code a || b}. All other shapes yield {@link #EMPTY}
+     * (conservative: no definite bindings).
      *
      * @see VariableScopeVisitor
      * @since 6.0.0
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java b/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
index f2f0d9ffc7..bf3bf57368 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
@@ -1192,6 +1192,19 @@ public class BinaryExpressionHelper {
         }
     }
 
+    /**
+     * Emits bytecode for {@code e !instanceof T} and for the JEP&nbsp;394
+     * type pattern form {@code e !instanceof T t}.
+     * <p>
+     * Implemented as {@code !(e instanceof T [t])} so pattern store logic in
+     * {@link #evaluateInstanceof} is shared: the pattern local is assigned when
+     * the value <em>is</em> an instance of {@code T} (i.e. when the overall
+     * {@code !instanceof} result is false). Path visibility follows
+     * {@code InstanceofFlowBindings} for {@code COMPARE_NOT_INSTANCEOF}
+     * (whenTrue/whenFalse swapped relative to plain {@code instanceof}).
+     *
+     * @param expression a {@code !instanceof} binary expression
+     */
     private void evaluateNotInstanceof(final BinaryExpression expression) {
         unaryExpressionHelper.writeNotExpression(
                 notX(
diff --git a/src/spec/doc/core-semantics.adoc b/src/spec/doc/core-semantics.adoc
index 55dfaed9ec..3efc02e161 100644
--- a/src/spec/doc/core-semantics.adoc
+++ b/src/spec/doc/core-semantics.adoc
@@ -485,9 +485,9 @@ It is possible to use labels in the `break` instruction as a target for jump, as
 include::../test/semantics/LabelsTest.groovy[tags=break_label,indent=0]
 ----
 
-=== `instanceof` pattern variables (JEP 394)
+=== `instanceof` / `!instanceof` pattern variables (JEP 394)
 
-Since Groovy 6, a type pattern on `instanceof` / `!instanceof` introduces a
+Since Groovy 6, a type pattern on `instanceof` or `!instanceof` introduces a
 *pattern variable* whose scope follows Java's flow rules (JLS §6.3 / JEP 394)
 for the common shapes used in application code:
 
@@ -500,13 +500,20 @@ if (o instanceof String s) {
     // s is *not* in scope here (dynamic: MissingPropertyException; static: error)
 }
 // s is not in scope after a fall-through if either
+
+if (o !instanceof Integer i) {
+    // i is *not* in scope here (condition true means o is not an Integer)
+} else {
+    assert i instanceof Integer      // i is bound when !instanceof is false
+}
 ----
 
-Short-circuit boolean operators and ternary arms respect the same “definitely
-bound on this path” rules (`&&` exposes true-path bindings on the right-hand
-side; `||` does not). Under `@TypeChecked` / `@CompileStatic` the type checker
-rejects out-of-scope uses at compile time; in dynamic Groovy the same uses
-become dynamic property lookups and typically throw
+The form `e !instanceof T t` is equivalent to `!(e instanceof T t)` for both
+binding and scoping. Short-circuit boolean operators and ternary arms respect
+the same “definitely bound on this path” rules (`&&` exposes true-path bindings
+on the right-hand side; `||` does not). Under `@TypeChecked` / `@CompileStatic`
+the type checker rejects out-of-scope uses at compile time; in dynamic Groovy
+the same uses become dynamic property lookups and typically throw
 `groovy.lang.MissingPropertyException` at runtime.
 
 [NOTE]
diff --git a/src/test/groovy/groovy/InstanceofFlowBindingsTest.groovy b/src/test/groovy/groovy/InstanceofFlowBindingsTest.groovy
index 2645ab4086..b6ba66a08a 100644
--- a/src/test/groovy/groovy/InstanceofFlowBindingsTest.groovy
+++ b/src/test/groovy/groovy/InstanceofFlowBindingsTest.groovy
@@ -46,6 +46,30 @@ final class InstanceofFlowBindingsTest {
         assert b.allNames() as List == ['s']
     }
 
+    @Test
+    void testBindingsOfNativeNotInstanceofPattern() {
+        def b = InstanceofFlowBindings.of(parseCondition('o !instanceof String s'))
+        assert b.whenTrue().isEmpty()
+        assert b.whenFalse()*.name == ['s']
+        assert b.allNames() as List == ['s']
+        // equivalent to !(o instanceof String s)
+        def negated = InstanceofFlowBindings.of(parseCondition('!(o instanceof String s)'))
+        assert b.whenTrue()*.name == negated.whenTrue()*.name
+        assert b.whenFalse()*.name == negated.whenFalse()*.name
+    }
+
+    @Test
+    void testContainsPatternNativeNotInstanceof() {
+        assert InstanceofFlowBindings.containsPattern(parseCondition('o !instanceof String s'))
+        assert !InstanceofFlowBindings.containsPattern(parseCondition('o !instanceof String'))
+    }
+
+    @Test
+    void testAllPatternNamesNativeNotInstanceof() {
+        def expr = parseCondition('o !instanceof String s')
+        assert InstanceofFlowBindings.allPatternNames(expr) == ['s'] as Set
+    }
+
     @Test
     void testBindingsOfAnd() {
         def b = InstanceofFlowBindings.of(parseCondition('o instanceof String s && s.length() > 0'))
diff --git a/src/test/groovy/groovy/InstanceofScopeTest.groovy b/src/test/groovy/groovy/InstanceofScopeTest.groovy
index 18e82cacbe..85f7567552 100644
--- a/src/test/groovy/groovy/InstanceofScopeTest.groovy
+++ b/src/test/groovy/groovy/InstanceofScopeTest.groovy
@@ -52,6 +52,7 @@ import org.junit.jupiter.api.Test
  *  1  | o instanceof String s                 | local    | dynamic    | dynamic (*)
  *  1b | o instanceof String s, else abrupt    | local    | (abrupt)   | local
  *  2  | !(o instanceof String s)              | dynamic  | local      | —
+ *  2n | o !instanceof String s  (native)      | dynamic  | local      | dynamic  (≡ 2)
  *  3  | !(o instanceof String s), if abrupt   | (abrupt) | local      | local
  *  4  | o instanceof String s &amp;&amp; cond         | local    | dynamic    | dynamic
  *  5  | o instanceof String s || cond         | dynamic  | dynamic    | dynamic
@@ -63,6 +64,7 @@ import org.junit.jupiter.api.Test
  * (*) s NOT visible after when both branches fall through.
  * (**) missing case: abrupt else alone is not enough; if-block must
  * also be abrupt for §6.3.2.2-200-C-B to apply.
+ * (2n) native {@code !instanceof} is equivalent to {@code !(instanceof)}.
  */
 final class InstanceofScopeTest {
 
@@ -102,6 +104,101 @@ final class InstanceofScopeTest {
         !(v instanceof DynamicVariable)
     }
 
+    // -------------------------------------------------------------------------
+    // Native !instanceof Type name (equivalent to !(instanceof), JEP 394)
+    // -------------------------------------------------------------------------
+
+    /**
+     * {@code o !instanceof String s} ≡ {@code !(o instanceof String s)}:
+     * whenTrue={}, whenFalse={s} → then dynamic, else local, after dynamic.
+     */
+    @Test
+    void testNativeNotInstanceof_ifBlockDynamic_elseLocal_afterDynamic() {
+        def src = '''
+            class C {
+                def m(Object o) {
+                    if (o !instanceof String s) {
+                        s                 // then → dynamic
+                    } else {
+                        s.length()        // else → local
+                    }
+                    s                     // after → dynamic
+                }
+            }
+        '''
+        def accesses = collectAccesses(src)
+        assert accesses.size() == 3
+        assert !isLocal(accesses[0]) : "then of !instanceof: s must be dynamic"
+        assert isLocal(accesses[1])  : "else of !instanceof: s must be local"
+        assert !isLocal(accesses[2]) : "after !instanceof if: s must be dynamic"
+    }
+
+    /**
+     * Early return in then of {@code !instanceof}: whenFalse={s} survives after
+     * (same as {@code !(instanceof)} with abrupt then).
+     */
+    @Test
+    void testNativeNotInstanceof_abruptThen_afterLocal() {
+        def src = '''
+            class C {
+                def m(Object o) {
+                    if (o !instanceof String s) return
+                    s.length()            // after → local (survivor)
+                }
+            }
+        '''
+        def accesses = collectAccesses(src)
+        assert accesses.size() == 1
+        assert isLocal(accesses[0]) : "after abrupt then of !instanceof: s must be local"
+    }
+
+    /**
+     * {@code &&} RHS of native {@code !instanceof} and of {@code !(instanceof)}
+     * must both be dynamic (whenTrue empty) — short-circuit isolation is symmetric.
+     */
+    @Test
+    void testNotInstanceof_andRhsDynamic_nativeAndNegatedForms() {
+        for (String cond : [
+                'o !instanceof String s && s.isEmpty()',
+                '!(o instanceof String s) && s.isEmpty()',
+        ]) {
+            def src = """
+                class C {
+                    def m(Object o) {
+                        ${cond}
+                    }
+                }
+            """
+            def accesses = collectAccesses(src)
+            assert accesses.size() == 1 : "expected one use of s in: $cond"
+            assert !isLocal(accesses[0]) : "&& RHS must be dynamic for: $cond"
+        }
+    }
+
+    /**
+     * Redeclare in then of {@code !instanceof} is allowed (whenTrue empty).
+     */
+    @Test
+    void testNativeNotInstanceof_redeclareInThen_isLocal() {
+        def src = '''
+            class C {
+                def m(Object o) {
+                    if (o !instanceof String s) {
+                        def s = 'x'
+                        s
+                    } else {
+                        s.length()
+                    }
+                }
+            }
+        '''
+        def accesses = collectAccesses(src)
+        assert accesses.size() == 2
+        assert isLocal(accesses[0]) : "then redeclare: local"
+        assert isLocal(accesses[1]) : "else pattern: local"
+        assert !accesses[0].is(accesses[1])
+    }
+
     // -------------------------------------------------------------------------
     // Case 1: o instanceof String s
     // -------------------------------------------------------------------------
diff --git a/src/test/groovy/groovy/InstanceofTest.groovy b/src/test/groovy/groovy/InstanceofTest.groovy
index 168e125c33..9257ad8bda 100644
--- a/src/test/groovy/groovy/InstanceofTest.groovy
+++ b/src/test/groovy/groovy/InstanceofTest.groovy
@@ -96,6 +96,95 @@ final class InstanceofTest {
         assert (n instanceof Integer i && i.intValue() == 12345)
     }
 
+    // GROOVY-12242: native !instanceof type pattern (JEP 394)
+    @Test
+    void testNotInstanceofPatternVariable() {
+        def n = (Number) 12345
+        if (n !instanceof String s) {
+            assert n.intValue() == 12345
+        } else {
+            assert false : 'expected non-String'
+        }
+        if (n !instanceof Integer i) {
+            assert false : 'expected Integer (condition false)'
+        } else {
+            assert i.intValue() == 12345
+        }
+    }
+
+    // GROOVY-12242: !instanceof pattern + short-circuit / early return survivors
+    @Test
+    void testNotInstanceofPatternScope() {
+        def f = { Object o ->
+            if (o !instanceof String s) {
+                return 'not-string'
+            } else {
+                return s.toUpperCase()
+            }
+        }
+        assert f('hi') == 'HI'
+        assert f(1) == 'not-string'
+
+        def g = { Object o ->
+            if (o !instanceof String s) return 'early'
+            return s.toUpperCase()
+        }
+        assert g('ab') == 'AB'
+        assert g(9) == 'early'
+    }
+
+    // GROOVY-12242: !instanceof pattern must not leak into then-block
+    @Test
+    void testNotInstanceofPatternThenBlockDynamic() {
+        def err = shouldFail MissingPropertyException, '''
+            def m(Object o) {
+                if (o !instanceof String s) {
+                    return s
+                }
+                return 'ok'
+            }
+            m(1)
+        '''
+        assert err.message =~ /No such property: s/
+    }
+
+    // GROOVY-12242: ternary with !instanceof pattern
+    @Test
+    void testNotInstanceofPatternTernary() {
+        def f = { Object o ->
+            (o !instanceof String s) ? 'not' : s.toUpperCase()
+        }
+        assert f(1) == 'not'
+        assert f('xy') == 'XY'
+    }
+
+    // GROOVY-12242: && / || with !instanceof pattern
+    @Test
+    void testNotInstanceofPatternBooleanOps() {
+        // true path of !instanceof is empty — RHS of && must not see s as bound from left
+        def err = shouldFail MissingPropertyException, '''
+            def m(Object o) {
+                return (o !instanceof String s && s.isEmpty())
+            }
+            m(1)
+        '''
+        assert err.message =~ /No such property: s/
+
+        // Same for parenthesised negation form (&& isolation is flow-based)
+        err = shouldFail MissingPropertyException, '''
+            def m(Object o) {
+                return (!(o instanceof String s) && s.isEmpty())
+            }
+            m(1)
+        '''
+        assert err.message =~ /No such property: s/
+
+        // false path of !instanceof binds s — RHS of || can use s when left is false
+        assert (({ Object o -> (o !instanceof String s || s.isEmpty()) }('')) == true)
+        assert (({ Object o -> (o !instanceof String s || s.length() > 0) }('ab')) == true)
+        assert (({ Object o -> (o !instanceof String s || s.isEmpty()) }(1)) == true)
+    }
+
     // GROOVY-11229
     @Test
     void testVariable2() {
diff --git a/src/test/groovy/org/apache/groovy/parser/antlr4/IntersectionCastParserTest.groovy b/src/test/groovy/org/apache/groovy/parser/antlr4/IntersectionCastParserTest.groovy
index ae278f787d..f6517f43df 100644
--- a/src/test/groovy/org/apache/groovy/parser/antlr4/IntersectionCastParserTest.groovy
+++ b/src/test/groovy/org/apache/groovy/parser/antlr4/IntersectionCastParserTest.groovy
@@ -115,6 +115,14 @@ final class IntersectionCastParserTest {
         assertTrue(!ast.context.errorCollector.hasErrors())
     }
 
+    @Test
+    void 'type pattern accepted for !instanceof'() {
+        ModuleNode ast = buildAST('def b = x !instanceof String s')
+        assertNotNull(ast)
+        assertTrue(!ast.context.errorCollector.hasErrors(),
+                "Parse should accept !instanceof type pattern; got: ${ast.context.errorCollector.errors}")
+    }
+
     //--------------------------------------------------------------------------
 
     private static ClassNode singleCastTargetType(String src) {