Daniel Sun created GROOVY-12842:
-----------------------------------

             Summary: Optimize ANTLR4 lexer, parser, AST builder, and front-end 
utilities
                 Key: GROOVY-12842
                 URL: https://issues.apache.org/jira/browse/GROOVY-12842
             Project: Groovy
          Issue Type: Improvement
            Reporter: Daniel Sun


h2. Motivation

Profiling the Apache Groovy ANTLR4 compiler front-end (using JFR, ANTLR4 
{{ParseInfo}}, and post-warmup lexer DFA-miss diagnostics) revealed several 
latency and allocation bottlenecks across lexing, parsing, AST lowering, 
Groovydoc attachment, and literal decoding:

* *Lexer:* 8,830 post-warmup DFA misses driven by leading semantic predicates 
on comments, triple-quoted strings, slashy strings, GString identifiers, and 
the {{val}} keyword, along with per-character GString mode churn and 
per-delimiter {{Paren}} object allocations.
* *Parser:* SLL-to-LL fallbacks and ambiguities on optional-parentheses DSL 
named-argument chains, plus 1,141 redundant parser DFA states caused by 
predicate-gated {{enumConstants}} lookahead inside {{classBody}}.
* *AST builder:* Heavy heap allocation from {{NodeMetaData}} ({{ListHashMap}}) 
cross-visitor parameter passing, single-element {{Stream}} pipelines, 
{{LinkedList}} usage, and repeated CST child lookups.
* *Front-end utilities:* Repeated forward sibling scans and regex whitespace 
matching in {{GroovydocManager}}, regex-based escape rewriting in 
{{StringUtils}}, eager map allocations in {{ModifierManager}}, boxed {{Tuple2}} 
end-position tracking in {{PositionConfigureUtils}}, and {{BigInteger}} 
allocations for common decimal literals in {{Numbers}}.

This improvement optimizes each front-end stage while preserving bit-for-bit 
token and AST equivalence, binary and visitor compatibility, and Groovy's 
declarative Stream API style.

h2. Summary of Changes

h3. 1. Lexer ({{GroovyLexer.g4}}, {{GroovyLangLexer}})

* *Pure-DFA factoring:* Refactored single-line ({{//}}) and 
multi-line/Groovydoc comments, triple-quoted string bodies ({{TdqBody}} and 
{{TsqBody}}), two-character slashy prefixes ({{SlashyFirstCharacter}}), and 
ASCII GString identifiers to follow pure DFA edges without leading semantic 
predicates; switched GString modes to bulk scanning and guarded delimiter 
mode-stack pushes/pops when the mode stack is empty.
* *Deferred feature-flag remapping:* Moved the {{groovy.val.enabled}} check for 
{{val}} from a lexer rule predicate into {{GroovyLexer.emit()}}, keeping 
{{val}} matching pure-DFA while letting HotSpot C2 constant-fold the branch 
under the default configuration.
* *Compact state tracking:* Replaced {{ArrayDeque<Paren>}} object allocations 
with a 64-bit {{parenBits}} bitmask (permanent bit-0 sentinel plus lazy 
{{BitSet}} overflow beyond depth 63); consolidated the three token-class 
{{BitSet}} fields into a single {{TOKEN_FLAGS}} byte table with a fast path in 
{{noteRealToken}}; cached the comment text {{Supplier}}; replaced varargs 
delimiter checks for the negated {{in}} and {{instanceof}} operators with 
zero-allocation helpers; avoided throwaway {{LexerATNSimulator}} allocation in 
{{GroovyLangLexer}}.

h3. 2. Parser and Semantic Predicates ({{GroovyParser.g4}}, 
{{GroovyLangParser}}, {{SemanticPredicates}}, {{DescriptiveErrorStrategy}})

* *Zero-fallback SLL named arguments:* Added {{isNamedArg}} and 
{{isNamedPropertyArg}} SLL predicates on {{firstArgumentListElement}} and 
{{argumentListElement}}, guarded by a {{colonSensitiveLevel}} nesting counter 
across {{assert}}, {{case}}, and ternary expressions so outer colons are never 
misclassified as named-argument labels.
* *Binary-compatible enum body split:* Extracted enum bodies into 
{{enumClassBody}} with {{baseContext = classBody}} so non-enum classes, 
interfaces, traits, and records avoid predicate-gated {{enumConstants}} 
lookahead while preserving {{ClassBodyContext}} and visitor compatibility 
(1,141 fewer DFA states).
* *Streamlined parsing and lookahead:* Simplified {{ifElseStatement}} to {{sep? 
ELSE}}; overrode {{DescriptiveErrorStrategy.isSyncRequired()}} to return 
{{false}} (matching {{BailErrorStrategy}}); added a package-private 
{{GroovyParser}} constructor accepting the shared {{ATN}} directly; switched 
grammar and {{SemanticPredicates}} lookahead from {{LT(k)}} to {{LA(k)}} with 
unified balanced-delimiter scanning and JDK {{Character}} surrogate helpers.

h3. 3. AST Builder ({{AstBuilder}})

* *Direct-parameter lowering:* Passed context objects directly across 14 hot 
visitor paths (class, body, enum, member, field, compact constructor, method, 
variable, command-argument, and path-element visitors) to eliminate 
{{NodeMetaData}} overhead, retaining all 14 public {{@Override}} methods as 
metadata-reading bridges for binary and subclass compatibility.
* *Flattened dispatch:* Refactored {{visitMemberDeclaration}} into a 
single-pass child loop with pattern-matching {{instanceof}}, flattened 
{{visitClassBodyDeclaration}}, {{visitMapEntry}}, and {{visitBuiltInType}}, and 
decomposed {{visitPathElement}} into focused helpers.
* *Stream-preserving fast paths and lower allocation:* Added declarative 
0/1/2-element fast paths ({{mapToList}}, {{createPathExpression}} via 
{{applyPathElement}} with uniform safe-chain metadata propagation, 
{{joinQualifiedNameElements}}, {{visitEnhancedArgumentListInPar}}, 
{{visitFormalParameterList}}, {{visitBlockStatements}}, and {{visitGstring}}); 
replaced {{LinkedList}} with pre-sized {{ArrayList}}; lazily initialized 
parameter metadata maps and sized internal stacks for small scripts; removed 
redundant {{BufferedReader}} wrapping in {{createCharStream}}; replaced 
unchecked switch {{reduce}} casts with type-safe {{flatMap}} / {{collect}}; 
added a direct {{groovyTokenType}} switch fast path ahead of {{Types.lookup}}.

h3. 4. Front-End Utilities ({{GroovydocManager}}, {{ModifierManager}}, 
{{PositionConfigureUtils}}, {{StringUtils}}, {{Numbers}})

* *Groovydoc scanning* ({{GroovydocManager}}): Replaced repeated forward 
sibling scanning and regex whitespace matching with localized backward walking 
from {{children.indexOf(node) - 1}} and JDK {{String.isBlank()}}.
* *Modifier validation* ({{ModifierManager}}): Used a zero-allocation linear 
duplicate scan for {{size <= 8}} (retaining {{HashSet}} for larger lists), 
added 0/1-element fast paths, fused visibility checking into 
{{calcModifiersOpValue}}, replaced {{INVALID_MODIFIERS_MAP}} with 
{{IntPredicate}} validation, and attached annotations without intermediate list 
allocation.
* *Token end positions* ({{PositionConfigureUtils}}): Packed single-pass end 
line/column computation into a primitive {{long}} (avoiding {{Tuple2}} and 
boxed {{Integer}} allocations), delegated code-point width counting to 
{{String.codePointCount}}, and aligned standalone {{\r}} line-terminator 
handling with ANTLR4's lexer alongside {{\n}} and {{\r\n}}.
* *Escape decoding* ({{StringUtils}}): Replaced regex-based hex, octal, 
standard, and line-continuation escape rewriters with single-pass {{charAt}} 
scanners returning the input unchanged when no backslash is present; reused JDK 
{{HexFormat}} and {{Numbers.isOctalDigit}}; supported standalone {{\r}} line 
continuations; packed octal parse state into a {{long}} to prevent index 
overflow on very large strings.
* *Numeric literals* ({{Numbers}}): Added an 18-digit decimal integer fast path 
in {{parseInteger}} to bypass {{BigInteger}} and substring allocations for 
common literals, and guarded underscore stripping with {{indexOf('_') >= 0}} in 
{{parseInteger}} and {{parseDecimal}}.

h2. Performance Impact

Measured on OpenJDK 21 across a 22-file corpus (1.59 MB, 183,983 tokens: 17 
real-world files plus 5 synthetic stress files) and a 400-script 
micro-compilation batch (3-fork steady-state medians; full methodology, 
per-tier results, and HotSpot C2 JIT analysis are documented in 
{{PARSER_PERFORMANCE_REPORT.md}}):

|| Workload / Metric || Baseline || Optimized || Improvement ||
| Post-warmup lexer DFA misses (22 files) | 8,830 | 333 | *96.2% fewer* |
| Real-world lexing (17 files) | 23.52 ms | 20.17 ms | *1.17x* (54.49 → 63.54 
MB/s) |
| Multi-line and interpolated GString lexing | 3.09 ms | 1.47 ms | *2.11x* |
| Real-world SLL parsing (17 files) | 52.94 ms | 48.74 ms | *1.09x* |
| Full-corpus parsing (22 files) | 375.17 ms | 70.81 ms | *5.30x* (63.3% less 
heap alloc; 0 LL fallbacks) |
| DSL named-argument chain parsing | 304.54 ms | 5.60 ms | *54.38x* (94.0% less 
heap alloc) |
| Cold-start DFA construction (17 files) | 3,781.11 ms | 1,994.79 ms | *1.90x* 
(1,141 fewer DFA states: 23,505 → 22,364) |
| Real-world {{CONVERSION}} (AST) | 234.05 ms | 182.90 ms | *1.28x* (40.4% less 
heap alloc) |
| Real-world {{CONVERSION}} (AST + Groovydoc, warmed) | 289.94 ms | 161.03 ms | 
*1.80x* (65.4% less heap alloc) |
| Full-corpus {{CONVERSION}} (AST, 22 files) | 602.07 ms | 218.28 ms | *2.76x* 
(58.4% less heap alloc) |
| Small-script batch (400 scripts) | 24.34 ms | 21.00 ms | *1.16x* (44.8% less 
heap alloc) |

h2. Compatibility and Verification

* *Semantic and structural parity:* Verified bit-for-bit identical token-stream 
and AST SHA-256 digests across all 22 corpus files (183,983 tokens).
* *Binary and visitor compatibility:* Passed {{:binary-compatibility:check}} 
({{japicmp}}) with zero breaking public/protected API changes across all 12 
modified production files.
* *Unit tests and coverage:* Added 4 new JUnit 5 test suites 
({{StringUtilsTest}}, {{GroovydocManagerTest}}, {{ModifierManagerTest}}, 
{{NumbersTest}}) and expanded 5 existing suites ({{AbstractLexerTest}}, 
{{AstBuilderHelperTest}}, {{ErrorStrategyTest}}, 
{{PositionConfigureUtilsTest}}, {{SemanticPredicatesTest}}), achieving *99.72%* 
JaCoCo diff-line coverage (100% of reachable modified lines) and *97.28%* 
diff-branch coverage across the 10 modified hand-written Java files.
* *Regression and quality gates:* 2,652 passing tests across core front-end 
suites (1,861) and downstream subprojects ({{groovy-lsp}}: 348, 
{{groovy-groovydoc}}: 212, {{groovy-groovysh}}: 231), with zero 
Checkstyle/CodeNarc violations ({{lintGate}}).
* *Documentation:* Synchronized {{ARCHITECTURE.md}}, 
{{src/spec/doc/core-grammar.adoc}}, and Javadocs, and added 
{{PARSER_PERFORMANCE_REPORT.md}}.




--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to