daniellansun opened a new pull request, #3370:
URL: https://github.com/apache/groovy/pull/3370

   https://issues.apache.org/jira/browse/GROOVY-12842
   
   
   <!--
     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.
   -->
   
   # Systematic Performance Optimization and Empirical Verification of the 
Apache Groovy ANTLR4 Front-End
   
   **Date:** November 28, 2026
   **Target System:** Apache Groovy Compiler Front-End (Lexer, Parser, AST 
Construction, Groovydoc, and Literal Processing)
   **Working Branch:** `tweak-parser-20261128`
   **Baseline Commit:** `494d161` (`upstream/master` & `origin/master`, 
`GROOVY-3351`)
   **ANTLR4 Runtime:** `me.sunlan:antlr4-runtime:4.13.2.20` 
([`daniellansun/antlr4`](https://github.com/daniellansun/antlr4), `opt` branch)
   
   ---
   
   ## Abstract
   
   The front-end of the Apache Groovy compiler—comprising ANTLR4-based lexical 
analysis, adaptive LL(\*) syntax analysis, Concrete Syntax Tree (CST) to 
Abstract Syntax Tree (AST) lowering, Groovydoc extraction, and literal 
decoding—constitutes a primary latency and allocation bottleneck during 
compilation, interactive tooling, and language-server analysis. This paper 
presents a systematic, three-iteration optimization study of the Groovy ANTLR4 
front-end engineered to preserve strict syntactic, structural, stylistic, and 
binary compatibility. Grounded in deterministic profiling (Java Flight 
Recorder, ANTLR4 `ParseInfo`, and post-warmup lexer DFA miss instrumentation), 
we introduce: (i) pure-DFA factoring of high-frequency lexical constructs 
alongside compact primitive bit-state tracking backed by lazy `BitSet` 
overflow, reducing post-warmup lexer DFA misses by **96.2%** (`8,830` to 
`333`); (ii) context-guarded SLL named-argument disambiguation and 
binary-compatible `enumClassBody
 ` rule splitting (`options { baseContext = classBody; }`), eliminating all 
SLL-to-LL fallbacks across the evaluation corpus (**54.38×** speedup and 
**-94.0%** heap allocation on DSL command chains) while cutting cold-start DFA 
construction latency by **47.2%** (**1.90×** speedup, `-1,141` DFA states); and 
(iii) direct-parameter AST lowering with flat single-pass member dispatch, 
declarative Stream-preserving cardinality fast paths, $O(1)$ local backward 
Groovydoc scanning, Stream-idiomatic linear-time modifier validation, 
standalone-`\r` (bare CR) parity with ANTLR4's lexer newline semantics, and 
JDK-backed allocation-free literal scanners, accelerating full real-world 
`CONVERSION` compilation by **1.28×** (**-40.4%** heap allocation) and fully 
warmed Groovydoc-enabled compilation by **1.80×** (**-65.4%** heap allocation). 
Furthermore, we document an empirical HotSpot C2 JIT case study characterizing 
two bytecode-size and constant-folding laws governing `CodePointLexerRunner` re
 gister allocation (and a corroborating `FreqInlineSize` boundary in 
`AstBuilder.visitMethodDeclaration`). All modifications achieve bit-for-bit 
token-stream and AST structural identity (`183,983` tokens), **99.72%** JaCoCo 
diff-line coverage (**100.0%** of reachable modified lines across 10 
hand-written Java files; **97.28%** diff-branch coverage), zero `lintGate` 
violations, zero `japicmp` public/protected API regressions, and **2,652** 
passing core and subproject tests.
   
   ---
   
   ## 1. Introduction and Motivation
   
   Modern JVM languages rely on fast, low-allocation compiler front-ends not 
only for batch builds, but increasingly for latency-sensitive developer 
workflows such as Language Server Protocol (`groovy-lsp`) diagnostics, 
interactive REPL sessions (`groovy-groovysh`), and dynamic script evaluation. 
Apache Groovy's front-end ("Parrot") builds upon a heavily optimized fork of 
ANTLR4 (`me.sunlan:antlr4-runtime:4.13.2.20`, 
[`daniellansun/antlr4`](https://github.com/daniellansun/antlr4)) featuring 
specialized 8-bit/16-bit code-point DFA runners (`CodePointLexerRunner`), fast 
predicate edge tables (`LexerPredEdgeTable`), warm SLL DFA execution 
(`execDFASllWarm`), and bare-CR (`\r`) line tracking in 
`LexerATNSimulator.consume`.
   
   Despite these runtime advances, profiling the Groovy front-end reveals that 
grammar-level predicate placements, SLL ambiguities in Groovy's 
optional-parentheses DSL syntax, redundant parser DFA state duplication, and 
allocation-heavy AST lowering routines prevent the front-end from saturating 
the underlying ANTLR4 fast paths. Optimizing a mature language grammar and 
compiler front-end poses stringent engineering constraints:
   
   1. **Semantic and Structural Fidelity:** Every valid and invalid Groovy 
source file—including `\n`, `\r\n`, and standalone `\r` line terminators—must 
yield identical token streams, accurate source positions, AST shapes, and 
diagnostic behavior without duplicating work already handled in the ANTLR4 
runtime.
   2. **Binary and Visitor Compatibility:** Public and protected signatures on 
`GroovyLexer`, `GroovyParser`, generated `*Context` classes, `AstBuilder`, 
`GroovydocManager`, `SemanticPredicates`, `StringUtils`, 
`PositionConfigureUtils`, and `Numbers` form a stable API surface audited by 
`japicmp`.
   3. **JIT Stability and Maintainability:** Micro-optimizations must cooperate 
with HotSpot C2's inlining heuristics without introducing bimodal latency 
regressions, excessive nesting, redundant wheel reinvention, or untestable dead 
code, while respecting Groovy's established declarative Stream API style.
   
   ### Summary of Headline Results
   
   Across a 22-file evaluation suite (`1.59 MB`, `183,983` tokens) and 400 
independent small scripts evaluated on OpenJDK 21, the final polished 
implementation achieves improvements across all 26 workloads relative to the 
`494d161` baseline (**R0**):
   
   - **Lexical Analysis:** Real-world lexing improves **1.17×** (`23.52 → 20.17 
ms`, `54.49 → 63.54 MB/s`; full corpus **1.18×**, `30.95 → 26.21 ms`); 
multi-line and interpolated GString lexing accelerates **2.11×** (`3.09 → 1.47 
ms`); post-warmup lexer DFA misses drop **96.2%** (`8,830 → 333`).
   - **Syntax Analysis:** Real-world SLL parsing improves **1.09×** (`52.94 → 
48.74 ms`; lex+parse **1.10×**, `79.92 → 72.49 ms`); full-corpus parsing 
improves **5.30×** (`375.17 → 70.81 ms`, **-63.3%** allocation) with **54.38×** 
speedup on DSL named-argument chains (`304.54 → 5.60 ms`, **-94.0%** 
allocation) and zero SLL→LL fallbacks.
   - **Cold-Start DFA Construction:** First-parse latency on a fresh ATN/DFA 
drops **1.90×** (`3,781.11 → 1,994.79 ms`) with **1,141 fewer DFA states** 
(`23,505 → 22,364`).
   - **AST Lowering & Groovydoc:** Real-world `CONVERSION` accelerates 
**1.28×** (`234.05 → 182.90 ms`, best fork `170.71 ms`, **-40.4%** allocation); 
fully warmed Groovydoc-enabled `CONVERSION` accelerates **1.80×** (`289.94 → 
161.03 ms`, best fork `154.81 ms`, **-65.4%** allocation); full-corpus AST 
construction accelerates **2.76×** (`602.07 → 218.28 ms`, best fork `209.75 
ms`, **-58.4%** allocation); 400-script batch compilation improves **1.16×** 
(`24.34 → 21.00 ms`) with **-44.8%** allocation.
   
   ---
   
   ## 2. Experimental Methodology and Evaluation Corpus
   
   ### 2.1 Execution Environment
   
   All measurements were conducted on a dedicated Linux virtual machine with 
Gradle daemons explicitly stopped (`./gradlew --stop`) prior to benchmark 
execution to prevent background CPU contention (**Table 1**).
   
   **Table 1:** Hardware, operating system, and JVM execution environment.
   
   | Parameter | Specification |
   |---|---|
   | **Processor** | 2 × Intel Xeon CPU @ 2.30 GHz (2 physical cores, 1 
thread/core, 2 vCPU) |
   | **Operating System** | Linux `6.18.57` x86\_64 (Ubuntu 24.04) |
   | **JVM** | OpenJDK 64-Bit Server VM `21.0.13.0.3` (mixed mode, sharing) |
   | **JVM Flags** | `-Xms1g -Xmx2g` (default G1GC, single C2 compiler thread 
on 2 vCPU) |
   | **Allocation Counter** | 
`com.sun.management.ThreadMXBean.getThreadAllocatedBytes(long)` |
   | **Profiling Tooling** | JDK Flight Recorder (`jfr`), ANTLR4 `ParseInfo`, 
`-XX:+PrintCompilation`, custom `DiagnoseLexerMisses` |
   
   ### 2.2 Stratified Evaluation Corpus
   
   To capture both realistic developer codebases and adversarial grammatical 
edge cases, we assembled a four-tier corpus totaling **22 files (1.59 MB, 
183,983 tokens)** plus a 400-script micro-compilation benchmark (**Table 2**).
   
   **Table 2:** Stratified benchmark corpus and workload composition.
   
   | Tier | Workload Group | Files | Size (Bytes / KiB) | Lines | 
Representative Characteristics |
   |---|---|---:|---:|---:|---|
   | **A** | `A_pleac` | 8 | 400,381 (391.0 KiB) | 11,201 | Idiomatic Groovy 
scripts (`pleac01`–`pleac20`), closures, regexes, literals |
   | **B** | `B_prod` | 4 | 306,433 (299.3 KiB) | 7,442 | Large production 
classes (`Console`, `GinqAstWalker`, `AstNodeToScriptAdapter`, 
`GroovyCommands`) |
   | **C** | `C_modern` | 5 | 575,137 (561.7 KiB) | 17,325 | Modern Groovy 
4/5/6 syntax (`SwitchPatternMatchingTest`, `AsyncAwaitTest`, `AnnotationTest`, 
`LambdaTest`, `MethodReferenceTest`) |
   | **—** | *Real-World Subtotal (A+B+C)* | *17* | *1,281,951 (1,251.9 KiB)* | 
*35,968* | *Primary realistic compilation workload* |
   | **D1–D5** | `D_stress` | 5 | ~310,000 (~303 KiB) | — | Synthetic stress 
tests: `D1_ident_ops`, `D2_gstrings`, `D3_comments_nl`, `D4_slashy_div`, 
`D5_dsl_chains` |
   | **D6** | `D6_SmallScripts_400` | 400 | ~24 KiB | — | Independent 
single-expression/script compilations isolating per-compilation fixed overhead |
   | **Cold** | `ColdDFA_Parse_RealWorld` | 17 | 1,281,951 (1,251.9 KiB) | 
35,968 | 3 fresh ATN/DFA instantiations per JVM measuring cold-start DFA 
construction and state count |
   
   ### 2.3 Correctness Equivalence Contract
   
   Prior to timing any candidate revision, a deterministic verification pass 
(`ParserBenchmark . verify`) hashes every emitted token (type, channel, line, 
column, text) and traverses the constructed `ModuleNode` AST across all 22 
corpus files. Every single iteration from **R0** through **Final** matched the 
exact golden digests:
   
   ```text
   VERIFY_OK tokens=183983
   tokSha256=244c2bee9689543b22e2c1b909f40add782877bd207a461bc15f481b31fdbf60
   astSha256=963ec81241d1f0704c1e1586e396dcc57c73a72c625a8758ea22283a840af46a
   ```
   
   ---
   
   ## 3. Architectural Diagnosis and Optimization Design
   
   Prior to code modification, we conducted a three-stage architectural 
analysis spanning ANTLR4 runtime mechanics, Groovy compiler semantics, HotSpot 
JIT behavior, LL(\*)/SLL parsing theory, data-structure allocation profiles, 
and static maintainability constraints:
   
   1. **Stage I — Empirical Bottleneck Identification:**
      - *Lexer:* Post-warmup `DiagnoseLexerMisses` recorded **8,830** DFA 
misses on the 22-file corpus, dominated by `SingleLineComment` (`//`), 
`MultiLineComment` (`/**`), triple-single-quoted strings (`'''`), the `val` 
keyword predicate, and character-by-character GString modes. Per-token state 
updates relied on `BitSet` allocations and multi-branch token checks.
      - *Parser:* `ParseInfo` profiling exposed a severe SLL→LL fallback on 
`D5_dsl_chains` (`4,800` decision-level LL fallbacks and `1,000` ambiguities in 
Top-8 rules), inflating single-file parse latency to `304.54 ms`. Meanwhile, `{ 
$t == 2 }? enumConstants` inside `classBody[int t]` leaked predicate-gated 
lookahead into non-enum declarations, inflating DFA state count to `23,505`.
      - *AST & Support Pipeline:* JFR sampling revealed heavy allocation 
pressure from `NodeMetaData` (`ListHashMap`) cross-visitor parameter passing, 
single-element Java `Stream` pipeline instantiations and `LinkedList` 
reductions in `AstBuilder`, regex-based escape rewriting in `StringUtils`, 
`BigInteger` allocations in `Numbers.parseInteger`, and an $O(N^2)$ forward 
sibling scan plus regex whitespace matching in `GroovydocManager` (`263.26 MB` 
allocated per pass).
   2. **Stage II — Compatibility Invariants and Trade-Off Resolution:**
      - Grammar restructurings that alter generated `*Context` class 
hierarchies or visitor contracts were ruled out. Instead, `enumClassBody` uses 
ANTLR4's `options { baseContext = classBody; }` so callers observe 
`ClassBodyContext` with `t == 2`.
      - In `AstBuilder`, all 14 public `@Override` metadata-reading visitor 
methods were preserved as thin bridges delegating to private direct-parameter 
overloads.
      - Named-argument SLL disambiguation was guarded by an explicit 
`colonSensitiveLevel` counter covering `assert`, ternary (`? :`), and 
`switch`/`case` expressions so outer colons are never misclassified as 
named-argument separators.
      - Because `daniellansun/antlr4` already counts standalone `\r` (not 
followed by `\n`) as a line terminator inside `LexerATNSimulator.consume` 
(`b0a6f85c`), Groovy avoids duplicating lexer-level newline counting and 
restricts bare-CR handling strictly to token-end measurement 
(`PositionConfigureUtils`) and backslash line-continuation stripping 
(`StringUtils`).
   3. **Stage III — Three-Iteration Execution Plan:**
      - **Iteration I (Lexer)** → **Iteration II (Parser)** → **Iteration III 
(AST, Groovydoc, Literal Utilities, and End-to-End Quality & Regression 
Remediation)**, with mandatory Golden SHA-256 verification and multi-fork 
benchmarking between rounds.
   
   ---
   
   ## 4. Iterative Implementation and Algorithmic Contributions
   
   ### 4.1 Iteration I — Lexer Pure-DFA Factoring and Allocation-Free State 
Representation
   
   Implemented in [`GroovyLexer.g4`](src/antlr/GroovyLexer.g4) and 
[`GroovyLangLexer.java`](src/main/java/org/apache/groovy/parser/antlr4/GroovyLangLexer.java):
   
   - **Pure-DFA Comment and Slashy Factoring:** Re-factored 
`SingleLineComment`, `MultiLineComment`, and `SlashyFirstCharacter` so `//`, 
`/*`, and `/**` traverse pure DFA edges in `DEFAULT_MODE` without invoking 
leading semantic predicates (`isRegexAllowed()`).
   - **Bulk String and GString Lexing:** Introduced `TdqBody`, `TsqBody`, 
`TdqNonQuote`, and `TsqNonQuote` alongside bulk GString scanning modes and 
conditional `pushMode`/`popMode`, eliminating per-character mode churn on long 
triple-quoted strings and interpolated GStrings.
   - **Deferred `VAL` Toggle in `emit()`:** Moved the 
`-Dgroovy.enable.val=false` check out of the lexer rule's semantic predicate 
into [`GroovyLexer.emit()`](src/antlr/GroovyLexer.g4), enabling pure-DFA 
matching of `val` while preserving runtime configurability (verified by 
`ValDisabledTest`).
   - **Compact Primitive State Machine:** Replaced eager `BitSet` parenthesis 
tracking with a 64-bit `long parenBits` bitmask featuring a permanent sentinel 
at bit 0 (eliminating depth-zero checks and index decrements in 
`isInsideParens()`) backed by a lazily allocated `java.util.BitSet 
parenOverflowBits` only for nesting depths exceeding 63 (avoiding custom 
array-resizing code). Replaced scattered token-class checks with a 256-entry 
`byte[] TOKEN_FLAGS` lookup table and a single-bitmask 
`FLAG_REAL_TOKEN_SPECIAL` fast path in `noteRealToken(int)` that skips 
special-token handling on 95.2% of real tokens.
   
   ### 4.2 Iteration II — Zero-Fallback SLL Parsing, Rule Splitting, and DFA 
Compaction
   
   Implemented in [`GroovyParser.g4`](src/antlr/GroovyParser.g4), 
[`SemanticPredicates.java`](src/main/java/org/apache/groovy/parser/antlr4/SemanticPredicates.java),
 
[`DescriptiveErrorStrategy.java`](src/main/java/org/apache/groovy/parser/antlr4/internal/DescriptiveErrorStrategy.java),
 and 
[`GroovyLangParser.java`](src/main/java/org/apache/groovy/parser/antlr4/GroovyLangParser.java):
   
   - **Context-Guarded Named-Argument SLL Gate:** Added `{ colonSensitiveLevel 
> 0 || !SemanticPredicates.isNamedArg(_input) }?` and 
`isNamedPropertyArg(_input)` predicates to `firstArgumentListElement` and 
`argumentListElement`, backed by a unified bounded delimiter scanner 
(`skipBalanced` / `isBalancedFollowedByColon`) and JDK 
`Character.isHighSurrogate` / `isLowSurrogate` checks. When outside 
colon-sensitive contexts (`colonSensitiveLevel == 0`), SLL immediately commits 
to `namedArg` / `namedPropertyArg` without ambiguity or LL fallback.
   - **Binary-Compatible `enumClassBody` Split:** Extracted enum bodies into 
`enumClassBody` with `options { baseContext = classBody; }` and `@init { 
_localctx.t = 2; }`. Non-enum classes, interfaces, traits, and records use a 
streamlined `classBody[int t]` devoid of `enumConstants` lookahead, eliminating 
**1,141** DFA states while preserving full `ClassBodyContext` compatibility.
   - **Streamlined Control Flow and Per-Compilation Overhead Reduction:** 
Simplified `ifElseStatement` to `sep? ELSE`; added 
`DescriptiveErrorStrategy.isSyncRequired()` so non-recovering SLL parses skip 
unnecessary error-recovery set computations; added package-private 
`GroovyLexer(CharStream, boolean)` and `GroovyParser(TokenStream, ATN)` 
constructors avoiding redundant ATN initialization overhead on small scripts.
   
   ### 4.3 Iteration III — Direct-Parameter AST Lowering, Linear-Time 
Groovydoc, and Literal Scanners
   
   Implemented across 
[`AstBuilder.java`](src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java),
 
[`GroovydocManager.java`](src/main/java/org/apache/groovy/parser/antlr4/GroovydocManager.java),
 
[`ModifierManager.java`](src/main/java/org/apache/groovy/parser/antlr4/ModifierManager.java),
 
[`StringUtils.java`](src/main/java/org/apache/groovy/parser/antlr4/util/StringUtils.java),
 
[`PositionConfigureUtils.java`](src/main/java/org/apache/groovy/parser/antlr4/util/PositionConfigureUtils.java),
 and [`Numbers.java`](src/main/java/org/codehaus/groovy/syntax/Numbers.java):
   
   - **Direct-Parameter Lowering, Flat Member Dispatch & Stream-Preserving Fast 
Paths in `AstBuilder`:** Converted 14 high-frequency visitor methods 
(`visitClassDeclaration`, `visitClassBody`, `visitEnumConstants`, 
`visitEnumConstant`, `visitClassBodyDeclaration`, `visitMemberDeclaration`, 
`visitFieldDeclaration`, `visitCompactConstructorDeclaration`, 
`visitMethodDeclaration`, `visitVariableDeclaration`, 
`visitVariableDeclarators`, `visitVariableDeclarator`, `visitCommandArgument`, 
`visitPathElement`) to pass context objects directly as parameters, retaining 
public `@Override` metadata bridges for backwards compatibility. Refactored 
`visitMemberDeclaration` into a flat single-pass `ctx.getChildCount()` / 
`ctx.getChild(i)` loop with Java 17 pattern-matching `instanceof` and early 
returns (cutting nesting from 6 levels to 2, eliminating up to 5 redundant 
`getRuleContext` scans and all `NodeMetaData` allocations across methods, 
fields, compact constructors, and nested types); flattened 
 `visitClassBodyDeclaration`, `visitMapEntry`, and `visitBuiltInType`; made 
`visitModifiersOpt` null-safe; replaced `new LinkedList<>()` with `new 
ArrayList<>(0)` and an empty guard before `forEach` in 
`visitMethodDeclaration`. Preserved `AstBuilder`'s idiomatic declarative Stream 
API / `forEach` style across multi-element transformations while introducing a 
reusable Stream-backed `mapToList` helper, Java 17 `switch` expressions for 1- 
and 2-element path chains (`createPathExpression` via `applyPathElement`) and 
qualified names (`joinQualifiedNameElements`), single-element fast paths in 
`visitEnhancedArgumentListInPar`, `visitFormalParameterList`, 
`visitBlockStatements` (streaming directly into `BlockStatement` via 
`forEach`), and `visitGstring` (`createGStringLiteral` + 
`parseGStringSegment`), type-safe `Stream.collect`/`flatMap` in switch 
visitors, and a direct `switch` in `groovyTokenType()` replacing `Types.lookup`.
   - **$O(1)$ Backward Groovydoc Scanning:** Replaced `GroovydocManager`'s 
$O(N^2)$ forward stream scan from child index `0` with a localized backward 
walk starting at `children.indexOf(node) - 1` (reusing `List.indexOf` directly) 
that terminates immediately upon encountering an earlier sibling of the same 
rule type or a doc comment. Replaced regex `\s+` matching with JDK's 
allocation-free `String.isBlank()` (`text.isEmpty() || !text.isBlank()`).
   - **Allocation-Free Escape, Number, Modifier, and Position Processing (with 
Bare-CR Support & JDK Reuse):**
     - `StringUtils`: Rewrote `replaceHexEscapes`, `replaceOctalEscapes`, 
`replaceStandardEscapes`, and `replaceLineEscape` as single-pass `charAt` 
scanners with identity return when no backslash exists; packed octal parse 
state into a 64-bit `long` (`((long) end << 8) | val`) to prevent 24-bit 
integer index overflow on multi-megabyte strings; handled standalone `\r` line 
continuations in `matchLineBreakEnd` (`'\r'? '\n' | '\r'`); reused JDK 17 
`java.util.HexFormat` (`isHexDigit` / `fromHexDigit`) and 
`Numbers.isOctalDigit`; preserved Stream style in `countChar`.
     - `Numbers`: Added an 18-digit decimal integer fast path 
(`parseSimpleDecimalInteger` + helper methods) bypassing `BigInteger` and 
substring allocation for the common case while falling back cleanly for 
underscores, non-decimal radices, `G`/`g` suffixes, and overflow diagnostics.
     - `ModifierManager`: Switched duplicate-modifier validation to an 
allocation-free linear scan for `size <= 8`, retaining `HashSet` validation for 
larger lists to guarantee $O(N)$ worst-case behavior; preserved Stream API / 
`forEach` style throughout query and mutation helpers while factoring out 
reusable `anyModifierMatches`, `checkVisibilityLimit`, and `validateDisallowed`.
     - `PositionConfigureUtils`: Computed end line/column positions in a single 
pass packed into a 64-bit `long`, treating `\n`, `\r\n`, and standalone `\r` 
identically to ANTLR4's `LexerATNSimulator.consume` (`b0a6f85c`), and 
delegating UTF-16 code-point counting directly to JDK's `String.codePointCount` 
($O(1)$ on Latin-1 compact strings).
   
   ---
   
   ## 5. Empirical Case Study: HotSpot C2 Inlining Laws for 
`CodePointLexerRunner` and `AstBuilder`
   
   During Iteration III (**R3**), we evaluated consolidating 10 grammar-level 
lexer actions into `GroovyLexer.emit()` via a bitflag dispatch helper 
(`handleEmitAction`), simultaneously shrinking the generated 
`GroovyLexer.action()` method from `531` bytes to `255` bytes. Controlled 
benchmarking immediately detected a sharp regression: `L1_Lex_All` degraded 
from **`26.31 ms` (R1) to `34.11 ms` (R3)**, accompanied by bimodal 
fork-to-fork jitter (`16.65 ms` vs `22.35 ms`).
   
   Using `CpuVsWall`, Tier-4 `-XX:+PrintCompilation` diffs, and 
`-XX:CompileCommand=dontinline` isolation experiments, we identified and 
verified **two HotSpot C2 compilation laws** governing `CodePointLexerRunner` + 
`GroovyLexer`:
   
   1. **Law #1 (Constant-Foldable `emit()`):** `GroovyLexer.emit()` must remain 
minimal (`if (!VAL_ENABLED && VAL == _type) _type = Identifier; return 
super.emit();`). Because `VAL_ENABLED` is `static final`, C2 constant-folds the 
branch away entirely under the default configuration (`VAL_ENABLED == true`). 
Introducing even a single runtime-variable test (e.g., `if (NL == _type)`) 
inside `emit()` degrades `L1_Lex_All` by `4–8 ms`.
   2. **Law #2 (Keep Cold-Heavy Dispatch Callees Above C2 `FreqInlineSize = 
325` Bytes):** Shrinking `GroovyLexer.action()` below HotSpot's 
`FreqInlineSize` threshold (`255 < 325` bytes) enables C2 to inline `action()` 
transitively into `LexerActionExecutor.execute()` → `finishToken()` → 
`CodePointLexerRunner.exec8Bit()`. Inlining the multi-way switch into 
`exec8Bit`'s tight per-byte DFA loop causes severe x86-64 register spilling and 
bimodal code layouts depending on compilation order. Keeping inline actions in 
`.g4` preserves `GroovyLexer.action()` at `531` bytes (`> 325`), keeping 
`exec8Bit()`'s register pressure minimal and deterministic.
   
   Reverting the `emit()` consolidation while retaining zero-bloat improvements 
(`parenBits` bit-0 sentinel, `FLAG_REAL_TOKEN_SPECIAL`, and a `24`-byte 
`GroovyLangLexer.nextToken()` fitting within C2 `MaxInlineSize = 35`) produced 
**R3B**, immediately restoring and surpassing all prior lexer throughput 
records (`19.80 ms` on `L1_Lex_RealWorld`, inter-fork spread `19.79–19.90 ms`).
   
   A corroborating instance of Law #2 emerged when refactoring 
`AstBuilder.visitMethodDeclaration` to accept `ClassNode` directly: removing 
redundant `getNodeMetaData` and `asBoolean` calls briefly shrank 
`visitMethodDeclaration` from `331` bytes to **`319` bytes** (`< 325`), causing 
C2 to inline the entire method-lowering body into `visitMemberDeclaration`, 
pushing `visitMemberDeclaration` over `InlineSmallCode` (`already compiled into 
a big method`), and causing bimodal tail spikes on `L4_AST_All` (`256.84 ms` vs 
`209.54 ms` under `-XX:CompileCommand=dontinline`). Replacing `new 
LinkedList<>()` with `new ArrayList<>(0)` and guarding empty 
`anonymousInnerClassList` before `forEach` both eliminated per-method 
`LinkedList` + iterator allocation and naturally restored 
`visitMethodDeclaration` to **`330` bytes** (`> 325`), recovering `161.03 ms` 
(`1.80×`) on `L4_AST_Gdoc_RealWorld`.
   
   ---
   
   ## 6. Quantitative Performance Evaluation
   
   ### 6.1 End-to-End Steady-State Progression Across All 26 Workloads
   
   ```mermaid
   xychart-beta
       title "Iterative Median Latency Across Core Front-End Stages (ms, lower 
is better)"
       x-axis ["R0 Baseline", "R1 Lexer", "R2C Parser", "R3B Fix", "Final 
Polished"]
       y-axis "Median Latency (ms)" 0 --> 620
       bar [234.05, 239.63, 235.45, 170.29, 182.90]
       bar [289.94, 289.46, 304.87, 157.67, 161.03]
       bar [602.07, 610.41, 294.18, 209.52, 218.28]
       line [79.92, 75.31, 77.61, 73.67, 72.49]
   ```
   **Figure 1:** Iterative median latency progression across core front-end 
compilation stages. *Bars from left to right per stage: `L4_AST_RealWorld`, 
`L4_AST_Gdoc_RealWorld`, and `L4_AST_All`; line series: 
`L3_LexParse_RealWorld`.*
   
   **Table 3:** Full steady-state benchmark progression across all 26 workloads 
(**R0** baseline, **R1** lexer, **R2C** parser, **R3\*** pre-fix lexer 
regression, and **Final** 3-fork steady-state median after 25 global warmup 
iterations with `AstBuilder`/`ModifierManager` Stream API style preserved, flat 
single-pass `visitMemberDeclaration`, bare-CR handling, and JDK reuse).
   
   | Workload | R0 (ms) | R1 (ms) | R2C (ms) | R3\* (ms) | **Final Med (ms)** | 
Final 3-Fork Medians (ms) | Speedup vs R0 | Throughput R0→Final (MB/s) | Heap 
Alloc R0→Final (MB) |
   |---|---:|---:|---:|---:|---:|---|---:|---:|---:|
   | `L1_Lex_RealWorld` | 23.52 | 20.23 | 20.89 | 22.82 | **20.17** | 19.59 / 
20.17 / 20.32 | **1.17×** | 54.49 → **63.54** | 7.64 → **7.23** (-5.4%) |
   | `L2_Parse_RealWorld` | 52.94 | 55.05 | 53.85 | 53.26 | **48.74** | 50.98 / 
48.74 / 48.34 | **1.09×** | 24.23 → **26.30** | 35.67 → **35.51** (-0.4%) |
   | `L3_LexParse_RealWorld` | 79.92 | 75.31 | 77.61 | 75.30 | **72.49** | 
72.09 / 72.49 / 72.78 | **1.10×** | 16.04 → **17.68** | 43.80 → **43.22** 
(-1.3%) |
   | `L4_AST_RealWorld` | 234.05 | 239.63 | 235.45 | 166.12 | **182.90** | 
183.99 / 182.90 / 170.71 | **1.28×** | 5.47 → **7.01** | 152.61 → **91.01** 
(**-40.4%**) |
   | `L4_AST_Gdoc_RealWorld` | 289.94 | 289.46 | 304.87 | 156.34 | **161.03** | 
154.81 / 161.03 / 162.94 | **1.80×** | 4.42 → **7.96** | 263.26 → **91.14** 
(**-65.4%**) |
   | `L1_Lex_All` | 30.95 | 26.31 | 27.33 | 34.11 | **26.21** | 25.63 / 26.21 / 
27.09 | **1.18×** | 51.51 → **60.83** | 10.98 → **10.41** (-5.2%) |
   | `L2_Parse_All` | 375.17 | 376.91 | 82.43 | 78.05 | **70.81** | 69.95 / 
72.24 / 70.81 | **5.30×** | 4.25 → **22.52** | 153.32 → **56.26** (**-63.3%**) |
   | `L3_LexParse_All` | 412.45 | 410.38 | 105.31 | 102.20 | **97.97** | 97.97 
/ 98.58 / 95.60 | **4.21×** | 3.87 → **16.28** | 165.02 → **67.40** 
(**-59.2%**) |
   | `L4_AST_All` | 602.07 | 610.41 | 294.18 | 206.76 | **218.28** | 220.25 / 
218.28 / 209.75 | **2.76×** | 2.65 → **7.30** | 333.65 → **138.83** 
(**-58.4%**) |
   | `D6_SmallScripts_400` | 24.34 | 25.49 | 26.52 | 22.11 | **21.00** | 22.34 
/ 21.00 / 19.65 | **1.16×** | 1.02 → **1.17** | 28.67 → **15.82** (**-44.8%**) |
   | `Lex_A_pleac` | 8.57 | 7.51 | 8.05 | 8.29 | **7.53** | 7.86 / 7.10 / 7.53 
| **1.14×** | 46.71 → **53.14** | 3.15 → **2.97** (-5.7%) |
   | `Parse_A_pleac` | 20.34 | 20.66 | 19.60 | 20.49 | **19.74** | 20.53 / 
19.74 / 19.21 | **1.03×** | 19.69 → **20.28** | 15.88 → **15.85** (-0.2%) |
   | `Lex_B_prod` | 6.98 | 5.93 | 6.20 | 6.51 | **5.83** | 5.83 / 5.92 / 5.73 | 
**1.20×** | 43.90 → **52.52** | 2.79 → **2.63** (-5.7%) |
   | `Parse_B_prod` | 20.03 | 19.31 | 21.90 | 18.80 | **18.24** | 19.51 / 17.52 
/ 18.24 | **1.10×** | 15.30 → **16.80** | 12.84 → **12.77** (-0.5%) |
   | `Lex_C_modern` | 6.85 | 5.88 | 6.40 | 7.16 | **5.79** | 6.24 / 5.68 / 5.79 
| **1.18×** | 83.97 → **99.37** | 1.70 → **1.62** (-4.7%) |
   | `Parse_C_modern` | 6.93 | 6.73 | 7.22 | 6.72 | **6.65** | 7.17 / 6.65 / 
6.41 | **1.04×** | 82.97 → **86.52** | 6.95 → **6.90** (-0.7%) |
   | `Lex_D1_ident_ops` | 1.91 | 1.69 | 1.67 | 1.83 | **1.71** | 1.91 / 1.68 / 
1.71 | **1.12×** | 27.80 → **31.06** | 0.90 → **0.83** (-7.8%) |
   | `Parse_D1_ident_ops` | 5.47 | 5.47 | 5.42 | 5.29 | **5.16** | 5.48 / 5.07 
/ 5.16 | **1.06×** | 9.70 → **10.30** | 5.84 → **5.79** (-0.9%) |
   | `Lex_D2_gstrings` | 3.09 | 1.52 | 1.59 | 1.85 | **1.47** | 1.54 / 1.47 / 
1.43 | **2.11×** | 33.33 → **70.25** | 0.54 → **0.52** (-3.7%) |
   | `Parse_D2_gstrings` | 2.29 | 2.23 | 2.21 | 2.21 | **2.17** | 2.19 / 2.17 / 
2.10 | **1.05×** | 45.22 → **47.56** | 2.47 → **2.47** (0.0%) |
   | `Lex_D3_comments_nl` | 1.25 | 1.06 | 1.17 | 1.29 | **1.05** | 1.17 / 1.05 
/ 1.03 | **1.19×** | 54.52 → **64.38** | 0.50 → **0.48** (-4.0%) |
   | `Parse_D3_comments_nl` | 1.90 | 1.95 | 1.88 | 1.83 | **1.79** | 1.90 / 
1.79 / 1.79 | **1.06×** | 35.47 → **37.83** | 2.03 → **2.00** (-1.5%) |
   | `Lex_D4_slashy_div` | 1.19 | 1.09 | 1.17 | 1.23 | **1.08** | 1.14 / 1.08 / 
1.05 | **1.10×** | 28.70 → **31.72** | 0.59 → **0.57** (-3.4%) |
   | `Parse_D4_slashy_div` | 3.95 | 3.96 | 3.83 | 3.74 | **3.71** | 3.81 / 3.71 
/ 3.70 | **1.06×** | 8.67 → **9.24** | 4.33 → **4.29** (-0.9%) |
   | `Lex_D5_dsl_chains` | 1.54 | 1.34 | 1.42 | 1.52 | **1.37** | 1.47 / 1.37 / 
1.33 | **1.13×** | 35.23 → **39.76** | 0.80 → **0.78** (-2.5%) |
   | `Parse_D5_dsl_chains` | 304.54 | 311.14 | 5.62 | 5.35 | **5.60** | 5.60 / 
5.16 / 5.61 | **54.38×** | 0.18 → **9.71** | 102.96 → **6.20** (**-94.0%**) |
   
   ### 6.2 Cold-Start DFA Construction and State-Space Compaction
   
   **Table 4:** Cold-start `ColdDFA_Parse_RealWorld` progression across 
iterations (median and minimum over 3 fresh ATN/DFA instantiations per JVM).
   
   | Iteration | Cold-Start Median (ms) | Cold-Start Min (ms) | Cold Heap Alloc 
(MB) | Total Parser DFA States | Speedup vs R0 |
   |---|---:|---:|---:|---:|---:|
   | **R0 (Baseline)** | 3,781.11 | 2,475.49 | 391.03 | 23,505 | 1.00× |
   | **R1 (Lexer)** | 2,235.17 | 2,084.08 | 393.26 | 23,505 | 1.69× |
   | **R2C (Parser)** | 2,509.71 | 1,997.93 | 381.31 | 22,364 | 1.51× |
   | **R3B (Fix)** | 2,166.43 | 2,033.08 | 381.36 | 22,364 | 1.75× |
   | **Final (Polished)** | **1,994.79** | **1,965.66** | **381.17** | **22,364 
(-1,141)** | **1.90×** |
   
   ### 6.3 Parser Decision Profile (`ParseInfo`) and Post-Warmup Lexer DFA 
Misses
   
   **Table 5:** Top parser decisions on the full 22-file corpus 
(`profile-all`), contrasting baseline SLL→LL fallback cascading against Final 
zero-fallback SLL execution.
   
   | Metric / Decision (Full 22-File Corpus) | R0 Baseline | Final Polished | 
Reduction |
   |---|---:|---:|---:|
   | Files triggering SLL → LL global fallback | 1 (`D5_dsl_chains.groovy`) | 
**0** | **-100%** |
   | Top-8 `pathExpression` time / `LL_FB` / `Amb` | 680.80 ms / 600 / 200 | 
**150.83 ms / 0 / 0** | **-77.8% time / -100% FB** |
   | Top-8 `commandArgument` time / `LL_FB` / `Amb` | 347.35 ms / 1,000 / 600 | 
*(dropped out of Top 25)* **0 / 0** | **-100% FB & Amb** |
   | Top-8 `commandExpression` time / `LL_FB` / `Amb` | 256.94 ms / 800 / 200 | 
**17.60 ms / 0 / 0** | **-93.1% time / -100% FB** |
   | Top-8 `firstArgumentListElement` time / `LL_FB` | 90.46 ms / 800 | 
*(dropped out of Top 25)* **0** | **-100% FB** |
   | Top-8 `argumentListElement` time / `LL_FB` | 43.86 ms / 400 | *(dropped 
out of Top 25)* **0** | **-100% FB** |
   | Aggregate `SLL_ATN` misses across Top 25 decisions | 0 | **0** | Pure SLL 
DFA |
   
   **Table 6:** Post-warmup `DiagnoseLexerMisses` breakdown across all 22 
corpus files.
   
   | Lexer Miss Category | R0 Post-Warmup Misses | Final Post-Warmup Misses | 
Reduction |
   |---|---:|---:|---:|
   | `SingleLineComment` (`// ...`) | 3,764+ | **0** | **-100.0%** |
   | Triple-single-quoted strings (`'''`) | 2,749 | **0** | **-100.0%** |
   | `MultiLineComment` / Groovydoc (`/*`, `/**`) | 379+ | **0** | **-100.0%** |
   | `VAL` keyword (`val`) | 186 | **0** | **-100.0%** |
   | GString identifier / path / TDQ modes | 115+ | **0** | **-100.0%** |
   | Remaining slashy regex / `!in` / `!instanceof` edge transitions | ~1,637 | 
**333** | **-79.7%** |
   | **Total Post-Warmup Lexer DFA Misses** | **8,830** | **333** | **-96.2%** |
   
   ### 6.4 Warmup Dynamics, Style–Performance Trade-Off, and Threats to Validity
   
   Three methodological considerations warrant explicit disclosure in 
accordance with rigorous JVM benchmarking practice:
   
   1. **Single-Thread C2 Queue Drain on 2-vCPU Hosts:** On a 2-vCPU VM (where 
HotSpot allocates a single C2 compiler thread), our global warmup runs 25 
lex/parse passes (`w = 0..24`) and 4 AST passes (`w = 0..3`), followed by 4 
per-benchmark warmup passes in `L4_AST_RealWorld`. Consequently, late Tier-4 
compilations in `AstBuilder` occasionally finish draining during 
`L4_AST_RealWorld` (`182.90 ms`, Fork 3 `170.71 ms`), whereas 
`L4_AST_Gdoc_RealWorld`—which runs immediately afterward over the same 17 files 
with Groovydoc additionally enabled—executes completely warm (`161.03 ms`, best 
fork `154.81 ms`, `min = 151.49 ms`).
   2. **Quantifying Stream API Preservation:** Comparing an intermediate 
imperative-loop variant of `AstBuilder` (`87.53 MB` / `160.73 ms` on 
`L4_AST_RealWorld`) against the final Stream-preserving design (`91.01 MB`, 
`-230 KB` lower than the prior Stream-preserving revision thanks to direct 
`visitClassDeclaration`/`visitMethodDeclaration`/`visitCompactConstructorDeclaration`
 dispatch and `ArrayList(0)` + empty-guard on `anonymousInnerClassList`) via 
JFR `ObjectAllocationSample` confirmed that `mapToList`, 1/2-element 
declarative `switch` fast paths, and `ModifierManager.anyModifierMatches` 
eliminated >90% of single-element Stream pipeline overhead, leaving only 
genuine multi-element Stream pipelines (`+3.48 MB`, or 3.8% of total AST 
allocation—while still delivering **-40.4%** allocation and **1.80×** fully 
warmed Groovydoc AST latency improvement over R0).
   3. **External Validity:** Absolute millisecond timings depend on CPU 
microarchitecture and core count; however, allocation reductions (`-40.4%` to 
`-94.0%`), DFA state reductions (`-1,141`), SLL→LL fallback elimination 
(`100%`), and post-warmup lexer DFA miss reductions (`-96.2%`) are 
hardware-independent algorithmic invariants that transfer directly across JVM 
platforms.
   
   ---
   
   ## 7. Static Quality Audit, Testing, and Compatibility Verification
   
   ### 7.1 Static Code Quality Audit and Refactoring
   
   Following Iteration III, all 12 modified production files underwent a 
systematic static quality audit enforcing strict cognitive-complexity, 
reusability, JDK reuse, reliability, and style standards:
   
   - **Cognitive Complexity, Flatness & Reusability:** Consolidated three 
duplicate balanced-delimiter scanning loops in 
[`SemanticPredicates.java`](src/main/java/org/apache/groovy/parser/antlr4/SemanticPredicates.java)
 into `skipBalanced` / `isBalancedFollowedByColon`, extracted 
`isDelimiterSpace(int)`, `isQualifiedCapitalizedEmptyCall`, and 
`isInvalidQualifiedLocalVariableDeclaration` (all methods ≤ 12). Decomposed 
`Numbers.parseSimpleDecimalInteger` (formerly complexity 27) into four focused 
helpers (all ≤ 9). Decomposed `StringUtils` escape scanners into 
`parseOctalEscape`, `matchLineBreakEnd`, and `ensureBuffer` (all ≤ 11). In 
[`AstBuilder.java`](src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java),
 flattened `visitMemberDeclaration` from 6 indentation levels down to 2 via 
single-pass `ctx.getChildCount()` / `ctx.getChild(i)` dispatch, flattened 
`visitClassBodyDeclaration`, `visitMapEntry`, and `visitBuiltInType`, and 
extracted `mapToList`, `applyPathElement`, `c
 reateGStringLiteral`, and `createNamedArgumentTuple` while preserving 
idiomatic Stream API pipelines across collection-mapping visitors. In 
[`ModifierManager.java`](src/main/java/org/apache/groovy/parser/antlr4/ModifierManager.java),
 restored Stream API / `forEach` style across all query and mutation methods 
and factored out `anyModifierMatches`, `checkVisibilityLimit`, and 
`validateDisallowed`.
   - **Avoiding Wheel Reinvention:** Replaced custom UTF-16 surrogate counting 
in `PositionConfigureUtils` with JDK's `String.codePointCount`; replaced custom 
hex and octal digit helpers in `StringUtils` with JDK 17 `java.util.HexFormat` 
(`isHexDigit` / `fromHexDigit`) and `Numbers.isOctalDigit`; replaced custom 
`indexOfChild` and `isWhitespaceOnly` in `GroovydocManager` with `List.indexOf` 
and `String.isBlank()`; replaced raw surrogate hex literals in 
`SemanticPredicates` with `Character.isHighSurrogate` / `isLowSurrogate`; 
replaced custom overflow `long[]` resizing in `GroovyLexer.g4` with 
lazily-allocated `java.util.BitSet`.
   - **Reliability, Bare-CR Parity & Overflow Hardening:** Aligned 
standalone-`\r` handling in `PositionConfigureUtils.computeEndPosition` and 
`StringUtils.matchLineBreakEnd` with ANTLR4's `LexerATNSimulator.consume` 
(`b0a6f85c`) without duplicating lexer newline tracking; eliminated a latent 
24-bit integer shift overflow risk in `StringUtils.parseOctalEscape` by packing 
indices in a 64-bit `long`; added null-text defense in 
`GroovydocManager.nonWhitespaceNlText`; made `AstBuilder.visitModifiersOpt` 
null-safe; added non-positive cardinality guard in 
`AstBuilder.createGroovyToken`; replaced raw unchecked `(Object)` / 
`(List<Statement>)` casts in `visitSwitchBlockStatementGroup` with a type-safe 
`Stream.collect(...)` pipeline; routed single-element path chains through 
`applyPathElement` so safe-chain (`??.`) metadata propagates uniformly across 
all chain lengths.
   - **Dead Code & Hygiene:** Removed dead `CLASS_DECLARATION_CLASS_NODE` 
writes on nested `ClassDeclarationContext`, removed unused private 
`List<Statement>` block-statement and trivial list-wrapper helpers in 
`AstBuilder`, removed an unused `Maps` import in `GroovyLexer.g4`, and restored 
untouched methods in `StringUtils.java` to exact upstream formatting (zero 
drive-by reformatting).
   - **Documentation Synchronization:** Updated Javadocs, inline comments, 
[`ARCHITECTURE.md`](ARCHITECTURE.md), and 
[`src/spec/doc/core-grammar.adoc`](src/spec/doc/core-grammar.adoc) to reflect 
every grammar and architectural refinement.
   
   ### 7.2 Unit Test Architecture and JaCoCo Execution Coverage
   
   We authored **4 new JUnit 5 test suites** 
([`StringUtilsTest.java`](src/test/java/org/apache/groovy/parser/antlr4/util/StringUtilsTest.java),
 
[`GroovydocManagerTest.java`](src/test/java/org/apache/groovy/parser/antlr4/GroovydocManagerTest.java),
 
[`ModifierManagerTest.java`](src/test/java/org/apache/groovy/parser/antlr4/ModifierManagerTest.java),
 
[`NumbersTest.java`](src/test/java/org/codehaus/groovy/syntax/NumbersTest.java))
 and expanded **5 existing test suites** 
([`AbstractLexerTest.java`](src/test/java/org/apache/groovy/parser/antlr4/AbstractLexerTest.java),
 
[`AstBuilderHelperTest.java`](src/test/java/org/apache/groovy/parser/antlr4/AstBuilderHelperTest.java),
 
[`ErrorStrategyTest.java`](src/test/java/org/apache/groovy/parser/antlr4/internal/ErrorStrategyTest.java),
 
[`PositionConfigureUtilsTest.groovy`](src/test/groovy/org/apache/groovy/parser/antlr4/PositionConfigureUtilsTest.groovy),
 
[`SemanticPredicatesTest.groovy`](src/test/groovy/org/apache/groovy/parser/antlr4/SemanticPred
 icatesTest.groovy)), exercising deep parenthesis overflow (`depth = 330`), 
UTF-16 surrogate pairs, standalone `\r` line terminators and continuations 
(`PositionConfigureUtils`, `StringUtils`, `GroovydocManager`), GString EOF 
errors, all 14 metadata-bridge `@Override` visitor contracts, empty/unmatched 
member declarations, 0/1/2/3+ cardinality fast-path boundaries and AST list 
mutability, `??.` safe-chain propagation, `groovyTokenType` parity against 
`Types.lookup`, 0/1/small/large modifier lists (`size > 8`), and octal/hex/line 
escape boundaries.
   
   **Table 7:** Exact JaCoCo line and branch coverage on modified lines across 
all 10 hand-written Java production files (`./gradlew :test ... 
:jacocoTestReport`).
   
   | Production Source File | Modified Line Coverage | Modified Branch Coverage 
| Whole-File Line Coverage |
   |---|---:|---:|---:|
   | 
[`PositionConfigureUtils.java`](src/main/java/org/apache/groovy/parser/antlr4/util/PositionConfigureUtils.java)
 | **18 / 18 (100.0%)** | **12 / 12 (100.0%)** | 58 / 59 (98.3%) |
   | 
[`DescriptiveErrorStrategy.java`](src/main/java/org/apache/groovy/parser/antlr4/internal/DescriptiveErrorStrategy.java)
 | **1 / 1 (100.0%)** | — | **19 / 19 (100.0%)** |
   | 
[`GroovyLangParser.java`](src/main/java/org/apache/groovy/parser/antlr4/GroovyLangParser.java)
 | **1 / 1 (100.0%)** | — | 9 / 14 (64.3%) |
   | 
[`GroovyLangLexer.java`](src/main/java/org/apache/groovy/parser/antlr4/GroovyLangLexer.java)
 | **6 / 6 (100.0%)** | — | **40 / 40 (100.0%)** |
   | [`Numbers.java`](src/main/java/org/codehaus/groovy/syntax/Numbers.java) | 
**49 / 49 (100.0%)** | **56 / 56 (100.0%)** | 120 / 121 (99.2%) |
   | 
[`StringUtils.java`](src/main/java/org/apache/groovy/parser/antlr4/util/StringUtils.java)
 | **128 / 128 (100.0%)** | **84 / 84 (100.0%)** | 163 / 164 (99.4%) |
   | 
[`GroovydocManager.java`](src/main/java/org/apache/groovy/parser/antlr4/GroovydocManager.java)
 | **33 / 33 (100.0%)** | 39 / 40 (97.5%) | **67 / 67 (100.0%)** |
   | 
[`ModifierManager.java`](src/main/java/org/apache/groovy/parser/antlr4/ModifierManager.java)
 | **85 / 85 (100.0%)** | **69 / 69 (100.0%)** | **126 / 126 (100.0%)** |
   | 
[`SemanticPredicates.java`](src/main/java/org/apache/groovy/parser/antlr4/SemanticPredicates.java)
 | **137 / 137 (100.0%)** | 176 / 180 (97.8%) | 180 / 184 (97.8%) |
   | 
[`AstBuilder.java`](src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java)
 | **607 / 610 (99.5%)**\* | 388 / 406 (95.6%) | 2,624 / 3,050 (86.0%) |
   | **Aggregate (10 Hand-Written Java Files)** | **1,065 / 1,068 (99.72%)** | 
**824 / 847 (97.28%)** | — |
   | Generated `GroovyLexer` / `GroovyParser` `@members` | **100.0% 
reachable**† | — | — |
   
   *\*The sole 3 uncovered diff lines in `AstBuilder.java` are structurally 
unreachable: L3699 is the parallel-combiner lambda `(l, r) -> r` required by 
the three-argument `Stream.reduce` signature on a sequential stream, and 
L4282–4283 belong to a pre-existing defensive branch explicitly annotated in 
Apache Groovy as unreachable (`// the branch should never reach, because named 
arguments must not be empty`), relocated verbatim during `visitPathElement` 
decomposition. †`GroovyLexer.emit()`'s `!VAL_ENABLED` branch executes under 
`-Dgroovy.enable.val=false` in `ValDisabledTest`'s forked JVM; every other 
custom `@members` method achieves 100.0% coverage.*
   
   ### 7.3 End-to-End Verification and Binary Compatibility Matrix
   
   **Table 8:** Summary of all quality, correctness, and compatibility gates 
executed on the exact final working tree.
   
   | Verification Gate | Command / Scope | Outcome |
   |---|---|---|
   | **Golden SHA-256 Parity** | `ParserBenchmark . verify` (22 files, 
`183,983` tokens) | **PASS** — Bit-for-bit identical token & AST digests |
   | **Core Front-End Test Suite** | `:test` (`parser.antlr4.*`, `syntax.*`, 
`gls.syntax.*`, `ast.*`, `ValDisabledTest`, `SwitchPatternMatchingTest`, 
`AsyncAwaitTest`, `Groovy12332`, `Groovy12142`) | **PASS** — `1,861 passed, 0 
failed, 1 skipped` |
   | **Downstream Subproject Tests** | `:groovy-lsp:test`, 
`:groovy-groovydoc:test`, `:groovy-groovysh:test` | **PASS** — `348 + 212 + 
231` (**2,652 passed, 0 failed, 3 skipped** aggregate) |
   | **Static Lint Gate** | `./gradlew lintGate --console=plain` | **PASS** — 
Checkstyle & CodeNarc **0 violations** |
   | **Binary Compatibility (`japicmp`)** | `./gradlew 
:binary-compatibility:check --console=plain` | **PASS** — **0 breaking 
public/protected API changes** across all 12 modified classes |
   
   ---
   
   ## 8. Conclusions and Artifact Inventory
   
   By aligning Apache Groovy's grammar structure, semantic predicates, 
declarative Stream-backed AST lowering, standalone-`\r` handling, and lexical 
state management with the DFA and HotSpot C2 mechanics of the optimized ANTLR4 
runtime, this work delivers **1.03×–54.38×** latency speedups across all 26 
workloads (**1.28×** real-world AST, **1.80×** fully warmed Groovydoc AST, 
**2.76×** full-corpus AST, **1.90×** cold-start DFA, **54.38×** DSL chains) and 
**40.4%–94.0%** heap allocation reductions—while preserving Groovy's idiomatic 
Stream API style, eliminating deep nesting and wheel reinvention, and 
maintaining zero regressions in behavioral equivalence, binary API stability, 
code quality, or test coverage.
   
   ### Modified and Added Repository Files (24 Total)
   
   - **Grammar & Production Code (12):**
     [`src/antlr/GroovyLexer.g4`](src/antlr/GroovyLexer.g4),
     [`src/antlr/GroovyParser.g4`](src/antlr/GroovyParser.g4),
     
[`src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java`](src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java),
     
[`src/main/java/org/apache/groovy/parser/antlr4/GroovyLangLexer.java`](src/main/java/org/apache/groovy/parser/antlr4/GroovyLangLexer.java),
     
[`src/main/java/org/apache/groovy/parser/antlr4/GroovyLangParser.java`](src/main/java/org/apache/groovy/parser/antlr4/GroovyLangParser.java),
     
[`src/main/java/org/apache/groovy/parser/antlr4/GroovydocManager.java`](src/main/java/org/apache/groovy/parser/antlr4/GroovydocManager.java),
     
[`src/main/java/org/apache/groovy/parser/antlr4/ModifierManager.java`](src/main/java/org/apache/groovy/parser/antlr4/ModifierManager.java),
     
[`src/main/java/org/apache/groovy/parser/antlr4/SemanticPredicates.java`](src/main/java/org/apache/groovy/parser/antlr4/SemanticPredicates.java),
     
[`src/main/java/org/apache/groovy/parser/antlr4/internal/DescriptiveErrorStrategy.java`](src/main/java/org/apache/groovy/parser/antlr4/internal/DescriptiveErrorStrategy.java),
     
[`src/main/java/org/apache/groovy/parser/antlr4/util/PositionConfigureUtils.java`](src/main/java/org/apache/groovy/parser/antlr4/util/PositionConfigureUtils.java),
     
[`src/main/java/org/apache/groovy/parser/antlr4/util/StringUtils.java`](src/main/java/org/apache/groovy/parser/antlr4/util/StringUtils.java),
     
[`src/main/java/org/codehaus/groovy/syntax/Numbers.java`](src/main/java/org/codehaus/groovy/syntax/Numbers.java)
   - **Documentation & Report (3):**
     [`ARCHITECTURE.md`](ARCHITECTURE.md),
     [`src/spec/doc/core-grammar.adoc`](src/spec/doc/core-grammar.adoc),
     [`PARSER_PERFORMANCE_REPORT.md`](PARSER_PERFORMANCE_REPORT.md)
   - **Unit Tests (9 — 5 updated, 4 added):**
     
[`src/test/java/org/apache/groovy/parser/antlr4/AbstractLexerTest.java`](src/test/java/org/apache/groovy/parser/antlr4/AbstractLexerTest.java),
     
[`src/test/java/org/apache/groovy/parser/antlr4/AstBuilderHelperTest.java`](src/test/java/org/apache/groovy/parser/antlr4/AstBuilderHelperTest.java),
     
[`src/test/java/org/apache/groovy/parser/antlr4/internal/ErrorStrategyTest.java`](src/test/java/org/apache/groovy/parser/antlr4/internal/ErrorStrategyTest.java),
     
[`src/test/groovy/org/apache/groovy/parser/antlr4/PositionConfigureUtilsTest.groovy`](src/test/groovy/org/apache/groovy/parser/antlr4/PositionConfigureUtilsTest.groovy),
     
[`src/test/groovy/org/apache/groovy/parser/antlr4/SemanticPredicatesTest.groovy`](src/test/groovy/org/apache/groovy/parser/antlr4/SemanticPredicatesTest.groovy),
     
[`src/test/java/org/apache/groovy/parser/antlr4/util/StringUtilsTest.java`](src/test/java/org/apache/groovy/parser/antlr4/util/StringUtilsTest.java),
     
[`src/test/java/org/apache/groovy/parser/antlr4/GroovydocManagerTest.java`](src/test/java/org/apache/groovy/parser/antlr4/GroovydocManagerTest.java),
     
[`src/test/java/org/apache/groovy/parser/antlr4/ModifierManagerTest.java`](src/test/java/org/apache/groovy/parser/antlr4/ModifierManagerTest.java),
     
[`src/test/java/org/codehaus/groovy/syntax/NumbersTest.java`](src/test/java/org/codehaus/groovy/syntax/NumbersTest.java)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to