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/09/04 21:16:52 UTC

(groovy) branch GROOVY-12353 updated (98ae71244e -> 0662618b14)

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

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


 discard 98ae71244e GROOVY-12353: Improve remaining common syntax error messages (unclosed literals, unexpected characters, missing punctuation, reserved keywords)
     new 0662618b14 GROOVY-12353: Improve remaining common syntax error messages (unclosed literals, unexpected characters, missing punctuation, reserved keywords)

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   (98ae71244e)
            \
             N -- N -- N   refs/heads/GROOVY-12353 (0662618b14)

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:
 ARCHITECTURE.md                                    |  8 ++--
 src/antlr/GroovyLexer.g4                           | 13 ++---
 .../groovy/parser/antlr4/GroovySyntaxError.java    |  2 +-
 .../internal/AbstractFriendlyErrorStrategy.java    | 21 ++++++---
 .../Comment_01x.groovy}                            | 16 +++++--
 .../groovy/parser/antlr4/GroovyParserTest.groovy   |  5 ++
 .../groovy/parser/antlr4/AbstractLexerTest.java    | 55 ++++++++++++++++++++++
 .../parser/antlr4/internal/ErrorStrategyTest.java  | 34 +++++++++++++
 8 files changed, 131 insertions(+), 23 deletions(-)
 copy src/test-resources/{bugs/BUG-GROOVY-8913.groovy => core/Comment_01x.groovy} (83%)


(groovy) 01/01: GROOVY-12353: Improve remaining common syntax error messages (unclosed literals, unexpected characters, missing punctuation, reserved keywords)

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

commit 0662618b141cc9e424bd78d4d9e0371dd85f271b
Author: Daniel Sun <su...@apache.org>
AuthorDate: Sat Sep 5 01:13:05 2026 +0900

    GROOVY-12353: Improve remaining common syntax error messages (unclosed literals, unexpected characters, missing punctuation, reserved keywords)
---
 ARCHITECTURE.md                                    |  11 +
 src/antlr/GroovyLexer.g4                           |  23 +-
 .../apache/groovy/parser/antlr4/AbstractLexer.java | 117 +++++++++
 .../apache/groovy/parser/antlr4/AstBuilder.java    |   3 +-
 .../groovy/parser/antlr4/GroovySyntaxError.java    |   9 +-
 .../parser/antlr4/SyntaxErrorReportable.java       |   7 +
 .../internal/AbstractFriendlyErrorStrategy.java    | 136 +++++++++-
 .../parser/antlr4/internal/package-info.java       |   6 +-
 src/spec/doc/core-syntax.adoc                      |   3 +
 .../core/Comment_01x.groovy}                       |  21 +-
 .../groovy/gls/generics/GenericsUsageTest.groovy   |   6 +-
 .../parser/antlr4/CommonSyntaxErrorTest.groovy     | 290 +++++++++++++++++++++
 .../groovy/parser/antlr4/GroovyParserTest.groovy   |   5 +
 .../groovy/parser/antlr4/SyntaxErrorTest.groovy    |  28 +-
 .../apache/groovy/parser/antlr4/TestUtils.groovy   |  24 ++
 .../groovy/parser/antlr4/AbstractLexerTest.java    | 211 +++++++++++++++
 .../parser/antlr4/internal/ErrorStrategyTest.java  | 173 +++++++++++-
 17 files changed, 1014 insertions(+), 59 deletions(-)

diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index b32d4104d2..e4f01adb51 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -105,6 +105,17 @@ verbatim keeps the reference precise; paraphrasing tends to drift.
   `GroovyLangParser`, `AstBuilder`, plus support classes:
   `ModifierManager`, `GroovydocManager`, `SemanticPredicates`,
   `PositionInfo`).
+- Recognition failures share one message path
+  (`DescriptiveErrorStrategy` / `RecoveringDescriptiveErrorStrategy` via
+  `AbstractFriendlyErrorStrategy`). `MissingDelimiterDiagnostic` may
+  relocate the caret for an unclosed `)` / `]` / `}`; reserved keywords
+  and sole-expected punctuation only refine the fallback sentence.
+  Lexer unexpected-character / GString-dollar display goes through
+  `Lexer.getCharErrorDisplay`. Unclosed `/*` comments are a lexer
+  diagnostic at the opener (`requireUnclosedComment`), not a parser
+  fallback. All of that runs only after recognition has already failed.
+  Do not re-introduce grammar-level parser error alternatives for this
+  (GROOVY-9588).
 - `AstBuilder` is the hand-off from CST to AST. It is large; almost
   every parser-visible language change touches it.
 
diff --git a/src/antlr/GroovyLexer.g4 b/src/antlr/GroovyLexer.g4
index dabef396b9..5e7b22fcf5 100644
--- a/src/antlr/GroovyLexer.g4
+++ b/src/antlr/GroovyLexer.g4
@@ -515,10 +515,10 @@ IntegerLiteral
         |   HexIntegerLiteral
         |   OctalIntegerLiteral
         |   BinaryIntegerLiteral
-        ) (Underscore { require(errorIgnored, "Number ending with underscores is invalid", -1, true); })?
+        ) (Underscore { require(errorIgnored, "Number ending with underscores is invalid", -1, false); })?
 
     // !!! Error Alternative !!!
-    |   Zero ([0-9] { invalidDigitCount++; })+ { require(errorIgnored, "Invalid octal number", -(invalidDigitCount + 1), true); } IntegerTypeSuffix?
+    |   Zero ([0-9] { invalidDigitCount++; })+ { require(errorIgnored, "Invalid octal number", -(invalidDigitCount + 1), false); } IntegerTypeSuffix?
     ;
 
 fragment
@@ -657,7 +657,7 @@ BinaryDigitOrUnderscore
 FloatingPointLiteral
     :   (   DecimalFloatingPointLiteral
         |   HexadecimalFloatingPointLiteral
-        ) (Underscore { require(errorIgnored, "Number ending with underscores is invalid", -1, true); })?
+        ) (Underscore { require(errorIgnored, "Number ending with underscores is invalid", -1, false); })?
     ;
 
 fragment
@@ -997,9 +997,14 @@ WS  : ([ \t]+ | LineEscape+) -> skip
 NL  : LineTerminator   { ignoreTokenInsideParens(); }
     ;
 
-// Multiple-line comments (including groovydoc comments)
+// Multiple-line comments (including groovydoc comments).
+// One outermost alt so `-> type(NL)` is legal. `.*?` then (`*/` | EOF) stops
+// at the first closer; a *separate* lexer rule for unclosed comments would
+// win by longest-match and swallow trailing source. javac reports
+// "unclosed comment" at the opener; requireUnclosedComment keeps the caret there.
 ML_COMMENT
-    :   '/*' .*? '*/'       { addComment(0); ignoreMultiLineCommentConditionally(); } -> type(NL)
+    :   '/*' .*? ('*/' | EOF { requireUnclosedComment(errorIgnored); })
+        { addComment(0); ignoreMultiLineCommentConditionally(); } -> type(NL)
     ;
 
 // Single-line comments
@@ -1010,10 +1015,12 @@ SL_COMMENT
 // Script-header comments.
 // The very first characters of the file may be "#!".  If so, ignore the first line.
 SH_COMMENT
-    :   '#!' { require(errorIgnored || 0 == this.tokenIndex, "Shebang comment should appear at the first line", -2, true); } ShCommand (LineTerminator '#!' ShCommand)* -> skip
+    :   '#!' { require(errorIgnored || 0 == this.tokenIndex, "Shebang comment should appear at the first line", -2, false); } ShCommand (LineTerminator '#!' ShCommand)* -> skip
     ;
 
-// Unexpected characters will be handled by groovy parser later.
+// Unexpected characters (and unclosed quotes). Display goes through
+// AbstractLexer#getCharErrorDisplay; an unexpected quote is reported as
+// an unclosed string literal.
 UNEXPECTED_CHAR
-    :   . { require(errorIgnored, "Unexpected character: '" + getText().replace("'", "\\'") + "'", -1, false); }
+    :   . { require(errorIgnored, unexpectedCharacterMessage(), -1, false); }
     ;
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 b3781b4d73..3056e4cf98 100644
--- a/src/main/java/org/apache/groovy/parser/antlr4/AbstractLexer.java
+++ b/src/main/java/org/apache/groovy/parser/antlr4/AbstractLexer.java
@@ -18,15 +18,132 @@
  */
 package org.apache.groovy.parser.antlr4;
 
+import groovy.lang.Tuple;
 import org.antlr.v4.runtime.CharStream;
 import org.antlr.v4.runtime.Lexer;
+import org.antlr.v4.runtime.Token;
 
 /**
  * Because antlr4 does not support generating lexer with specified interface,
  * we have to create a super class for it and implement the interface.
+ * <p>
+ * Lexer-error-path helpers used from {@code GroovyLexer.g4} actions also live
+ * here so the grammar stays thin. Successful tokenisation never calls them.
+ * Character display for diagnostics goes through {@link #getCharErrorDisplay(int)}
+ * so GString dollar errors and {@code UNEXPECTED_CHAR} share one escape policy.
+ * </p>
  */
 public abstract class AbstractLexer extends Lexer implements SyntaxErrorReportable {
+
     public AbstractLexer(CharStream input) {
         super(input);
     }
+
+    /**
+     * User-facing message for {@code UNEXPECTED_CHAR}.
+     * <p>
+     * An unexpected {@code '} or {@code "} is reported as an unclosed string
+     * literal (javac: {@code unclosed string literal}). Other characters use
+     * {@code Unexpected character: '...'} via {@link #getCharErrorDisplay(int)}.
+     * </p>
+     */
+    String unexpectedCharacterMessage() {
+        return unexpectedCharacterMessage(getText());
+    }
+
+    /**
+     * @param text the unexpected character(s), or {@code null}/{@code ""} if the
+     *             lexer has no current text (still reported, without a glyph)
+     */
+    static String unexpectedCharacterMessage(final String text) {
+        if (text == null || text.isEmpty()) {
+            return "Unexpected character";
+        }
+        int cp = text.codePointAt(0);
+        if (cp == '\'' || cp == '"') {
+            return "Unclosed string literal";
+        }
+        return "Unexpected character: " + quotedCodePoint(cp);
+    }
+
+    /**
+     * Report an unclosed {@code /}{@code *} comment at the opener (javac:
+     * {@code unclosed comment}), not at EOF after the scan.
+     *
+     * @param errorIgnored when {@code true}, keep tokenising (IDE highlighting)
+     */
+    void requireUnclosedComment(final boolean errorIgnored) {
+        require(errorIgnored, "Unclosed comment",
+                Tuple.tuple(_tokenStartLine - getLine(),
+                        _tokenStartCharPositionInLine - getCharPositionInLine()),
+                false);
+    }
+
+    /**
+     * Quoted diagnostic form of a code point. Overrides ANTLR's UTF-16
+     * {@code (char)} truncation and limited escapes so both unexpected-character
+     * and GString-dollar messages can name invisible code points.
+     */
+    @Override
+    public String getCharErrorDisplay(final int c) {
+        if (c == Token.EOF) {
+            return "'<EOF>'";
+        }
+        return quotedCodePoint(c);
+    }
+
+    private static String quotedCodePoint(final int cp) {
+        return "'" + displayCodePoint(cp) + "'";
+    }
+
+    /**
+     * Render {@code cp} for a diagnostic, matching javac's {@code Convert.quote}
+     * for the standard escapes and using a UTF-16 unicode escape for other
+     * non-printable / format / ignorable code points. Printable characters —
+     * including non-ASCII such as emoji — are left as-is so the message stays
+     * readable when the glyph is visible.
+     */
+    private static String displayCodePoint(final int cp) {
+        switch (cp) {
+            case '\b':
+                return "\\b";
+            case '\t':
+                return "\\t";
+            case '\n':
+                return "\\n";
+            case '\f':
+                return "\\f";
+            case '\r':
+                return "\\r";
+            case '\'':
+                return "\\'";
+            case '\\':
+                return "\\\\";
+            default:
+                if (shouldEscape(cp)) {
+                    if (cp <= 0xFFFF) {
+                        return String.format("\\u%04x", cp);
+                    }
+                    return String.format("\\u%04x\\u%04x",
+                            (int) Character.highSurrogate(cp),
+                            (int) Character.lowSurrogate(cp));
+                }
+                return new String(Character.toChars(cp));
+        }
+    }
+
+    private static boolean shouldEscape(final int cp) {
+        if (cp < 0x20 || cp == 0x7F) {
+            return true;
+        }
+        int type = Character.getType(cp);
+        return type == Character.CONTROL
+                || type == Character.FORMAT
+                || type == Character.LINE_SEPARATOR
+                || type == Character.PARAGRAPH_SEPARATOR
+                || type == Character.SURROGATE
+                || type == Character.PRIVATE_USE
+                || type == Character.UNASSIGNED
+                || Character.isIdentifierIgnorable(cp);
+    }
 }
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 c463ac4346..0a291629b5 100644
--- a/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
+++ b/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
@@ -4500,7 +4500,8 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
         for (int i = 0, n = formalParameterList.size(); i < n - 1; i += 1) {
             FormalParameterContext formalParameterContext = formalParameterList.get(i);
             if (asBoolean(formalParameterContext.ELLIPSIS())) {
-                throw createParsingFailedException("The var-arg parameter strs must be the last parameter", formalParameterContext);
+                String name = formalParameterContext.variableDeclaratorId().getText();
+                throw createParsingFailedException("The var-arg parameter " + name + " must be the last parameter", formalParameterContext);
             }
         }
     }
diff --git a/src/main/java/org/apache/groovy/parser/antlr4/GroovySyntaxError.java b/src/main/java/org/apache/groovy/parser/antlr4/GroovySyntaxError.java
index 3ce09c2f7d..de911151d2 100644
--- a/src/main/java/org/apache/groovy/parser/antlr4/GroovySyntaxError.java
+++ b/src/main/java/org/apache/groovy/parser/antlr4/GroovySyntaxError.java
@@ -19,7 +19,14 @@
 package org.apache.groovy.parser.antlr4;
 
 /**
- * Represents a syntax error of groovy program
+ * Represents a syntax error of a Groovy program, raised by the lexer or parser.
+ * <p>
+ * The message is the diagnostic as produced by the recogniser (for example
+ * {@code Unclosed string literal} or {@code Unexpected character: '\u005cu200b'}).
+ * Line and column are 1-based; they are the caret location, not part of the
+ * message string — {@link org.codehaus.groovy.syntax.SyntaxException} appends
+ * {@code @ line N, column M} when the error is reported through the compiler.
+ * </p>
  */
 public class GroovySyntaxError extends AssertionError {
     public static final int LEXER = 0;
diff --git a/src/main/java/org/apache/groovy/parser/antlr4/SyntaxErrorReportable.java b/src/main/java/org/apache/groovy/parser/antlr4/SyntaxErrorReportable.java
index 92c927ae9d..8f8518370d 100644
--- a/src/main/java/org/apache/groovy/parser/antlr4/SyntaxErrorReportable.java
+++ b/src/main/java/org/apache/groovy/parser/antlr4/SyntaxErrorReportable.java
@@ -56,6 +56,13 @@ public interface SyntaxErrorReportable {
     default void throwSyntaxError(String msg, int offset, boolean toAttachPositionInfo) {
         throwSyntaxError(msg, Tuple.tuple(0, offset), toAttachPositionInfo);
     }
+    /**
+     * @param toAttachPositionInfo if {@code true}, append {@code " @ line N, column M"}
+     *                             to the exception message. Leave {@code false} when the
+     *                             error will be wrapped in {@link org.codehaus.groovy.syntax.SyntaxException},
+     *                             which already appends the same location (otherwise the
+     *                             displayed message repeats the position).
+     */
     default void throwSyntaxError(String msg, Tuple2<Integer, Integer> offset, boolean toAttachPositionInfo) {
         PositionInfo positionInfo = this.genPositionInfo(offset);
         throw new GroovySyntaxError(msg + (toAttachPositionInfo ? positionInfo.toString() : ""),
diff --git a/src/main/java/org/apache/groovy/parser/antlr4/internal/AbstractFriendlyErrorStrategy.java b/src/main/java/org/apache/groovy/parser/antlr4/internal/AbstractFriendlyErrorStrategy.java
index 11fbb850e1..663208f666 100644
--- a/src/main/java/org/apache/groovy/parser/antlr4/internal/AbstractFriendlyErrorStrategy.java
+++ b/src/main/java/org/apache/groovy/parser/antlr4/internal/AbstractFriendlyErrorStrategy.java
@@ -28,16 +28,38 @@ import org.antlr.v4.runtime.RecognitionException;
 import org.antlr.v4.runtime.Token;
 import org.antlr.v4.runtime.TokenStream;
 import org.antlr.v4.runtime.misc.Interval;
+import org.antlr.v4.runtime.misc.IntervalSet;
 
 import java.util.Objects;
 
+import static org.apache.groovy.parser.antlr4.GroovyParser.CASE;
+import static org.apache.groovy.parser.antlr4.GroovyParser.CATCH;
+import static org.apache.groovy.parser.antlr4.GroovyParser.COLON;
+import static org.apache.groovy.parser.antlr4.GroovyParser.CONST;
+import static org.apache.groovy.parser.antlr4.GroovyParser.ELSE;
+import static org.apache.groovy.parser.antlr4.GroovyParser.FINALLY;
+import static org.apache.groovy.parser.antlr4.GroovyParser.GOTO;
+import static org.apache.groovy.parser.antlr4.GroovyParser.GT;
+import static org.apache.groovy.parser.antlr4.GroovyParser.LBRACE;
+import static org.apache.groovy.parser.antlr4.GroovyParser.LBRACK;
+import static org.apache.groovy.parser.antlr4.GroovyParser.LPAREN;
+import static org.apache.groovy.parser.antlr4.GroovyParser.SEMI;
+import static org.apache.groovy.parser.antlr4.GroovyParser.WHILE;
+
 /**
  * Shared friendly recognition diagnostics for Parrot error strategies.
  * <p>
  * Subclasses choose control flow ({@link DescriptiveErrorStrategy} fail-fast vs
- * {@link RecoveringDescriptiveErrorStrategy} multi-error resync). Reporting —
- * including {@link MissingDelimiterDiagnostic} — stays here so both modes share
- * one message path.
+ * {@link RecoveringDescriptiveErrorStrategy} multi-error resync). Reporting
+ * stays here so both modes share one message path. A successful parse never
+ * enters these methods.
+ * </p>
+ * <p>
+ * Two layers, on purpose: {@link MissingDelimiterDiagnostic} may <em>relocate</em>
+ * the caret (insertion point after an unclosed {@code ) } / {@code ] } / {@code } }).
+ * Keyword / sole-expected-punctuation / unexpected-EOF wording only changes the
+ * sentence and keeps ANTLR's offending token, so it is a fallback-string refine
+ * rather than a second locate pass.
  * </p>
  */
 abstract class AbstractFriendlyErrorStrategy extends DefaultErrorStrategy {
@@ -49,24 +71,116 @@ abstract class AbstractFriendlyErrorStrategy extends DefaultErrorStrategy {
     }
 
     /**
-     * Prefer a precise "Missing …" delimiter diagnostic when the token stream
-     * clearly indicates an unclosed / incomplete construct; otherwise fall
-     * back to the generic message.
+     * Prefer a relocated "Missing …" closer when the token stream supports it;
+     * otherwise refine the generic {@code Unexpected input: ...} fallback
+     * (reserved keyword, sole expected punctuation, unexpected EOF).
+     * Locate/refine run in a defensive try; listener dispatch is outside so a
+     * listener {@link IllegalArgumentException} / {@link IndexOutOfBoundsException}
+     * is not mistaken for a lookup failure and re-dispatched.
      */
     private void reportFriendlyError(final Parser recognizer, final RecognitionException e, final String fallbackMessage) {
         MissingDelimiterDiagnostic.Hit hit = null;
+        String message = fallbackMessage;
         try {
-            // Incomplete / synthetic contexts can leave token indices out of range.
+            // Incomplete / synthetic contexts can leave token indices out of range,
+            // and getExpectedTokens() can reject an invalid ATN state number.
             hit = MissingDelimiterDiagnostic.locate(recognizer.getInputStream(), e);
+            if (hit == null) {
+                message = refineFallbackMessage(e, fallbackMessage);
+            }
         } catch (IndexOutOfBoundsException | IllegalArgumentException ignored) {
-            // Fall through to the generic message. Catch only locate()'s known
-            // defensive failures — never listener-side fatals (e.g. addFatalError).
+            hit = null;
+            message = fallbackMessage;
         }
         if (hit != null) {
             recognizer.notifyErrorListeners(hit.at, hit.message, e);
-            return;
+        } else {
+            notifyErrorListeners(recognizer, message, e);
+        }
+    }
+
+    /**
+     * Improve a generic mismatch/NVAE sentence without moving the caret.
+     * Precedence: reserved/misplaced keyword, then a singleton expected
+     * punctuation token, then unexpected EOF, then {@code generic}.
+     */
+    static String refineFallbackMessage(final RecognitionException e, final String generic) {
+        if (e == null) {
+            return generic;
+        }
+        Token offending = e.getOffendingToken();
+        if (offending != null) {
+            String keyword = keywordMessage(offending.getType());
+            if (keyword != null) {
+                return keyword;
+            }
+        }
+        String sole = soleExpectedMessage(e);
+        if (sole != null) {
+            return sole;
+        }
+        if (offending != null && offending.getType() == Token.EOF) {
+            return "Unexpected end of input";
         }
-        notifyErrorListeners(recognizer, fallbackMessage, e);
+        return generic;
+    }
+
+    /**
+     * javac wording for reserved keywords Groovy tokenises but does not
+     * implement, and for control-flow keywords that appear as the offending
+     * token. Like javac, the sentence names the keyword even when a related
+     * construct is nearby but incomplete ({@code if (x) else {}} is
+     * {@code 'else' without 'if'} because the then-branch is missing).
+     * {@code const} is reserved and unused in Java (JLS 3.9); the replacements
+     * are {@code val} (locals; preferred over {@code final} in Groovy 6) and
+     * {@code static final} (class constants).
+     */
+    static String keywordMessage(final int tokenType) {
+        return switch (tokenType) {
+            case CONST -> "'const' is not supported; use 'val' or 'static final' instead";
+            case GOTO -> "'goto' is not supported";
+            case ELSE -> "'else' without 'if'";
+            case CATCH -> "'catch' without 'try'";
+            case FINALLY -> "'finally' without 'try'";
+            case CASE -> "'case' outside of switch";
+            default -> null;
+        };
+    }
+
+    /**
+     * When ANTLR's expected set is a single punctuation token, name it
+     * (javac: {@code '(' expected} → {@code Missing '('}). Closers are omitted:
+     * {@link MissingDelimiterDiagnostic} already decides those with a depth check,
+     * so a balanced {@code [1,,2]} is not reported as {@code Missing ']'}.
+     */
+    static String soleExpectedMessage(final RecognitionException e) {
+        if (e == null) {
+            return null;
+        }
+        final IntervalSet expected;
+        try {
+            expected = e.getExpectedTokens();
+        } catch (IllegalArgumentException | IndexOutOfBoundsException ignored) {
+            // ATN.getExpectedTokens rejects an invalid offending state.
+            return null;
+        }
+        if (expected == null || expected.size() != 1) {
+            return null;
+        }
+        return soleExpectedMessage(expected.getMinElement());
+    }
+
+    static String soleExpectedMessage(final int tokenType) {
+        return switch (tokenType) {
+            case LPAREN -> "Missing '('";
+            case LBRACK -> "Missing '['";
+            case LBRACE -> "Missing '{'";
+            case COLON -> "Missing ':'";
+            case SEMI -> "Missing ';'";
+            case GT -> "Missing '>'";
+            case WHILE -> "Missing 'while'";
+            default -> null;
+        };
     }
 
     protected String createNoViableAlternativeErrorMessage(final Parser recognizer, final NoViableAltException e) {
diff --git a/src/main/java/org/apache/groovy/parser/antlr4/internal/package-info.java b/src/main/java/org/apache/groovy/parser/antlr4/internal/package-info.java
index adfc5e5381..bd535efbe1 100644
--- a/src/main/java/org/apache/groovy/parser/antlr4/internal/package-info.java
+++ b/src/main/java/org/apache/groovy/parser/antlr4/internal/package-info.java
@@ -20,6 +20,10 @@
 /**
  * Internal utilities for the ANTLR4 (Parrot) parser: ATN management, friendly
  * error strategies ({@link DescriptiveErrorStrategy} fail-fast,
- * {@link RecoveringDescriptiveErrorStrategy} multi-error), and related diagnostics.
+ * {@link RecoveringDescriptiveErrorStrategy} multi-error), and related
+ * diagnostics ({@link MissingDelimiterDiagnostic} for relocated missing-closer
+ * carets; fallback wording lives on {@link AbstractFriendlyErrorStrategy}).
+ * Diagnostic helpers run only after recognition has already failed so they do
+ * not affect steady-state parse performance.
  */
 package org.apache.groovy.parser.antlr4.internal;
diff --git a/src/spec/doc/core-syntax.adoc b/src/spec/doc/core-syntax.adoc
index e826b6fd39..86b4095920 100644
--- a/src/spec/doc/core-syntax.adoc
+++ b/src/spec/doc/core-syntax.adoc
@@ -125,6 +125,9 @@ include::../test/SyntaxTest.groovy[tags=reserved_keywords,indent=0]
 |===
 
 Of these, `const`, `goto`, `strictfp`, and `threadsafe` are not currently in use.
+Using `const` or `goto` is a compilation error: the diagnostic names the
+reserved keyword and, for `const`, points at `val` (locals; preferred
+over `final` in Groovy 6) or `static final` (class constants).
 
 The reserved keywords can't in general be used for variable, field and method names.
 
diff --git a/src/main/java/org/apache/groovy/parser/antlr4/internal/package-info.java b/src/test-resources/core/Comment_01x.groovy
similarity index 74%
copy from src/main/java/org/apache/groovy/parser/antlr4/internal/package-info.java
copy to src/test-resources/core/Comment_01x.groovy
index adfc5e5381..9696eb985e 100644
--- a/src/main/java/org/apache/groovy/parser/antlr4/internal/package-info.java
+++ b/src/test-resources/core/Comment_01x.groovy
@@ -17,9 +17,18 @@
  *  under the License.
  */
 
-/**
- * Internal utilities for the ANTLR4 (Parrot) parser: ATN management, friendly
- * error strategies ({@link DescriptiveErrorStrategy} fail-fast,
- * {@link RecoveringDescriptiveErrorStrategy} multi-error), and related diagnostics.
- */
-package org.apache.groovy.parser.antlr4.internal;
+/* leading */
+def x = 1
+assert x == 1
+
+/** groovydoc-looking */
+def y = 2
+assert y == 2
+
+/* inner /* is just text */
+assert true
+
+/* empty closer follows */
+/**/
+def z = 3
+assert z == 3
diff --git a/src/test/groovy/gls/generics/GenericsUsageTest.groovy b/src/test/groovy/gls/generics/GenericsUsageTest.groovy
index 194b97bafa..c7c5117ea7 100644
--- a/src/test/groovy/gls/generics/GenericsUsageTest.groovy
+++ b/src/test/groovy/gls/generics/GenericsUsageTest.groovy
@@ -193,7 +193,7 @@ final class GenericsUsageTest {
     void testCompilationWithMissingClosingBracketsInGenerics() {
         shouldFailCompilationWithMessage '''
             def list1 = new ArrayList<Integer()
-        ''', "Unexpected input: '('"
+        ''', "Missing '>'"
 
         shouldFailCompilationWithMessage '''
             List<Integer list2 = new ArrayList<Integer>()
@@ -210,7 +210,7 @@ final class GenericsUsageTest {
 
         shouldFailCompilationWithMessage '''
             abstract class ArrayList1<E extends AbstractList<E> implements List<E> {}
-        ''', "Unexpected input: 'implements'"
+        ''', "Missing '>'"
 
         shouldFailCompilationWithMessage '''
             abstract class ArrayList2<E> extends AbstractList<E implements List<E> {}
@@ -226,7 +226,7 @@ final class GenericsUsageTest {
 
         shouldFailCompilationWithMessage '''
             def List<List<Integer>> history = new ArrayList<List<Integer>()
-        ''', "Unexpected input: '('"
+        ''', "Missing '>'"
     }
 
     // GROOVY-3975
diff --git a/src/test/groovy/org/apache/groovy/parser/antlr4/CommonSyntaxErrorTest.groovy b/src/test/groovy/org/apache/groovy/parser/antlr4/CommonSyntaxErrorTest.groovy
new file mode 100644
index 0000000000..a5642bab32
--- /dev/null
+++ b/src/test/groovy/org/apache/groovy/parser/antlr4/CommonSyntaxErrorTest.groovy
@@ -0,0 +1,290 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.groovy.parser.antlr4
+
+import groovy.transform.AutoFinal
+import org.codehaus.groovy.control.CompilationUnit
+import org.codehaus.groovy.control.Phases
+import org.junit.jupiter.api.Assertions
+import org.junit.jupiter.api.Test
+
+import static org.apache.groovy.parser.antlr4.TestUtils.expectParseError
+
+/**
+ * Message-quality catalog for the javac-aligned diagnostics added around
+ * unclosed literals, escaped unexpected characters, missing punctuation,
+ * and reserved keywords.
+ * <p>
+ * Caret-level contracts for missing {@code ) } / {@code ] } / {@code } },
+ * GString {@code $}, and declaration-shape errors stay in {@link SyntaxErrorTest}.
+ * This class locks the <em>new</em> sentences.
+ * </p>
+ */
+@AutoFinal
+final class CommonSyntaxErrorTest {
+
+    @Test
+    void 'unclosed single-quoted string'() {
+        expectParseError '''\
+            |println 'Hello
+            |'''.stripMargin(), '''\
+            |Unclosed string literal @ line 1, column 9.
+            |   println 'Hello
+            |           ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'unclosed double-quoted string'() {
+        expectParseError '''\
+            |println "Hello
+            |'''.stripMargin(), '''\
+            |Unclosed string literal @ line 1, column 9.
+            |   println "Hello
+            |           ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'unclosed triple-quoted string'() {
+        expectContains "s = '''hello", 'Unclosed string literal'
+    }
+
+    @Test
+    void 'unclosed comment'() {
+        expectParseError '''\
+            |/* comment
+            |'''.stripMargin(), '''\
+            |Unclosed comment @ line 1, column 1.
+            |   /* comment
+            |   ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'unclosed comment after a statement'() {
+        expectParseError '''\
+            |def x = 1
+            |/* still open
+            |'''.stripMargin(), '''\
+            |Unclosed comment @ line 2, column 1.
+            |   /* still open
+            |   ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'zero-width space is shown as a unicode escape'() {
+        expectParseError "def \u200Bname = null\n", '''\
+            |Unexpected character: '\\u200b' @ line 1, column 5.
+            |   def \u200Bname = null
+            |       ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'form feed is shown as \\f'() {
+        expectParseError "def na\u000Cme = null\n", '''\
+            |Unexpected character: '\\f' @ line 1, column 7.
+            |   def na\u000Cme = null
+            |         ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'NUL is shown as a unicode escape'() {
+        expectContains 'def x\u0000 = 1', "Unexpected character: '\\u0000'"
+    }
+
+    @Test
+    void 'BOM is shown as a unicode escape'() {
+        expectContains "\uFEFFdef x = 1", "Unexpected character: '\\ufeff'"
+    }
+
+    @Test
+    void 'printable unexpected character is shown as itself'() {
+        expectContains 'def `name` = 1', "Unexpected character: '`'"
+    }
+
+    @Test
+    void 'if without parentheses'() {
+        expectParseError '''\
+            |if true { x = 1 }
+            |'''.stripMargin(), '''\
+            |Missing '(' @ line 1, column 4.
+            |   if true { x = 1 }
+            |      ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'while without parentheses'() {
+        expectContains 'while true { x = 1 }', "Missing '('"
+    }
+
+    @Test
+    void 'for without parentheses'() {
+        expectContains 'for int i in 1..2 {}', "Missing '('"
+    }
+
+    @Test
+    void 'incomplete ternary missing colon'() {
+        expectParseError 'x ? y', '''\
+            |Missing ':' @ line 1, column 6.
+            |   x ? y
+            |        ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'generic type missing closing angle'() {
+        expectContains 'def list1 = new ArrayList<Integer()', "Missing '>'"
+    }
+
+    @Test
+    void 'const is not supported'() {
+        expectParseError '''\
+            |const x = 1
+            |'''.stripMargin(), '''\
+            |'const' is not supported; use 'val' or 'static final' instead @ line 1, column 1.
+            |   const x = 1
+            |   ^
+            |
+            |1 error
+            |'''.stripMargin()
+        // Same sentence in class and method bodies: the token has no parse
+        // context cheap enough to pick one replacement, so both are named.
+        expectContains 'class C { const x = 1 }', "'const' is not supported; use 'val' or 'static final' instead"
+        expectContains 'def m() { const x = 1 }', "'const' is not supported; use 'val' or 'static final' instead"
+    }
+
+    @Test
+    void 'goto is not supported'() {
+        expectParseError '''\
+            |goto label
+            |'''.stripMargin(), '''\
+            |'goto' is not supported @ line 1, column 1.
+            |   goto label
+            |   ^
+            |
+            |1 error
+            |'''.stripMargin()
+    }
+
+    @Test
+    void 'else after if with no then-branch still names else'() {
+        expectContains 'if (x) else { }', "'else' without 'if'"
+    }
+
+    @Test
+    void 'else without if'() {
+        expectContains 'else { x = 1 }', "'else' without 'if'"
+    }
+
+    @Test
+    void 'catch without try'() {
+        expectContains 'catch (e) { }', "'catch' without 'try'"
+    }
+
+    @Test
+    void 'finally without try'() {
+        expectContains 'finally { }', "'finally' without 'try'"
+    }
+
+    @Test
+    void 'case outside of switch'() {
+        expectContains 'case 1: x = 1', "'case' outside of switch"
+    }
+
+    @Test
+    void 'throw with nothing after it'() {
+        expectContains 'throw', 'Unexpected end of input'
+    }
+
+    @Test
+    void 'import static with nothing after it'() {
+        expectContains 'import static', 'Unexpected end of input'
+    }
+
+    @Test
+    void 'number ending with underscore'() {
+        def msg = compileMessage('def n = 1_')
+        assertContains msg, 'Number ending with underscores is invalid'
+        Assertions.assertEquals(1, (msg =~ /@ line /).count, "position must appear once, got: $msg")
+    }
+
+    @Test
+    void 'invalid octal number'() {
+        def msg = compileMessage('def n = 08')
+        assertContains msg, 'Invalid octal number'
+        Assertions.assertEquals(1, (msg =~ /@ line /).count, "position must appear once, got: $msg")
+    }
+
+    @Test
+    void 'shebang not on the first line'() {
+        def msg = compileMessage('x = 1\n#!/usr/bin/env groovy')
+        assertContains msg, 'Shebang comment should appear at the first line'
+        Assertions.assertEquals(1, (msg =~ /@ line /).count, "position must appear once, got: $msg")
+    }
+
+    @Test
+    void 'varargs must be the last parameter and names it'() {
+        expectContains 'def m(int... a, int b) {}', 'The var-arg parameter a must be the last parameter'
+    }
+
+    //--------------------------------------------------------------------------
+
+    private static void expectContains(String source, String fragment) {
+        assertContains compileMessage(source), fragment
+    }
+
+    private static void assertContains(String msg, String fragment) {
+        Assertions.assertTrue(msg.contains(fragment), "expected '$fragment' in:\n$msg")
+    }
+
+    private static String compileMessage(String source) {
+        try {
+            new CompilationUnit().with {
+                addSource('test.groovy', source)
+                compile(Phases.CONVERSION)
+                getAST()
+            }
+            Assertions.fail('expected parse to fail')
+            return ''
+        } catch (e) {
+            return (e.message ?: e.toString()).replace('\r\n', '\n')
+        }
+    }
+}
diff --git a/src/test/groovy/org/apache/groovy/parser/antlr4/GroovyParserTest.groovy b/src/test/groovy/org/apache/groovy/parser/antlr4/GroovyParserTest.groovy
index 3ca7c7b28c..707f786ae7 100644
--- a/src/test/groovy/org/apache/groovy/parser/antlr4/GroovyParserTest.groovy
+++ b/src/test/groovy/org/apache/groovy/parser/antlr4/GroovyParserTest.groovy
@@ -488,6 +488,11 @@ final class GroovyParserTest {
         doRunAndTestAntlr4('core/Val_01x.groovy')
     }
 
+    @Test
+    void 'groovy core - block comments'() {
+        doRunAndTestAntlr4('core/Comment_01x.groovy')
+    }
+
     @Test
     void 'groovy core - var'() {
         doRunAndTestAntlr4('core/Var_01x.groovy')
diff --git a/src/test/groovy/org/apache/groovy/parser/antlr4/SyntaxErrorTest.groovy b/src/test/groovy/org/apache/groovy/parser/antlr4/SyntaxErrorTest.groovy
index 06373e374e..66c8365e40 100644
--- a/src/test/groovy/org/apache/groovy/parser/antlr4/SyntaxErrorTest.groovy
+++ b/src/test/groovy/org/apache/groovy/parser/antlr4/SyntaxErrorTest.groovy
@@ -20,11 +20,9 @@ package org.apache.groovy.parser.antlr4
 
 import groovy.test.NotYetImplemented
 import groovy.transform.AutoFinal
-import org.codehaus.groovy.control.CompilationUnit
-import org.codehaus.groovy.control.Phases
-import org.junit.jupiter.api.Assertions
 import org.junit.jupiter.api.Test
 
+import static org.apache.groovy.parser.antlr4.TestUtils.expectParseError
 import static org.apache.groovy.parser.antlr4.util.ASTComparatorCategory.LOCATION_IGNORE_LIST
 
 /**
@@ -83,12 +81,12 @@ final class SyntaxErrorTest {
         TestUtils.doRunAndShouldFail('fail/UnexpectedCharacter_01x.groovy')
     }
 
-    @Test // TODO: Could the character be escaped in the error message?
+    @Test
     void 'groovy core - UnexpectedCharacter 2'() {
         expectParseError '''\
             |def \u200Bname = null
             |'''.stripMargin(), '''\
-            |Unexpected character: '\u200B' @ line 1, column 5.
+            |Unexpected character: '\\u200b' @ line 1, column 5.
             |   def \u200Bname = null
             |       ^
             |
@@ -98,7 +96,7 @@ final class SyntaxErrorTest {
         expectParseError '''\
             |def na\u200Bme = null
             |'''.stripMargin(), '''\
-            |Unexpected character: '\u200B' @ line 1, column 7.
+            |Unexpected character: '\\u200b' @ line 1, column 7.
             |   def na\u200Bme = null
             |         ^
             |
@@ -108,7 +106,7 @@ final class SyntaxErrorTest {
         expectParseError '''\
             |def na\u000Cme = null
             |'''.stripMargin(), '''\
-            |Unexpected character: '\u000C' @ line 1, column 7.
+            |Unexpected character: '\\f' @ line 1, column 7.
             |   def na\u000Cme = null
             |         ^
             |
@@ -123,7 +121,7 @@ final class SyntaxErrorTest {
             |  println 'Hello
             |}
             |'''.stripMargin(), '''\
-            |Unexpected character: '\\'' @ line 2, column 11.
+            |Unclosed string literal @ line 2, column 11.
             |     println 'Hello
             |             ^
             |
@@ -966,20 +964,6 @@ final class SyntaxErrorTest {
 
     //--------------------------------------------------------------------------
 
-    private static void expectParseError(String source, String expect) {
-        try {
-            new CompilationUnit().with {
-                addSource('test.groovy', source)
-                compile(Phases.CONVERSION)
-                getAST()
-            }
-            Assertions.fail('expected parse to fail')
-        } catch (e) {
-            def line = (expect =~ /@ line (\d+),/)[0][1]
-            Assertions.assertEquals("startup failed:\ntest.groovy: $line: $expect".toString(), e.message.replace('\r\n', '\n'))
-        }
-    }
-
     private static unzipScriptAndShouldFail(String entryName, List ignoreClazzList, Map<String, String> replacementsMap = [:], boolean toCheckNewParserOnly = false) {
         ignoreClazzList.addAll(TestUtils.COMMON_IGNORE_CLASS_LIST)
 
diff --git a/src/test/groovy/org/apache/groovy/parser/antlr4/TestUtils.groovy b/src/test/groovy/org/apache/groovy/parser/antlr4/TestUtils.groovy
index 8056ffb57c..0ac30380f8 100644
--- a/src/test/groovy/org/apache/groovy/parser/antlr4/TestUtils.groovy
+++ b/src/test/groovy/org/apache/groovy/parser/antlr4/TestUtils.groovy
@@ -41,11 +41,14 @@ package org.apache.groovy.parser.antlr4
     import org.codehaus.groovy.ast.stmt.ReturnStatement
     import org.codehaus.groovy.ast.stmt.ThrowStatement
     import org.codehaus.groovy.ast.stmt.WhileStatement
+    import org.codehaus.groovy.control.CompilationUnit
     import org.codehaus.groovy.control.CompilerConfiguration
     import org.codehaus.groovy.control.ParserPlugin
     import org.codehaus.groovy.control.ParserPluginFactory
+    import org.codehaus.groovy.control.Phases
     import org.codehaus.groovy.control.SourceUnit
     import org.codehaus.groovy.syntax.Token
+    import org.junit.jupiter.api.Assertions
 
     import java.util.logging.Level
     import java.util.zip.ZipEntry
@@ -109,6 +112,27 @@ final class TestUtils {
 //        }
     }
 
+    /**
+     * Compile {@code source} through CONVERSION and assert the full
+     * {@code startup failed:} diagnostic matches {@code expect} (which must
+     * contain {@code @ line N,}). Shared by {@code SyntaxErrorTest} and
+     * {@code CommonSyntaxErrorTest}.
+     */
+    @CompileDynamic
+    static void expectParseError(String source, String expect) {
+        try {
+            new CompilationUnit().with {
+                addSource('test.groovy', source)
+                compile(Phases.CONVERSION)
+                getAST()
+            }
+            Assertions.fail('expected parse to fail')
+        } catch (e) {
+            def line = (expect =~ /@ line (\d+),/)[0][1]
+            Assertions.assertEquals("startup failed:\ntest.groovy: $line: $expect".toString(), e.message.replace('\r\n', '\n'))
+        }
+    }
+
     /*
     static void unzipAndTest(String path, String entryName) {
         unzipAndTest(path, entryName, ASTComparatorCategory.DEFAULT_CONFIGURATION)
diff --git a/src/test/java/org/apache/groovy/parser/antlr4/AbstractLexerTest.java b/src/test/java/org/apache/groovy/parser/antlr4/AbstractLexerTest.java
new file mode 100644
index 0000000000..9edfdc3578
--- /dev/null
+++ b/src/test/java/org/apache/groovy/parser/antlr4/AbstractLexerTest.java
@@ -0,0 +1,211 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.groovy.parser.antlr4;
+
+import org.antlr.v4.runtime.CharStreams;
+import org.antlr.v4.runtime.Token;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Branch coverage for {@link AbstractLexer} unexpected-character diagnostics
+ * and {@link AbstractLexer#getCharErrorDisplay(int)}. End-to-end messages live
+ * in {@code CommonSyntaxErrorTest}.
+ */
+final class AbstractLexerTest {
+
+    @Test
+    void unexpectedCharacterMessageNullOrEmpty() {
+        assertEquals("Unexpected character", AbstractLexer.unexpectedCharacterMessage(null));
+        assertEquals("Unexpected character", AbstractLexer.unexpectedCharacterMessage(""));
+    }
+
+    @Test
+    void unexpectedQuoteIsUnclosedString() {
+        assertEquals("Unclosed string literal", AbstractLexer.unexpectedCharacterMessage("'"));
+        assertEquals("Unclosed string literal", AbstractLexer.unexpectedCharacterMessage("\""));
+        assertEquals("Unclosed string literal", AbstractLexer.unexpectedCharacterMessage("'''"));
+    }
+
+    @Test
+    void unexpectedPrintableStaysAsGlyph() {
+        assertEquals("Unexpected character: '`'", AbstractLexer.unexpectedCharacterMessage("`"));
+        assertEquals("Unexpected character: '#'", AbstractLexer.unexpectedCharacterMessage("#"));
+        assertEquals("Unexpected character: '😀'", AbstractLexer.unexpectedCharacterMessage("😀"));
+    }
+
+    @Test
+    void getCharErrorDisplayNamedEscapes() {
+        GroovyLangLexer lexer = displayLexer();
+        assertEquals("'\\b'", lexer.getCharErrorDisplay('\b'));
+        assertEquals("'\\t'", lexer.getCharErrorDisplay('\t'));
+        assertEquals("'\\n'", lexer.getCharErrorDisplay('\n'));
+        assertEquals("'\\f'", lexer.getCharErrorDisplay('\f'));
+        assertEquals("'\\r'", lexer.getCharErrorDisplay('\r'));
+        assertEquals("'\\''", lexer.getCharErrorDisplay('\''));
+        assertEquals("'\\\\'", lexer.getCharErrorDisplay('\\'));
+        assertEquals("'<EOF>'", lexer.getCharErrorDisplay(Token.EOF));
+    }
+
+    @Test
+    void getCharErrorDisplayUnicodeEscapesForInvisible() {
+        GroovyLangLexer lexer = displayLexer();
+        assertEquals("'\\u0000'", lexer.getCharErrorDisplay(0));
+        assertEquals("'\\u007f'", lexer.getCharErrorDisplay(0x7F));
+        assertEquals("'\\u200b'", lexer.getCharErrorDisplay(0x200B));
+        assertEquals("'\\ufeff'", lexer.getCharErrorDisplay(0xFEFF));
+        assertEquals("'\\u2028'", lexer.getCharErrorDisplay(0x2028));
+        assertEquals("'\\u2029'", lexer.getCharErrorDisplay(0x2029));
+        assertEquals("'\\ud800'", lexer.getCharErrorDisplay(0xD800));
+        assertEquals("'\\ue000'", lexer.getCharErrorDisplay(0xE000));
+        assertEquals("'\\u0378'", lexer.getCharErrorDisplay(0x0378));
+        assertEquals("'\\u00ad'", lexer.getCharErrorDisplay(0x00AD));
+    }
+
+    @Test
+    void getCharErrorDisplaySupplementaryPrivateUseAsUtf16Escapes() {
+        assertEquals("'\\udb80\\udc00'", displayLexer().getCharErrorDisplay(0xF0000));
+    }
+
+    @Test
+    void getCharErrorDisplayPrintableGlyphs() {
+        GroovyLangLexer lexer = displayLexer();
+        assertEquals("'A'", lexer.getCharErrorDisplay('A'));
+        assertEquals("'`'", lexer.getCharErrorDisplay('`'));
+        assertEquals("'😀'", lexer.getCharErrorDisplay("😀".codePointAt(0)));
+    }
+
+    @Test
+    void errorIgnoredUnexpectedCharacterTokenizesWithoutThrowing() {
+        GroovyLangLexer lexer = new GroovyLangLexer(CharStreams.fromString("`"));
+        lexer.setErrorIgnored(true);
+        Token t = lexer.nextToken();
+        assertTrue(t.getType() > 0);
+        assertEquals(Token.EOF, lexer.nextToken().getType());
+    }
+
+    @Test
+    void lexerThrowsGroovySyntaxErrorForUnexpectedCharacter() {
+        GroovyLangLexer lexer = new GroovyLangLexer(CharStreams.fromString("`"));
+        GroovySyntaxError err = assertThrows(GroovySyntaxError.class, lexer::nextToken);
+        assertEquals("Unexpected character: '`'", err.getMessage());
+        assertEquals(GroovySyntaxError.LEXER, err.getSource());
+    }
+
+    @Test
+    void lexerThrowsUnclosedStringForLoneQuote() {
+        GroovyLangLexer lexer = new GroovyLangLexer(CharStreams.fromString("'hello"));
+        GroovySyntaxError err = assertThrows(GroovySyntaxError.class, () -> drain(lexer));
+        assertEquals("Unclosed string literal", err.getMessage());
+    }
+
+    @Test
+    void requireUnclosedCommentPointsAtOpener() {
+        GroovyLangLexer lexer = new GroovyLangLexer(CharStreams.fromString("/* comment"));
+        GroovySyntaxError err = assertThrows(GroovySyntaxError.class, () -> drain(lexer));
+        assertEquals("Unclosed comment", err.getMessage());
+        assertEquals(1, err.getLine());
+        assertEquals(1, err.getColumn());
+    }
+
+    @Test
+    void errorIgnoredUnclosedCommentTokenizesWithoutThrowing() {
+        GroovyLangLexer lexer = new GroovyLangLexer(CharStreams.fromString("/* comment"));
+        lexer.setErrorIgnored(true);
+        drain(lexer);
+    }
+
+    @Test
+    void requireUnclosedCommentPointsAtIndentedOpener() {
+        GroovyLangLexer lexer = new GroovyLangLexer(CharStreams.fromString("    /* comment"));
+        GroovySyntaxError err = assertThrows(GroovySyntaxError.class, () -> drain(lexer));
+        assertEquals("Unclosed comment", err.getMessage());
+        assertEquals(1, err.getLine());
+        assertEquals(5, err.getColumn());
+    }
+
+    @Test
+    void closedBlockCommentDoesNotConsumeTrailingSource() {
+        List<Token> tokens = collect("/* ok */\ndef x = 1\n");
+        assertEquals("/* ok */", tokens.get(0).getText());
+        assertTrue(texts(tokens).contains("def"), texts(tokens).toString());
+        assertTrue(texts(tokens).contains("x"), texts(tokens).toString());
+        assertEquals(Token.EOF, tokens.get(tokens.size() - 1).getType());
+    }
+
+    @Test
+    void closedBlockCommentStopsAtFirstCloser() {
+        List<Token> tokens = collect("/* a /* nested */ def x = 1\n");
+        assertEquals("/* a /* nested */", tokens.get(0).getText());
+        assertTrue(texts(tokens).contains("def"), texts(tokens).toString());
+        assertFalse(texts(tokens).get(0).contains("def"), tokens.get(0).getText());
+    }
+
+    @Test
+    void emptyAndGroovydocBlockCommentsLeaveFollowingSource() {
+        List<Token> tokens = collect("/**/\n/** groovydoc */\ndef y = 2\n");
+        assertEquals("/**/", tokens.get(0).getText());
+        assertTrue(texts(tokens).contains("def"), texts(tokens).toString());
+        assertTrue(texts(tokens).contains("y"), texts(tokens).toString());
+    }
+
+    @Test
+    void closedBlockCommentAtEofDoesNotThrow() {
+        List<Token> tokens = collect("/* ok */");
+        assertEquals("/* ok */", tokens.get(0).getText());
+        assertEquals(Token.EOF, tokens.get(tokens.size() - 1).getType());
+    }
+
+    private static GroovyLangLexer displayLexer() {
+        return new GroovyLangLexer(CharStreams.fromString("x"));
+    }
+
+    private static void drain(GroovyLangLexer lexer) {
+        collect(lexer);
+    }
+
+    private static List<Token> collect(final String src) {
+        return collect(new GroovyLangLexer(CharStreams.fromString(src)));
+    }
+
+    private static List<Token> collect(final GroovyLangLexer lexer) {
+        List<Token> tokens = new ArrayList<>();
+        Token t;
+        do {
+            t = lexer.nextToken();
+            tokens.add(t);
+        } while (t.getType() != Token.EOF);
+        return tokens;
+    }
+
+    private static List<String> texts(final List<Token> tokens) {
+        List<String> texts = new ArrayList<>(tokens.size());
+        for (Token t : tokens) {
+            texts.add(t.getText());
+        }
+        return texts;
+    }
+}
diff --git a/src/test/java/org/apache/groovy/parser/antlr4/internal/ErrorStrategyTest.java b/src/test/java/org/apache/groovy/parser/antlr4/internal/ErrorStrategyTest.java
index eb3cb94763..cd9d6381c5 100644
--- a/src/test/java/org/apache/groovy/parser/antlr4/internal/ErrorStrategyTest.java
+++ b/src/test/java/org/apache/groovy/parser/antlr4/internal/ErrorStrategyTest.java
@@ -35,6 +35,7 @@ import org.antlr.v4.runtime.atn.AbstractPredicateTransition;
 import org.antlr.v4.runtime.atn.ATN;
 import org.antlr.v4.runtime.atn.ATNState;
 import org.antlr.v4.runtime.atn.PredictionMode;
+import org.antlr.v4.runtime.misc.IntervalSet;
 import org.antlr.v4.runtime.misc.ParseCancellationException;
 import org.apache.groovy.parser.antlr4.GroovyLangLexer;
 import org.apache.groovy.parser.antlr4.GroovyLangParser;
@@ -48,6 +49,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertSame;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -121,8 +123,7 @@ final class ErrorStrategyTest {
                 () -> strategy.recover(parser, nvae));
         assertInstanceOf(NoViableAltException.class, pce.getCause());
         assertFalse(messages.isEmpty(), "LL recover must report before cancel");
-        assertTrue(messages.stream().anyMatch(m ->
-                        m.contains("Unexpected input") || m.startsWith("Missing ")),
+        assertTrue(messages.stream().anyMatch(ErrorStrategyTest::isNonAntlrJargon),
                 "friendly diagnostic expected, got: " + messages);
     }
 
@@ -140,8 +141,7 @@ final class ErrorStrategyTest {
                 () -> strategy.recover(parser, cause));
         assertInstanceOf(InputMismatchException.class, pce.getCause());
         assertFalse(messages.isEmpty(), "LL IME recover must report before cancel: " + messages);
-        assertTrue(messages.stream().anyMatch(m ->
-                        m.contains("Unexpected input") || m.startsWith("Missing ")),
+        assertTrue(messages.stream().anyMatch(ErrorStrategyTest::isNonAntlrJargon),
                 "friendly diagnostic expected, got: " + messages);
     }
 
@@ -323,8 +323,42 @@ final class ErrorStrategyTest {
         strategy.exposeReportInputMismatch(parser, ime);
 
         assertFalse(messages.isEmpty(), "fallback report must still notify: " + messages);
-        assertTrue(messages.stream().anyMatch(m -> m.contains("Unexpected input")),
-                "generic fallback expected, got: " + messages);
+        assertTrue(messages.stream().anyMatch(ErrorStrategyTest::isNonAntlrJargon),
+                "fallback report must still notify with a diagnostic, got: " + messages);
+    }
+
+    @Test
+    void reportFriendlyErrorDoesNotRedispatchWhenListenerThrows() {
+        // Dispatch is outside the defensive catch: a listener IAE must
+        // propagate, not be treated as a locate/refine failure and retried.
+        var charStream = CharStreams.fromString("x");
+        var strategy = new StrategyProbe(charStream);
+        var messages = new ArrayList<String>();
+        var tokens = new CommonTokenStream(new GroovyLangLexer(charStream));
+        tokens.fill();
+        var parser = new GroovyLangParser(tokens);
+        parser.setErrorHandler(strategy);
+        parser.removeErrorListeners();
+        parser.addErrorListener(new BaseErrorListener() {
+            private int calls;
+
+            @Override
+            public <T extends Token> void syntaxError(Recognizer<T, ?> recognizer, T offendingSymbol, int line,
+                                                      int charPositionInLine, String msg, RecognitionException e) {
+                calls++;
+                messages.add(msg);
+                if (calls == 1) {
+                    throw new IllegalArgumentException("listener");
+                }
+            }
+        });
+
+        Token tok = tokens.get(0);
+        var nvae = new NoViableAltException(parser, tokens, tok, tok, null, parser.getContext());
+        IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class,
+                () -> strategy.exposeReportNoViable(parser, nvae));
+        assertEquals("listener", thrown.getMessage());
+        assertEquals(1, messages.size(), "listener must not be invoked a second time, got: " + messages);
     }
 
     //--------------------------------------------------------------------------
@@ -362,6 +396,104 @@ final class ErrorStrategyTest {
         assertTrue(parser.getInputStream().index() >= indexBefore);
     }
 
+    /**
+     * Strategy reporting must not leak ANTLR's stock jargon onto the listener.
+     * The exact sentence is locked by {@code CommonSyntaxErrorTest} / delimiter tests.
+     */
+    private static boolean isNonAntlrJargon(final String m) {
+        return !m.contains("no viable alternative") && !m.startsWith("mismatched input");
+    }
+
+    @Test
+    void refineFallbackPrefersKeywordOverSoleExpected() {
+        Token elseTok = token(GroovyParser.ELSE, "else");
+        RecognitionException e = stubException(setOf(GroovyParser.LPAREN), elseTok);
+        assertEquals("'else' without 'if'",
+                AbstractFriendlyErrorStrategy.refineFallbackMessage(e, "Unexpected input: 'else'"));
+    }
+
+    @Test
+    void refineFallbackNamesSoleExpectedPunctuation() {
+        Token trueTok = token(GroovyParser.BooleanLiteral, "true");
+        RecognitionException e = stubException(setOf(GroovyParser.LPAREN), trueTok);
+        assertEquals("Missing '('",
+                AbstractFriendlyErrorStrategy.refineFallbackMessage(e, "Unexpected input: 'true'"));
+        assertEquals("Missing ':'", AbstractFriendlyErrorStrategy.soleExpectedMessage(GroovyParser.COLON));
+        assertEquals("Missing '>'", AbstractFriendlyErrorStrategy.soleExpectedMessage(GroovyParser.GT));
+        assertEquals("Missing 'while'", AbstractFriendlyErrorStrategy.soleExpectedMessage(GroovyParser.WHILE));
+        assertEquals("Missing '['", AbstractFriendlyErrorStrategy.soleExpectedMessage(GroovyParser.LBRACK));
+        assertEquals("Missing '{'", AbstractFriendlyErrorStrategy.soleExpectedMessage(GroovyParser.LBRACE));
+        assertEquals("Missing ';'", AbstractFriendlyErrorStrategy.soleExpectedMessage(GroovyParser.SEMI));
+        assertNull(AbstractFriendlyErrorStrategy.soleExpectedMessage(GroovyParser.RPAREN));
+        assertNull(AbstractFriendlyErrorStrategy.soleExpectedMessage(GroovyParser.Identifier));
+    }
+
+    @Test
+    void refineFallbackUnexpectedEof() {
+        Token eof = token(Token.EOF, "<EOF>");
+        RecognitionException e = stubException(new IntervalSet(), eof);
+        assertEquals("Unexpected end of input",
+                AbstractFriendlyErrorStrategy.refineFallbackMessage(e, "Unexpected input: '<EOF>'"));
+    }
+
+    @Test
+    void refineFallbackEofWithSoleColonPrefersMissingColon() {
+        Token eof = token(Token.EOF, "<EOF>");
+        RecognitionException e = stubException(setOf(GroovyParser.COLON), eof);
+        assertEquals("Missing ':'",
+                AbstractFriendlyErrorStrategy.refineFallbackMessage(e, "Unexpected input: '<EOF>'"));
+    }
+
+    @Test
+    void refineFallbackNullExceptionKeepsGeneric() {
+        assertEquals("generic", AbstractFriendlyErrorStrategy.refineFallbackMessage(null, "generic"));
+        assertNull(AbstractFriendlyErrorStrategy.soleExpectedMessage((RecognitionException) null));
+    }
+
+    @Test
+    void refineFallbackSwallowsInvalidExpectedTokensState() {
+        RecognitionException e = new RecognitionException(null, null, null) {
+            @Override
+            public IntervalSet getExpectedTokens() {
+                throw new IllegalArgumentException("Invalid state number.");
+            }
+
+            @Override
+            public Token getOffendingToken() {
+                return token(GroovyParser.Identifier, "x");
+            }
+        };
+        assertNull(AbstractFriendlyErrorStrategy.soleExpectedMessage(e));
+        assertEquals("generic", AbstractFriendlyErrorStrategy.refineFallbackMessage(e, "generic"));
+    }
+
+    @Test
+    void refineFallbackIgnoresMultiTokenExpectedSet() {
+        IntervalSet multi = setOf(GroovyParser.LPAREN, GroovyParser.COLON);
+        Token x = token(GroovyParser.Identifier, "x");
+        RecognitionException e = stubException(multi, x);
+        assertEquals("Unexpected input: 'x'",
+                AbstractFriendlyErrorStrategy.refineFallbackMessage(e, "Unexpected input: 'x'"));
+        assertNull(AbstractFriendlyErrorStrategy.soleExpectedMessage(stubException(null, x)));
+    }
+
+    @Test
+    void keywordMessages() {
+        assertEquals("'const' is not supported; use 'val' or 'static final' instead",
+                AbstractFriendlyErrorStrategy.keywordMessage(GroovyParser.CONST));
+        assertEquals("'goto' is not supported",
+                AbstractFriendlyErrorStrategy.keywordMessage(GroovyParser.GOTO));
+        assertEquals("'else' without 'if'",
+                AbstractFriendlyErrorStrategy.keywordMessage(GroovyParser.ELSE));
+        assertEquals("'catch' without 'try'",
+                AbstractFriendlyErrorStrategy.keywordMessage(GroovyParser.CATCH));
+        assertEquals("'finally' without 'try'",
+                AbstractFriendlyErrorStrategy.keywordMessage(GroovyParser.FINALLY));
+        assertEquals("'case' outside of switch",
+                AbstractFriendlyErrorStrategy.keywordMessage(GroovyParser.CASE));
+        assertNull(AbstractFriendlyErrorStrategy.keywordMessage(GroovyParser.Identifier));
+    }
+
     // --- helpers ----------------------------------------------------------------
 
     private static GroovyLangParser parser(org.antlr.v4.runtime.CharStream charStream,
@@ -436,6 +568,35 @@ final class ErrorStrategyTest {
         }
     }
 
+    private static CommonToken token(int type, String text) {
+        CommonToken t = new CommonToken(type, text);
+        t.setLine(1);
+        t.setCharPositionInLine(0);
+        return t;
+    }
+
+    private static IntervalSet setOf(int... types) {
+        IntervalSet set = new IntervalSet();
+        for (int type : types) {
+            set.add(type);
+        }
+        return set;
+    }
+
+    private static RecognitionException stubException(IntervalSet expected, Token offending) {
+        return new RecognitionException(null, null, null) {
+            @Override
+            public IntervalSet getExpectedTokens() {
+                return expected;
+            }
+
+            @Override
+            public Token getOffendingToken() {
+                return offending;
+            }
+        };
+    }
+
     /**
      * Parser whose {@link #getInputStream()} is null so NVAE messaging hits the
      * {@code <unknown input>} branch when the strategy reads the stream from the parser.