Repository navigation
GROOVY-12842: Optimize lexer, parser and front-end utilities - #3370
Open
daniellansun wants to merge 1 commit into
Open
daniellansun wants to merge 1 commit into
daniellansun wants to merge 1 commit into
Conversation
daniellansun
force-pushed
the
tweak-parser-20261128
branch
from
November 28, 2026 19:39
b6817f1 to
9664d26
Compare
- Lexer: factor comments, triple-quoted strings, slashy prefixes, and GString modes for pure-DFA matching; move VAL toggle to emit(); replace eager BitSet paren tracking with 64-bit primitive bitmask (+ lazy BitSet overflow) and TOKEN_FLAGS table, cutting post-warmup lexer DFA misses by 96.2%. - Parser: add colon-sensitive named-argument SLL disambiguation to eliminate SLL->LL fallbacks on DSL chains; split enumClassBody with baseContext=classBody (-1,141 DFA states, 1.90x faster cold start); simplify ifElseStatement and skip non-recovering sync() work; reuse JDK Character surrogate helpers in SemanticPredicates. - AST & utilities: pass context directly on 14 hot AstBuilder visitor paths (preserving public metadata-based overrides); flatten visitMemberDeclaration into a single-pass child loop and flatten visitClassBodyDeclaration, visitMapEntry, and visitBuiltInType; preserve Stream API / forEach style across AstBuilder, ModifierManager, and StringUtils with reusable helpers and declarative fast paths; switch GroovydocManager to O(1) local backward scanning reusing List.indexOf and String.isBlank; handle standalone '\r' line terminators in PositionConfigureUtils (using String.codePointCount) and StringUtils line escapes (reusing HexFormat and Numbers.isOctalDigit) aligned with ANTLR4's lexer handling; add Numbers 18-digit decimal fast path. - Docs, tests & report: synchronize ARCHITECTURE.md, core-grammar.adoc, and Javadocs; add unit tests achieving 99.72% JaCoCo diff-line coverage (100% reachable, 97.28% branch).
daniellansun
force-pushed
the
tweak-parser-20261128
branch
from
November 28, 2026 19:46
9664d26 to
b28804c
Compare
🚨 TestLens detected 2 failed tests 🚨Test SummaryTip Inspect all details with the TestLens CLI: Build and test / lts (25, ubuntu-latest) > :test
🏷️ Commit: b28804c Test FailuresGrabResolverTest > testResolverDefinitionResolvesDependency() (:test in Build and test / lts (25, ubuntu-latest))GrabResolverTest > testResolverDefinitionResolvesDependencyWithShorthand() (:test in Build and test / lts (25, ubuntu-latest))Rerun ControlsSelect tests to mute in this pull request:
Reuse successful test results:
Click the checkbox to trigger a rerun:
Learn more about TestLens at testlens.app/docs. |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #3370 +/- ##
==================================================
+ Coverage 75.2860% 75.3836% +0.0976%
- Complexity 49967 50292 +325
==================================================
Files 1775 1775
Lines 163660 164045 +385
Branches 32301 32409 +108
==================================================
+ Hits 123213 123663 +450
+ Misses 28947 28917 -30
+ Partials 11500 11465 -35
🚀 New features to boost your workflow:
|
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
https://issues.apache.org/jira/browse/GROOVY-12842
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-20261128Baseline Commit:
494d161(upstream/master&origin/master,GROOVY-3351)ANTLR4 Runtime:
me.sunlan:antlr4-runtime:4.13.2.20(daniellansun/antlr4,optbranch)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$O(1)$ local backward Groovydoc scanning, Stream-idiomatic linear-time modifier validation, standalone-
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 lazyBitSetoverflow, reducing post-warmup lexer DFA misses by 96.2% (8,830to333); (ii) context-guarded SLL named-argument disambiguation and binary-compatibleenumClassBodyrule 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,141DFA states); and (iii) direct-parameter AST lowering with flat single-pass member dispatch, declarative Stream-preserving cardinality fast paths,\r(bare CR) parity with ANTLR4's lexer newline semantics, and JDK-backed allocation-free literal scanners, accelerating full real-worldCONVERSIONcompilation 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 governingCodePointLexerRunnerregister allocation (and a corroboratingFreqInlineSizeboundary inAstBuilder.visitMethodDeclaration). All modifications achieve bit-for-bit token-stream and AST structural identity (183,983tokens), 99.72% JaCoCo diff-line coverage (100.0% of reachable modified lines across 10 hand-written Java files; 97.28% diff-branch coverage), zerolintGateviolations, zerojapicmppublic/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) 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 inLexerATNSimulator.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:
\n,\r\n, and standalone\rline terminators—must yield identical token streams, accurate source positions, AST shapes, and diagnostic behavior without duplicating work already handled in the ANTLR4 runtime.GroovyLexer,GroovyParser, generated*Contextclasses,AstBuilder,GroovydocManager,SemanticPredicates,StringUtils,PositionConfigureUtils, andNumbersform a stable API surface audited byjapicmp.Summary of Headline Results
Across a 22-file evaluation suite (
1.59 MB,183,983tokens) and 400 independent small scripts evaluated on OpenJDK 21, the final polished implementation achieves improvements across all 26 workloads relative to the494d161baseline (R0):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).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.3,781.11 → 1,994.79 ms) with 1,141 fewer DFA states (23,505 → 22,364).CONVERSIONaccelerates 1.28× (234.05 → 182.90 ms, best fork170.71 ms, -40.4% allocation); fully warmed Groovydoc-enabledCONVERSIONaccelerates 1.80× (289.94 → 161.03 ms, best fork154.81 ms, -65.4% allocation); full-corpus AST construction accelerates 2.76× (602.07 → 218.28 ms, best fork209.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.
6.18.57x86_64 (Ubuntu 24.04)21.0.13.0.3(mixed mode, sharing)-Xms1g -Xmx2g(default G1GC, single C2 compiler thread on 2 vCPU)com.sun.management.ThreadMXBean.getThreadAllocatedBytes(long)jfr), ANTLR4ParseInfo,-XX:+PrintCompilation, customDiagnoseLexerMisses2.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.
A_pleacpleac01–pleac20), closures, regexes, literalsB_prodConsole,GinqAstWalker,AstNodeToScriptAdapter,GroovyCommands)C_modernSwitchPatternMatchingTest,AsyncAwaitTest,AnnotationTest,LambdaTest,MethodReferenceTest)D_stressD1_ident_ops,D2_gstrings,D3_comments_nl,D4_slashy_div,D5_dsl_chainsD6_SmallScripts_400ColdDFA_Parse_RealWorld2.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 constructedModuleNodeAST across all 22 corpus files. Every single iteration from R0 through Final matched the exact golden digests: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:
DiagnoseLexerMissesrecorded 8,830 DFA misses on the 22-file corpus, dominated bySingleLineComment(//),MultiLineComment(/**), triple-single-quoted strings ('''), thevalkeyword predicate, and character-by-character GString modes. Per-token state updates relied onBitSetallocations and multi-branch token checks.ParseInfoprofiling exposed a severe SLL→LL fallback onD5_dsl_chains(4,800decision-level LL fallbacks and1,000ambiguities in Top-8 rules), inflating single-file parse latency to304.54 ms. Meanwhile,{ $t == 2 }? enumConstantsinsideclassBody[int t]leaked predicate-gated lookahead into non-enum declarations, inflating DFA state count to23,505.NodeMetaData(ListHashMap) cross-visitor parameter passing, single-element JavaStreampipeline instantiations andLinkedListreductions inAstBuilder, regex-based escape rewriting inStringUtils,BigIntegerallocations inNumbers.parseInteger, and anGroovydocManager(263.26 MBallocated per pass).*Contextclass hierarchies or visitor contracts were ruled out. Instead,enumClassBodyuses ANTLR4'soptions { baseContext = classBody; }so callers observeClassBodyContextwitht == 2.AstBuilder, all 14 public@Overridemetadata-reading visitor methods were preserved as thin bridges delegating to private direct-parameter overloads.colonSensitiveLevelcounter coveringassert, ternary (? :), andswitch/caseexpressions so outer colons are never misclassified as named-argument separators.daniellansun/antlr4already counts standalone\r(not followed by\n) as a line terminator insideLexerATNSimulator.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).4. Iterative Implementation and Algorithmic Contributions
4.1 Iteration I — Lexer Pure-DFA Factoring and Allocation-Free State Representation
Implemented in
GroovyLexer.g4andGroovyLangLexer.java:SingleLineComment,MultiLineComment, andSlashyFirstCharacterso//,/*, and/**traverse pure DFA edges inDEFAULT_MODEwithout invoking leading semantic predicates (isRegexAllowed()).TdqBody,TsqBody,TdqNonQuote, andTsqNonQuotealongside bulk GString scanning modes and conditionalpushMode/popMode, eliminating per-character mode churn on long triple-quoted strings and interpolated GStrings.VALToggle inemit(): Moved the-Dgroovy.enable.val=falsecheck out of the lexer rule's semantic predicate intoGroovyLexer.emit(), enabling pure-DFA matching ofvalwhile preserving runtime configurability (verified byValDisabledTest).BitSetparenthesis tracking with a 64-bitlong parenBitsbitmask featuring a permanent sentinel at bit 0 (eliminating depth-zero checks and index decrements inisInsideParens()) backed by a lazily allocatedjava.util.BitSet parenOverflowBitsonly for nesting depths exceeding 63 (avoiding custom array-resizing code). Replaced scattered token-class checks with a 256-entrybyte[] TOKEN_FLAGSlookup table and a single-bitmaskFLAG_REAL_TOKEN_SPECIALfast path innoteRealToken(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,SemanticPredicates.java,DescriptiveErrorStrategy.java, andGroovyLangParser.java:{ colonSensitiveLevel > 0 || !SemanticPredicates.isNamedArg(_input) }?andisNamedPropertyArg(_input)predicates tofirstArgumentListElementandargumentListElement, backed by a unified bounded delimiter scanner (skipBalanced/isBalancedFollowedByColon) and JDKCharacter.isHighSurrogate/isLowSurrogatechecks. When outside colon-sensitive contexts (colonSensitiveLevel == 0), SLL immediately commits tonamedArg/namedPropertyArgwithout ambiguity or LL fallback.enumClassBodySplit: Extracted enum bodies intoenumClassBodywithoptions { baseContext = classBody; }and@init { _localctx.t = 2; }. Non-enum classes, interfaces, traits, and records use a streamlinedclassBody[int t]devoid ofenumConstantslookahead, eliminating 1,141 DFA states while preserving fullClassBodyContextcompatibility.ifElseStatementtosep? ELSE; addedDescriptiveErrorStrategy.isSyncRequired()so non-recovering SLL parses skip unnecessary error-recovery set computations; added package-privateGroovyLexer(CharStream, boolean)andGroovyParser(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,GroovydocManager.java,ModifierManager.java,StringUtils.java,PositionConfigureUtils.java, andNumbers.java: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@Overridemetadata bridges for backwards compatibility. RefactoredvisitMemberDeclarationinto a flat single-passctx.getChildCount()/ctx.getChild(i)loop with Java 17 pattern-matchinginstanceofand early returns (cutting nesting from 6 levels to 2, eliminating up to 5 redundantgetRuleContextscans and allNodeMetaDataallocations across methods, fields, compact constructors, and nested types); flattenedvisitClassBodyDeclaration,visitMapEntry, andvisitBuiltInType; madevisitModifiersOptnull-safe; replacednew LinkedList<>()withnew ArrayList<>(0)and an empty guard beforeforEachinvisitMethodDeclaration. PreservedAstBuilder's idiomatic declarative Stream API /forEachstyle across multi-element transformations while introducing a reusable Stream-backedmapToListhelper, Java 17switchexpressions for 1- and 2-element path chains (createPathExpressionviaapplyPathElement) and qualified names (joinQualifiedNameElements), single-element fast paths invisitEnhancedArgumentListInPar,visitFormalParameterList,visitBlockStatements(streaming directly intoBlockStatementviaforEach), andvisitGstring(createGStringLiteral+parseGStringSegment), type-safeStream.collect/flatMapin switch visitors, and a directswitchingroovyTokenType()replacingTypes.lookup.GroovydocManager's0with a localized backward walk starting atchildren.indexOf(node) - 1(reusingList.indexOfdirectly) 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-freeString.isBlank()(text.isEmpty() || !text.isBlank()).StringUtils: RewrotereplaceHexEscapes,replaceOctalEscapes,replaceStandardEscapes, andreplaceLineEscapeas single-passcharAtscanners with identity return when no backslash exists; packed octal parse state into a 64-bitlong(((long) end << 8) | val) to prevent 24-bit integer index overflow on multi-megabyte strings; handled standalone\rline continuations inmatchLineBreakEnd('\r'? '\n' | '\r'); reused JDK 17java.util.HexFormat(isHexDigit/fromHexDigit) andNumbers.isOctalDigit; preserved Stream style incountChar.Numbers: Added an 18-digit decimal integer fast path (parseSimpleDecimalInteger+ helper methods) bypassingBigIntegerand substring allocation for the common case while falling back cleanly for underscores, non-decimal radices,G/gsuffixes, and overflow diagnostics.ModifierManager: Switched duplicate-modifier validation to an allocation-free linear scan forsize <= 8, retainingHashSetvalidation for larger lists to guaranteeforEachstyle throughout query and mutation helpers while factoring out reusableanyModifierMatches,checkVisibilityLimit, andvalidateDisallowed.PositionConfigureUtils: Computed end line/column positions in a single pass packed into a 64-bitlong, treating\n,\r\n, and standalone\ridentically to ANTLR4'sLexerATNSimulator.consume(b0a6f85c), and delegating UTF-16 code-point counting directly to JDK'sString.codePointCount(5. Empirical Case Study: HotSpot C2 Inlining Laws for
CodePointLexerRunnerandAstBuilderDuring Iteration III (R3), we evaluated consolidating 10 grammar-level lexer actions into
GroovyLexer.emit()via a bitflag dispatch helper (handleEmitAction), simultaneously shrinking the generatedGroovyLexer.action()method from531bytes to255bytes. Controlled benchmarking immediately detected a sharp regression:L1_Lex_Alldegraded from26.31 ms(R1) to34.11 ms(R3), accompanied by bimodal fork-to-fork jitter (16.65 msvs22.35 ms).Using
CpuVsWall, Tier-4-XX:+PrintCompilationdiffs, and-XX:CompileCommand=dontinlineisolation experiments, we identified and verified two HotSpot C2 compilation laws governingCodePointLexerRunner+GroovyLexer:emit()):GroovyLexer.emit()must remain minimal (if (!VAL_ENABLED && VAL == _type) _type = Identifier; return super.emit();). BecauseVAL_ENABLEDisstatic 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)) insideemit()degradesL1_Lex_Allby4–8 ms.FreqInlineSize = 325Bytes): ShrinkingGroovyLexer.action()below HotSpot'sFreqInlineSizethreshold (255 < 325bytes) enables C2 to inlineaction()transitively intoLexerActionExecutor.execute()→finishToken()→CodePointLexerRunner.exec8Bit(). Inlining the multi-way switch intoexec8Bit's tight per-byte DFA loop causes severe x86-64 register spilling and bimodal code layouts depending on compilation order. Keeping inline actions in.g4preservesGroovyLexer.action()at531bytes (> 325), keepingexec8Bit()'s register pressure minimal and deterministic.Reverting the
emit()consolidation while retaining zero-bloat improvements (parenBitsbit-0 sentinel,FLAG_REAL_TOKEN_SPECIAL, and a24-byteGroovyLangLexer.nextToken()fitting within C2MaxInlineSize = 35) produced R3B, immediately restoring and surpassing all prior lexer throughput records (19.80 msonL1_Lex_RealWorld, inter-fork spread19.79–19.90 ms).A corroborating instance of Law #2 emerged when refactoring
AstBuilder.visitMethodDeclarationto acceptClassNodedirectly: removing redundantgetNodeMetaDataandasBooleancalls briefly shrankvisitMethodDeclarationfrom331bytes to319bytes (< 325), causing C2 to inline the entire method-lowering body intovisitMemberDeclaration, pushingvisitMemberDeclarationoverInlineSmallCode(already compiled into a big method), and causing bimodal tail spikes onL4_AST_All(256.84 msvs209.54 msunder-XX:CompileCommand=dontinline). Replacingnew LinkedList<>()withnew ArrayList<>(0)and guarding emptyanonymousInnerClassListbeforeforEachboth eliminated per-methodLinkedList+ iterator allocation and naturally restoredvisitMethodDeclarationto330bytes (> 325), recovering161.03 ms(1.80×) onL4_AST_Gdoc_RealWorld.6. Quantitative Performance Evaluation
6.1 End-to-End Steady-State Progression Across All 26 Workloads
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, andL4_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/ModifierManagerStream API style preserved, flat single-passvisitMemberDeclaration, bare-CR handling, and JDK reuse).L1_Lex_RealWorldL2_Parse_RealWorldL3_LexParse_RealWorldL4_AST_RealWorldL4_AST_Gdoc_RealWorldL1_Lex_AllL2_Parse_AllL3_LexParse_AllL4_AST_AllD6_SmallScripts_400Lex_A_pleacParse_A_pleacLex_B_prodParse_B_prodLex_C_modernParse_C_modernLex_D1_ident_opsParse_D1_ident_opsLex_D2_gstringsParse_D2_gstringsLex_D3_comments_nlParse_D3_comments_nlLex_D4_slashy_divParse_D4_slashy_divLex_D5_dsl_chainsParse_D5_dsl_chains6.2 Cold-Start DFA Construction and State-Space Compaction
Table 4: Cold-start
ColdDFA_Parse_RealWorldprogression across iterations (median and minimum over 3 fresh ATN/DFA instantiations per JVM).6.3 Parser Decision Profile (
ParseInfo) and Post-Warmup Lexer DFA MissesTable 5: Top parser decisions on the full 22-file corpus (
profile-all), contrasting baseline SLL→LL fallback cascading against Final zero-fallback SLL execution.D5_dsl_chains.groovy)pathExpressiontime /LL_FB/AmbcommandArgumenttime /LL_FB/AmbcommandExpressiontime /LL_FB/AmbfirstArgumentListElementtime /LL_FBargumentListElementtime /LL_FBSLL_ATNmisses across Top 25 decisionsTable 6: Post-warmup
DiagnoseLexerMissesbreakdown across all 22 corpus files.SingleLineComment(// ...)''')MultiLineComment/ Groovydoc (/*,/**)VALkeyword (val)!in/!instanceofedge transitions6.4 Warmup Dynamics, Style–Performance Trade-Off, and Threats to Validity
Three methodological considerations warrant explicit disclosure in accordance with rigorous JVM benchmarking practice:
w = 0..24) and 4 AST passes (w = 0..3), followed by 4 per-benchmark warmup passes inL4_AST_RealWorld. Consequently, late Tier-4 compilations inAstBuilderoccasionally finish draining duringL4_AST_RealWorld(182.90 ms, Fork 3170.71 ms), whereasL4_AST_Gdoc_RealWorld—which runs immediately afterward over the same 17 files with Groovydoc additionally enabled—executes completely warm (161.03 ms, best fork154.81 ms,min = 151.49 ms).AstBuilder(87.53 MB/160.73 msonL4_AST_RealWorld) against the final Stream-preserving design (91.01 MB,-230 KBlower than the prior Stream-preserving revision thanks to directvisitClassDeclaration/visitMethodDeclaration/visitCompactConstructorDeclarationdispatch andArrayList(0)+ empty-guard onanonymousInnerClassList) via JFRObjectAllocationSampleconfirmed thatmapToList, 1/2-element declarativeswitchfast paths, andModifierManager.anyModifierMatcheseliminated >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).-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:
SemanticPredicates.javaintoskipBalanced/isBalancedFollowedByColon, extractedisDelimiterSpace(int),isQualifiedCapitalizedEmptyCall, andisInvalidQualifiedLocalVariableDeclaration(all methods ≤ 12). DecomposedNumbers.parseSimpleDecimalInteger(formerly complexity 27) into four focused helpers (all ≤ 9). DecomposedStringUtilsescape scanners intoparseOctalEscape,matchLineBreakEnd, andensureBuffer(all ≤ 11). InAstBuilder.java, flattenedvisitMemberDeclarationfrom 6 indentation levels down to 2 via single-passctx.getChildCount()/ctx.getChild(i)dispatch, flattenedvisitClassBodyDeclaration,visitMapEntry, andvisitBuiltInType, and extractedmapToList,applyPathElement,createGStringLiteral, andcreateNamedArgumentTuplewhile preserving idiomatic Stream API pipelines across collection-mapping visitors. InModifierManager.java, restored Stream API /forEachstyle across all query and mutation methods and factored outanyModifierMatches,checkVisibilityLimit, andvalidateDisallowed.PositionConfigureUtilswith JDK'sString.codePointCount; replaced custom hex and octal digit helpers inStringUtilswith JDK 17java.util.HexFormat(isHexDigit/fromHexDigit) andNumbers.isOctalDigit; replaced customindexOfChildandisWhitespaceOnlyinGroovydocManagerwithList.indexOfandString.isBlank(); replaced raw surrogate hex literals inSemanticPredicateswithCharacter.isHighSurrogate/isLowSurrogate; replaced custom overflowlong[]resizing inGroovyLexer.g4with lazily-allocatedjava.util.BitSet.\rhandling inPositionConfigureUtils.computeEndPositionandStringUtils.matchLineBreakEndwith ANTLR4'sLexerATNSimulator.consume(b0a6f85c) without duplicating lexer newline tracking; eliminated a latent 24-bit integer shift overflow risk inStringUtils.parseOctalEscapeby packing indices in a 64-bitlong; added null-text defense inGroovydocManager.nonWhitespaceNlText; madeAstBuilder.visitModifiersOptnull-safe; added non-positive cardinality guard inAstBuilder.createGroovyToken; replaced raw unchecked(Object)/(List<Statement>)casts invisitSwitchBlockStatementGroupwith a type-safeStream.collect(...)pipeline; routed single-element path chains throughapplyPathElementso safe-chain (??.) metadata propagates uniformly across all chain lengths.CLASS_DECLARATION_CLASS_NODEwrites on nestedClassDeclarationContext, removed unused privateList<Statement>block-statement and trivial list-wrapper helpers inAstBuilder, removed an unusedMapsimport inGroovyLexer.g4, and restored untouched methods inStringUtils.javato exact upstream formatting (zero drive-by reformatting).ARCHITECTURE.md, andsrc/spec/doc/core-grammar.adocto 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,GroovydocManagerTest.java,ModifierManagerTest.java,NumbersTest.java) and expanded 5 existing test suites (AbstractLexerTest.java,AstBuilderHelperTest.java,ErrorStrategyTest.java,PositionConfigureUtilsTest.groovy,SemanticPredicatesTest.groovy), exercising deep parenthesis overflow (depth = 330), UTF-16 surrogate pairs, standalone\rline terminators and continuations (PositionConfigureUtils,StringUtils,GroovydocManager), GString EOF errors, all 14 metadata-bridge@Overridevisitor contracts, empty/unmatched member declarations, 0/1/2/3+ cardinality fast-path boundaries and AST list mutability,??.safe-chain propagation,groovyTokenTypeparity againstTypes.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).PositionConfigureUtils.javaDescriptiveErrorStrategy.javaGroovyLangParser.javaGroovyLangLexer.javaNumbers.javaStringUtils.javaGroovydocManager.javaModifierManager.javaSemanticPredicates.javaAstBuilder.javaGroovyLexer/GroovyParser@members*The sole 3 uncovered diff lines in
AstBuilder.javaare structurally unreachable: L3699 is the parallel-combiner lambda(l, r) -> rrequired by the three-argumentStream.reducesignature 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 duringvisitPathElementdecomposition. †GroovyLexer.emit()'s!VAL_ENABLEDbranch executes under-Dgroovy.enable.val=falseinValDisabledTest's forked JVM; every other custom@membersmethod 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.
ParserBenchmark . verify(22 files,183,983tokens):test(parser.antlr4.*,syntax.*,gls.syntax.*,ast.*,ValDisabledTest,SwitchPatternMatchingTest,AsyncAwaitTest,Groovy12332,Groovy12142)1,861 passed, 0 failed, 1 skipped:groovy-lsp:test,:groovy-groovydoc:test,:groovy-groovysh:test348 + 212 + 231(2,652 passed, 0 failed, 3 skipped aggregate)./gradlew lintGate --console=plainjapicmp)./gradlew :binary-compatibility:check --console=plain8. Conclusions and Artifact Inventory
By aligning Apache Groovy's grammar structure, semantic predicates, declarative Stream-backed AST lowering, standalone-
\rhandling, 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.