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/09 13:31:44 UTC

(groovy) branch GROOVY-12425 updated (338a978306 -> f19e092bfa)

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

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


    omit 338a978306 GROOVY-12425: Refine error message for unclosed type argument and unclosed slashy string
     new f19e092bfa GROOVY-12425: Refine error message for unclosed type argument and unclosed slashy string

This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version.  This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:

 * -- * -- B -- O -- O -- O   (338a978306)
            \
             N -- N -- N   refs/heads/GROOVY-12425 (f19e092bfa)

You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.

Any revisions marked "omit" are not gone; other references still
refer to them.  Any revisions marked "discard" are gone forever.

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.


Summary of changes:
 .../parser/antlr4/ParserNegativeSyntaxTest.groovy  | 14 +++++++
 .../groovy/parser/antlr4/AbstractLexerTest.java    | 14 ++++++-
 .../groovy/parser/antlr4/AstBuilderHelperTest.java | 48 ++++++++++++++++++++++
 3 files changed, 75 insertions(+), 1 deletion(-)


(groovy) 01/01: GROOVY-12425: Refine error message for unclosed type argument and unclosed slashy string

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-12425
in repository https://gitbox.apache.org/repos/asf/groovy.git

commit f19e092bfac5bddb51518500ac4418c212d066ec
Author: Daniel Sun <su...@apache.org>
AuthorDate: Fri Sep 25 05:21:54 2026 +0900

    GROOVY-12425: Refine error message for unclosed type argument and unclosed slashy string
---
 src/antlr/GroovyLexer.g4                           |  57 +++++++-
 .../apache/groovy/parser/antlr4/AbstractLexer.java |  16 +-
 .../apache/groovy/parser/antlr4/AstBuilder.java    |  11 +-
 .../parser/antlr4/ParserNegativeSyntaxTest.groovy  | 162 ++++++++++++++++++++-
 .../groovy/parser/antlr4/AbstractLexerTest.java    | 115 ++++++++++++++-
 .../groovy/parser/antlr4/AstBuilderHelperTest.java |  50 +++++++
 6 files changed, 392 insertions(+), 19 deletions(-)

diff --git a/src/antlr/GroovyLexer.g4 b/src/antlr/GroovyLexer.g4
index 12f228a7d0..ad0cc80f61 100644
--- a/src/antlr/GroovyLexer.g4
+++ b/src/antlr/GroovyLexer.g4
@@ -47,7 +47,14 @@ options {
 @members {
     private boolean errorIgnored;
     private long tokenIndex;
-    private int  lastTokenType;
+    /** Previous default-channel token. {@link Token#INVALID_TYPE} at the start of an input. */
+    private int  lastTokenType = Token.INVALID_TYPE;
+    /**
+     * Last default-channel token whose type is not {@code NL}.
+     * Stays {@link Token#INVALID_TYPE} until one is seen. Not {@link Token#EOF}:
+     * a negative index is rejected by {@link java.util.BitSet#get(int)}.
+     */
+    private int  lastRealTokenType = Token.INVALID_TYPE;
 
     /**
      * When {@code false}, the {@code val} keyword is treated as a regular
@@ -67,7 +74,12 @@ options {
         this.tokenIndex++;
 
         int tokenType = token.getType();
-        if (Token.DEFAULT_CHANNEL == token.getChannel()) {
+        // EOF is negative. Recording it makes the next slashy decision call
+        // BitSet.get(-1). setInputStream rewinds only through reset().
+        if (tokenType >= 0 && Token.DEFAULT_CHANNEL == token.getChannel()) {
+            if (NL != tokenType) {
+                this.lastRealTokenType = tokenType;
+            }
             this.lastTokenType = tokenType;
         }
 
@@ -78,6 +90,13 @@ options {
         super.emit(token);
     }
 
+    @Override
+    public void reset() {
+        super.reset();
+        this.lastTokenType = Token.INVALID_TYPE;
+        this.lastRealTokenType = Token.INVALID_TYPE;
+    }
+
     /**
      * Token types after which {@code /.../} must not be treated as a slashy string
      * (e.g. {@code a++ / b}, {@code list[i] / n}). {@link java.util.BitSet} gives
@@ -106,7 +125,24 @@ options {
     }
 
     private boolean isRegexAllowed() {
-        return !REGEX_CHECK_SET.get(this.lastTokenType);
+        return !isDivisionOperand(this.lastTokenType);
+    }
+
+    /**
+     * A {@code /} that reaches EOF is an unclosed slashy string only when the
+     * previous real token (ignoring {@code NL}) could not be the left operand
+     * of division. {@code 9 \n / \n 3} stays division; {@code s = /hello} does not.
+     * {@link Token#INVALID_TYPE} (no real token yet, including a leading newline)
+     * is not an operand.
+     */
+    private boolean isUnclosedSlashy() {
+        int decision = this.lastTokenType == NL ? this.lastRealTokenType : this.lastTokenType;
+        return !isDivisionOperand(decision);
+    }
+
+    /** {@code REGEX_CHECK_SET} rejects a negative type, and {@link Token#EOF} is not an operand. */
+    private static boolean isDivisionOperand(final int tokenType) {
+        return tokenType >= 0 && REGEX_CHECK_SET.get(tokenType);
     }
 
     /**
@@ -289,13 +325,26 @@ options {
 
 
 // ยง3.10.5 String Literals
+// A quote that never closes matches nothing here, so it is UNEXPECTED_CHAR.
+// requireUnexpectedCharacter maps that quote to "Unclosed string literal"
+// unless the remainder is an illegal escape. `/` is also DIV, so an unclosed
+// `/.../` cannot use that fall-through and is an EOF alternative of this rule.
+// isUnclosedSlashy() is the first edge of that alternative, before any body
+// character is read. `*` is safe because the follower is EOF, not `/`:
+// `//` is not an empty slashy. EOF stays here so a second rule cannot
+// swallow source after a real closer.
 StringLiteral
     :   GStringQuotationMark  DqStringCharacter*  GStringQuotationMark
     |   SqStringQuotationMark  SqStringCharacter*  SqStringQuotationMark
-    |   Slash { this.isRegexAllowed() && _input.LA(1) != '*' }?  SlashyStringCharacter+  Slash
+    |   Slash { this.isRegexAllowed() && _input.LA(1) != '*' }?
+            (   SlashyStringCharacter+ Slash
+            |   { this.isUnclosedSlashy() }? SlashyStringCharacter* EOF { requireUnclosedString(errorIgnored); }
+            )
 
     |   TdqStringQuotationMark  TdqStringCharacter*  TdqStringQuotationMark
     |   TsqStringQuotationMark  TsqStringCharacter*  TsqStringQuotationMark
+    // `$/` is also identifier `$` plus division. An EOF alternative here would
+    // reject `($/2)` and `$/=`. Unclosed `$/...` stays a later error.
     |   DollarSlashyGStringQuotationMarkBegin  DollarSlashyStringCharacter+  DollarSlashyGStringQuotationMarkEnd
     ;
 
diff --git a/src/main/java/org/apache/groovy/parser/antlr4/AbstractLexer.java b/src/main/java/org/apache/groovy/parser/antlr4/AbstractLexer.java
index 4057eff850..6347aa9e4e 100644
--- a/src/main/java/org/apache/groovy/parser/antlr4/AbstractLexer.java
+++ b/src/main/java/org/apache/groovy/parser/antlr4/AbstractLexer.java
@@ -213,6 +213,16 @@ public abstract class AbstractLexer extends Lexer implements SyntaxErrorReportab
         requireAtTokenStart(errorIgnored, "Unclosed comment");
     }
 
+    /**
+     * Report an unclosed {@code /.../} at the opener (javac:
+     * {@code unclosed string literal}), not at EOF after the scan.
+     *
+     * @param errorIgnored when {@code true}, keep tokenising (IDE highlighting)
+     */
+    void requireUnclosedString(final boolean errorIgnored) {
+        requireAtTokenStart(errorIgnored, "Unclosed string literal");
+    }
+
     /**
      * Invalid octal ({@code 08}, {@code 09}, {@code 08L}) reports at the
      * token start. Using the start index rather than a running digit count keeps
@@ -226,9 +236,9 @@ public abstract class AbstractLexer extends Lexer implements SyntaxErrorReportab
     }
 
     /**
-     * {@link SyntaxErrorReportable#require} positions relative to the current
-     * lexer cursor. After scanning to EOF that cursor is past the comment, so
-     * the offset is token-start minus current (line and column).
+     * {@link SyntaxErrorReportable#require} is relative to the current lexer
+     * cursor. The offset is token-start minus that cursor, so the caret stays
+     * on the opener after a scan to EOF and on an invalid octal's first digit.
      */
     private void requireAtTokenStart(final boolean errorIgnored, final String msg) {
         require(errorIgnored, msg,
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 dde9972427..86f99b6878 100644
--- a/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
+++ b/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
@@ -2594,11 +2594,16 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
                 && baseExpr instanceof BinaryExpression bin
                 && !"[".equals(bin.getOperation().getText())) {
             // `List<Integer name` is parsed as the comparison `List < Integer` plus a
-            // command argument. javac: `'>' expected`.
-            if ("<".equals(bin.getOperation().getText())
+            // following argument list. javac: `'>' expected`. Unmatched `>` in the
+            // error strategy keeps ANTLR's offender; point at that list, not at `List`.
+            // An identifier after `T < U` is argumentList, not commandArgument.
+            // The list is the caret. Without one, keep the Unexpected input path
+            // below instead of passing a null anchor.
+            if (hasArgumentList
+                    && "<".equals(bin.getOperation().getText())
                     && looksLikeTypeName(bin.getLeftExpression())
                     && looksLikeTypeName(bin.getRightExpression())) {
-                throw createParsingFailedException("Missing '>'", bin);
+                throw createParsingFailedException("Missing '>'", ctx.enhancedArgumentListInPar());
             }
             throw createParsingFailedException("Unexpected input: '" + getOriginalText(ctx.expression()) + "'", ctx.expression());
         }
diff --git a/src/test/groovy/org/apache/groovy/parser/antlr4/ParserNegativeSyntaxTest.groovy b/src/test/groovy/org/apache/groovy/parser/antlr4/ParserNegativeSyntaxTest.groovy
index c1f90e2c8a..78c2268f3e 100644
--- a/src/test/groovy/org/apache/groovy/parser/antlr4/ParserNegativeSyntaxTest.groovy
+++ b/src/test/groovy/org/apache/groovy/parser/antlr4/ParserNegativeSyntaxTest.groovy
@@ -265,9 +265,36 @@ final class ParserNegativeSyntaxTest {
         expectParseError '''\
             |List<Integer list2 = new ArrayList<Integer>()
             |'''.stripMargin(), '''\
-            |Missing '>' @ line 1, column 1.
+            |Missing '>' @ line 1, column 14.
             |   List<Integer list2 = new ArrayList<Integer>()
-            |   ^
+            |                ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'unclosed nested type argument'() {
+        expectParseError '''\
+            |List<List<Integer> list2 = new ArrayList<>()
+            |'''.stripMargin(), '''\
+            |Missing '>' @ line 1, column 20.
+            |   List<List<Integer> list2 = new ArrayList<>()
+            |                      ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'unclosed type argument with extra space before the identifier'() {
+        // Two spaces so `name` is not the column after Integer.
+        expectParseError '''\
+            |List<Integer  name
+            |'''.stripMargin(), '''\
+            |Missing '>' @ line 1, column 15.
+            |   List<Integer  name
+            |                 ^
             |
             |1 error
             |'''.stripMargin()
@@ -3259,6 +3286,77 @@ final class ParserNegativeSyntaxTest {
             |'''.stripMargin()
     }
 
+    @Test
+    void 'unclosed quote at the start of the file'() {
+        // No surrounding tokens: the caret is the quote itself, not omitted.
+        expectParseError "'abc", '''\
+            |Unclosed string literal @ line 1, column 1.
+            |   'abc
+            |   ^
+            |
+            |1 error
+            |'''.stripMargin()
+        expectParseError '"abc', '''\
+            |Unclosed string literal @ line 1, column 1.
+            |   "abc
+            |   ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'unclosed slashy string'() {
+        expectParseError 's = /hello', '''\
+            |Unclosed string literal @ line 1, column 5.
+            |   s = /hello
+            |       ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'unclosed slashy string on a later line'() {
+        expectParseError '''\
+            |def n = 1
+            |s = /hello
+            |world
+            |'''.stripMargin(), '''\
+            |Unclosed string literal @ line 2, column 5.
+            |   s = /hello
+            |       ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'unclosed slashy string after a line break'() {
+        // The newline is not a division operand. The caret is the '/' on line 2.
+        expectParseError '''\
+            |s =
+            |/hello
+            |'''.stripMargin(), '''\
+            |Unclosed string literal @ line 2, column 1.
+            |   /hello
+            |   ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'unclosed slashy at end of file after equals'() {
+        expectParseError 's = /', '''\
+            |Unclosed string literal @ line 1, column 5.
+            |   s = /
+            |       ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
     @Test
     void 'unclosed double-quoted string'() {
         expectParseError '''\
@@ -3423,7 +3521,15 @@ final class ParserNegativeSyntaxTest {
 
     @Test
     void 'generic type missing closing angle'() {
-        expectContains 'def list1 = new ArrayList<Integer()', "Missing '>'"
+        expectParseError '''\
+            |def list1 = new ArrayList<Integer()
+            |'''.stripMargin(), '''\
+            |Missing '>' @ line 1, column 34.
+            |   def list1 = new ArrayList<Integer()
+            |                                    ^
+            |
+            |1 error
+            |'''.stripMargin()
     }
 
     @Test
@@ -3707,14 +3813,14 @@ final class ParserNegativeSyntaxTest {
 
     @Test
     void 'unclosed type argument as a comparison plus command argument'() {
-        // Spaces make `<` a comparison; `name` is then a command argument.
+        // Spaces make `<` a comparison; `name` is then the argument list.
         // AstBuilder rewrites that shape to javac's `'>' expected`.
         expectParseError '''\
             |List < Integer name
             |'''.stripMargin(), '''\
-            |Missing '>' @ line 1, column 1.
+            |Missing '>' @ line 1, column 16.
             |   List < Integer name
-            |   ^
+            |                  ^
             |
             |1 error
             |'''.stripMargin()
@@ -3725,9 +3831,35 @@ final class ParserNegativeSyntaxTest {
         expectParseError '''\
             |List<String> < Integer name
             |'''.stripMargin(), '''\
-            |Missing '>' @ line 1, column 1.
+            |Missing '>' @ line 1, column 24.
             |   List<String> < Integer name
-            |   ^
+            |                          ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'unclosed type argument with a comma-separated argument list'() {
+        expectParseError '''\
+            |List < Integer 1, 2
+            |'''.stripMargin(), '''\
+            |Missing '>' @ line 1, column 16.
+            |   List < Integer 1, 2
+            |                  ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'unclosed type argument with an argument list then a command argument'() {
+        expectParseError '''\
+            |List < Integer name foo
+            |'''.stripMargin(), '''\
+            |Missing '>' @ line 1, column 16.
+            |   List < Integer name foo
+            |                  ^
             |
             |1 error
             |'''.stripMargin()
@@ -3739,4 +3871,18 @@ final class ParserNegativeSyntaxTest {
         expectContains 'Integer < list name', "Unexpected input: 'Integer < list'"
         expectContains 'foo() < Integer name', "Unexpected input: 'foo() < Integer'"
     }
+
+    @Test
+    void 'comparison command that is not an unclosed type argument'() {
+        // Only `<` between two type names is rewritten. `>` stays Unexpected input.
+        expectParseError '''\
+            |List > Integer name
+            |'''.stripMargin(), '''\
+            |Unexpected input: 'List > Integer' @ line 1, column 1.
+            |   List > Integer name
+            |   ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
 }
diff --git a/src/test/java/org/apache/groovy/parser/antlr4/AbstractLexerTest.java b/src/test/java/org/apache/groovy/parser/antlr4/AbstractLexerTest.java
index 587fb2f727..4c2b311522 100644
--- a/src/test/java/org/apache/groovy/parser/antlr4/AbstractLexerTest.java
+++ b/src/test/java/org/apache/groovy/parser/antlr4/AbstractLexerTest.java
@@ -25,18 +25,22 @@ import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.Arguments;
 import org.junit.jupiter.params.provider.MethodSource;
 
+import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 import java.util.stream.Stream;
 
 import static org.apache.groovy.parser.antlr4.GroovyLexer.CapitalizedIdentifier;
+import static org.apache.groovy.parser.antlr4.GroovyLexer.DIV;
 import static org.apache.groovy.parser.antlr4.GroovyLexer.FloatingPointLiteral;
+import static org.apache.groovy.parser.antlr4.GroovyLexer.StringLiteral;
 import static org.apache.groovy.parser.antlr4.GroovyLexer.GStringBegin;
 import static org.apache.groovy.parser.antlr4.GroovyLexer.GStringEnd;
 import static org.apache.groovy.parser.antlr4.GroovyLexer.GStringPathPart;
 import static org.apache.groovy.parser.antlr4.GroovyLexer.Identifier;
 import static org.apache.groovy.parser.antlr4.GroovyLexer.IntegerLiteral;
+import static org.apache.groovy.parser.antlr4.GroovyLexer.NL;
 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -148,10 +152,119 @@ final class AbstractLexerTest {
                 Arguments.of("\"C:\\Users\\me\"", "Illegal escape character: '\\U'", 1, 4),
                 Arguments.of("\"C:\\Users", "Illegal escape character: '\\U'", 1, 4),
                 Arguments.of("/* comment", "Unclosed comment", 1, 1),
-                Arguments.of("    /* comment", "Unclosed comment", 1, 5)
+                Arguments.of("    /* comment", "Unclosed comment", 1, 5),
+                Arguments.of("/hello", "Unclosed string literal", 1, 1),
+                Arguments.of("    /hello", "Unclosed string literal", 1, 5),
+                Arguments.of("/hello\nworld", "Unclosed string literal", 1, 1),
+                Arguments.of("/", "Unclosed string literal", 1, 1)
         );
     }
 
+    @Test
+    void closedSlashyAndDivisionStayDistinct() {
+        List<Token> slashy = defaultChannel("/ab/");
+        assertEquals(StringLiteral, slashy.get(0).getType());
+        assertEquals("/ab/", slashy.get(0).getText());
+
+        List<Token> division = defaultChannel("a / b");
+        assertEquals(Identifier, division.get(0).getType());
+        assertEquals(DIV, division.get(1).getType());
+        assertEquals(Identifier, division.get(2).getType());
+
+        List<Token> dollar = defaultChannel("$/ab/$");
+        assertEquals(StringLiteral, dollar.get(0).getType());
+        assertEquals("$/ab/$", dollar.get(0).getText());
+    }
+
+    @Test
+    void errorIgnoredUnclosedSlashyTokenizesWithoutThrowing() {
+        GroovyLangLexer lexer = new GroovyLangLexer(CharStreams.fromString("s = /hello"));
+        lexer.setErrorIgnored(true);
+        List<Token> tokens = assertDoesNotThrow(() -> collect(lexer));
+        assertEquals(Token.EOF, tokens.get(tokens.size() - 1).getType());
+        assertTrue(tokens.stream().anyMatch(t -> t.getType() == StringLiteral && "/hello".equals(t.getText())),
+                tokens.toString());
+    }
+
+    @Test
+    void closedSlashyAfterNewlineIsStillAString() {
+        List<Token> tokens = defaultChannel("9\n/3/");
+        assertEquals(IntegerLiteral, tokens.get(0).getType());
+        assertEquals(StringLiteral, tokens.get(2).getType());
+        assertEquals("/3/", tokens.get(2).getText());
+    }
+
+    @Test
+    void lineCommentIsNotAnEmptySlashy() {
+        // Bare // is length 2, the same length as an empty slashy. StringLiteral
+        // is the earlier rule, so it would win that tie.
+        List<Token> tokens = defaultChannel("s = //\n1");
+        assertTrue(tokens.stream().anyMatch(t -> t.getType() == NL && "//".equals(t.getText())),
+                tokens.toString());
+        assertTrue(tokens.stream().noneMatch(t -> t.getType() == StringLiteral || t.getType() == DIV),
+                tokens.toString());
+        assertEquals(IntegerLiteral, tokens.get(tokens.size() - 1).getType());
+    }
+
+    @Test
+    void divisionAcrossLinesIsNotAnUnclosedSlashy() {
+        List<Token> tokens = defaultChannel("9\n/\n3");
+        assertEquals(IntegerLiteral, tokens.get(0).getType());
+        assertEquals(DIV, tokens.get(2).getType());
+        assertEquals(IntegerLiteral, tokens.get(4).getType());
+    }
+
+    @Test
+    void leadingNewlineWithoutAnOperandIsAnUnclosedSlashy() {
+        // No real token yet. A leading newline is not a division operand.
+        // lexer() stays outside the lambda so the assertion names one call.
+        GroovyLangLexer leadingNewline = lexer("\n/");
+        GroovySyntaxError err = assertThrows(GroovySyntaxError.class, () -> drain(leadingNewline));
+        assertEquals("Unclosed string literal", err.getMessage());
+        assertEquals(2, err.getLine());
+        assertEquals(1, err.getColumn());
+    }
+
+    @Test
+    void reusedLexerForgetsThePreviousDivisionOperand() {
+        // setInputStream rewinds through Lexer.reset(). Draining emits EOF
+        // (-1); a partial lex leaves the operand. Neither may decide the next input.
+        GroovyLangLexer drained = lexer("9");
+        drain(drained);
+        drained.setInputStream(CharStreams.fromString("\n/"));
+        GroovySyntaxError afterNewline = assertThrows(GroovySyntaxError.class, () -> drain(drained));
+        assertEquals("Unclosed string literal", afterNewline.getMessage());
+        assertEquals(2, afterNewline.getLine());
+        assertEquals(1, afterNewline.getColumn());
+
+        GroovyLangLexer partial = lexer("9");
+        assertEquals(IntegerLiteral, partial.nextToken().getType());
+        partial.setInputStream(CharStreams.fromString("/hello"));
+        GroovySyntaxError freshSlash = assertThrows(GroovySyntaxError.class, () -> drain(partial));
+        assertEquals("Unclosed string literal", freshSlash.getMessage());
+        assertEquals(1, freshSlash.getLine());
+        assertEquals(1, freshSlash.getColumn());
+    }
+
+    @Test
+    void divisionOperandRejectsANegativeTokenType() throws Exception {
+        // Callers only pass lastTokenType, which is never negative. EOF is -1,
+        // and BitSet.get rejects that, so the guard has to answer false itself.
+        Method method = GroovyLexer.class.getDeclaredMethod("isDivisionOperand", int.class);
+        method.setAccessible(true);
+        assertFalse((Boolean) method.invoke(null, Token.EOF));
+    }
+
+    @Test
+    void dollarThenDivisionIsNotAString() {
+        // `$` is an identifier. `$/2` is division, not an unclosed dollar-slashy string.
+        List<Token> tokens = defaultChannel("($/2)");
+        assertEquals(Identifier, tokens.get(1).getType());
+        assertEquals("$", tokens.get(1).getText());
+        assertEquals(DIV, tokens.get(2).getType());
+        assertEquals(IntegerLiteral, tokens.get(3).getType());
+    }
+
     @Test
     void twoDigitOctalIsLegal() {
         assertEquals(0, AbstractLexer.illegalEscapeLaIndex(CharStreams.fromString("\\77x\""), '"'));
diff --git a/src/test/java/org/apache/groovy/parser/antlr4/AstBuilderHelperTest.java b/src/test/java/org/apache/groovy/parser/antlr4/AstBuilderHelperTest.java
index 82f1cf9c8c..f5d90f3ade 100644
--- a/src/test/java/org/apache/groovy/parser/antlr4/AstBuilderHelperTest.java
+++ b/src/test/java/org/apache/groovy/parser/antlr4/AstBuilderHelperTest.java
@@ -18,6 +18,9 @@
  */
 package org.apache.groovy.parser.antlr4;
 
+import groovy.lang.GroovyClassLoader;
+import org.antlr.v4.runtime.CharStreams;
+import org.antlr.v4.runtime.CommonTokenStream;
 import org.codehaus.groovy.ast.ClassHelper;
 import org.codehaus.groovy.ast.ClassNode;
 import org.codehaus.groovy.ast.InnerClassNode;
@@ -31,6 +34,7 @@ import org.codehaus.groovy.control.CompilationUnit;
 import org.codehaus.groovy.control.CompilerConfiguration;
 import org.codehaus.groovy.control.ErrorCollector;
 import org.codehaus.groovy.control.Phases;
+import org.codehaus.groovy.control.SourceUnit;
 import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
@@ -42,7 +46,10 @@ import java.util.List;
 import java.util.stream.Stream;
 
 import static org.codehaus.groovy.control.CompilerConfiguration.ERROR_RECOVERY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
@@ -50,6 +57,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
  * {@code isAnonymousConstructorDeclaration} defends against (interfaces live
  * on {@code new Interface()}, which is stored as the unresolved super type).
  * The same is true of empty / null names in {@code looksLikeTypeName}.
+ * A binary command with a command argument and no argument list is also
+ * unreachable: a following primary is always the argument list.
  */
 final class AstBuilderHelperTest {
 
@@ -186,6 +195,8 @@ final class AstBuilderHelperTest {
                         }
                         """, "Annotation type elements cannot have a void return type"),
                 Arguments.of("List < Integer name", "Missing '>'"),
+                Arguments.of("List < Integer 1, 2", "Missing '>'"),
+                Arguments.of("List < Integer name foo", "Missing '>'"),
                 Arguments.of("1 = 2", "The left-hand side of an assignment must be a variable or a field"),
                 Arguments.of("foo(String a)", "Invalid method declaration; a return type or 'def' is required"),
                 Arguments.of("""
@@ -203,6 +214,45 @@ final class AstBuilderHelperTest {
         );
     }
 
+    @Test
+    void missingGtWithoutAnArgumentListStaysOnUnexpectedInput() {
+        // `List < Integer name foo` has both an argument list and a command
+        // argument. Drop the list so the `<` guard must not anchor on null.
+        String source = "List < Integer name foo";
+        CompilerConfiguration config = new CompilerConfiguration();
+        SourceUnit unit = new SourceUnit("test.groovy", source, config,
+                new GroovyClassLoader(), new ErrorCollector(config));
+        AstBuilder builder = new AstBuilder(unit, false, false);
+
+        GroovyLangLexer lexer = new GroovyLangLexer(CharStreams.fromString(source));
+        GroovyLangParser parser = new GroovyLangParser(new CommonTokenStream(lexer));
+        GroovyParser.CommandExpressionContext command = commandExpression(parser.compilationUnit());
+        assertNotNull(command.enhancedArgumentListInPar());
+        command.children.removeIf(child -> child instanceof GroovyParser.EnhancedArgumentListInParContext);
+
+        assertThrows(CompilationFailedException.class, () -> builder.visitCommandExpression(command));
+        List<String> messages = unit.getErrorCollector().getErrors().stream()
+                .filter(SyntaxErrorMessage.class::isInstance)
+                .map(msg -> ((SyntaxErrorMessage) msg).getCause().getMessage())
+                .toList();
+        assertEquals(List.of("Unexpected input: 'List < Integer' @ line 1, column 1."), messages);
+    }
+
+    private static GroovyParser.CommandExpressionContext commandExpression(final GroovyParser.CompilationUnitContext unit) {
+        GroovyParser.CommandExpressionContext[] found = new GroovyParser.CommandExpressionContext[1];
+        new GroovyParserBaseVisitor<Void>() {
+            @Override
+            public Void visitCommandExpression(final GroovyParser.CommandExpressionContext ctx) {
+                if (ctx.enhancedArgumentListInPar() != null && !ctx.commandArgument().isEmpty()) {
+                    found[0] = ctx;
+                }
+                return super.visitCommandExpression(ctx);
+            }
+        }.visit(unit);
+        assertNotNull(found[0]);
+        return found[0];
+    }
+
     @Test
     void looksLikeTypeNameAcceptsClassLiteralsAndCapitalizedVariables() throws Exception {
         assertTrue(looksLikeTypeName(new ClassExpression(ClassHelper.STRING_TYPE)));