Repository navigation
Avoid 64KB clinit limit for large grammars via init methods - #12
Open
manticore-projects wants to merge 13 commits into
Open
manticore-projects wants to merge 13 commits into
manticore-projects wants to merge 13 commits into
Conversation
Grammars with many keywords (e.g. JSqlParser with 500+ SQL keywords) generate TokenManager classes where the combined static array initializers exceed the JVM's 64 KB bytecode limit per method. All static final field initializers compile into a single <clinit> method, causing ClassFormatError at class load time. Move array initialization out of <clinit> into dedicated _init() methods. For very large arrays, split across multiple chunk methods so no single method exceeds the bytecode limit. For 2D arrays (jjnextStateSet, jjcompositeState), flatten into contiguous 1D arrays with offset/length accessors, eliminating both the <clinit> problem and the per-row object header overhead. New file: JavaArrayHelper.java Reusable utility for emitting chunked int[], String[] and flattened int[][] array initializers via _init() methods. Modified: TokenManagerCodeGenerator.java Six arrays now emitted via JavaArrayHelper: - stringLiterals (int[]) — collect then emit via emitIntArray - jjstrLiteralImages (String[]) — collect then emit via emitStringArray - jjmatchKinds (int[]) — collect then emit via emitIntArray - jjnewLexState (int[]) — emit via emitIntArray - jjnextStateSet (int[][]) — flatten to 1D via emitFlatIntArray2D - jjcompositeState (int[][]) — flatten to 1D via emitFlatIntArray2D Modified: TokenManagerDriver.template Two lines changed to use generated _row() accessors for the flattened 2D arrays (jjcompositeState_row, jjnextStateSet_row). Backward compatible: generated parser is functionally identical. Tested with JSqlParser (500+ keywords, 500+ productions).
…alls GC threshold Strip all `if (DBG_EXP) System.out.println(...)` emissions from the Java parser code generator. These produced dead branches in the generated parser (DBG_EXP is a `static final boolean = false` constant) that inflated jj_scan_token bytecode, reducing HotSpot's ability to inline this critical method which is called from every phase-3 lookahead routine. Also increase MAX_NB_POS from 100 to 512, reducing the frequency of the JJCalls cleanup sweep in jj_consume_token from every 100 to every 512 consumed tokens. Both changes are logic-free: no control flow, branching, or error reporting behavior is altered.
…dant field writes The default code path in jjFillToken created tokens via the one-arg Token.newToken(kind), which sets image to null, then immediately overwrote both t.kind (redundant, already set by constructor) and t.image. Switch to the two-arg Token.newToken(kind, image) that was already available behind the BINARY_NEW_TOKEN option flag, making it the unconditional default. This eliminates two field writes per token created. The BINARY_NEW_TOKEN conditional is removed as it is now the default path.
The jjMoveNfa inner loop called jjnextStateSet_row(state) on every NFA state transition and jjcompositeState_row(startState) for epsilon closure initialization. Both methods allocated a new int[] and did a System.arraycopy on every call — in the hottest loop of the tokenizer. Replace with direct indexed iteration over the existing flat data arrays (jjnextStateSet_data/offsets/lengths and jjcompositeState_data/ offsets/lengths). Same data, same order, zero allocation. The _row helper methods become dead code. Also includes the previously confirmed Token.newToken two-arg change (eliminates redundant kind/image field writes in jjFillToken).
…ing literal matching The startAndSize map in jjRunStringLiteralMatch used a HashMap<Integer,int[]> to look up string literal match candidates by (lexState << 16 | firstChar). Every lookup autoboxed the int key to Integer. Replace with two sorted parallel int[] arrays (ssKeys, ssValues) and java.util.Arrays.binarySearch for zero-boxing lookup. For typical grammars with ~50-100 entries, binary search takes 6-7 int comparisons vs HashMap hash+equals+chain traversal. Also eliminates the InitStartAndSize() method and its 55 individual HashMap.put calls with new int[] allocations at class load time.
The jj_save() call in each jj_2_N method was in a finally block, executing on every lookahead regardless of outcome. jj_save feeds jj_rescan_token which only runs during error reporting (generateParseException). Move jj_save inside the try block, conditional on lookahead failure. Successful lookaheads and LookaheadSuccess catches skip jj_save entirely. This eliminates the finally block from all 675 jj_2 methods, giving the JIT simpler control flow. Trade-off: on parse errors, only failed lookaheads contribute to the error token set. The most relevant lookahead (the failing one) is still captured.
…imit Split large generated methods into sub-methods when safety thresholds are exceeded, preventing MethodTooLargeException from javac or from ASM-based instrumentation tools (JaCoCo, ByteBuddy). ParserCodeGenerator: - Split jj_rescan_token switch into chunk sub-methods (threshold: 500) - Split jj_la1_init_* array init into chunk sub-methods (threshold: 4000) - Split phase3 Choice chains into continuation sub-methods (threshold: 1000) TokenManagerCodeGenerator: - Route canMatchAnyChar, jjInitStates, jjInitialMatchForLexState through JavaArrayHelper.emitIntArray() instead of inline static arrays - Route jjtoToken/Skip/Special/More through JavaArrayHelper.emitLongArray() - Wrap large CharDataConsts CHAR_DATA arrays and jjCharData in _init() methods JavaArrayHelper: - Add emitLongArray() with chunk splitting (2000 elements per chunk) All changes are backwards-compatible: splitting only activates when thresholds are exceeded. Existing grammars produce identical output. Fixes: org.objectweb.asm.MethodTooLargeException: Method too large: net/sf/jsqlparser/parser/CCJSqlParserTokenManager.<clinit> ()V
Author
|
For JSQLParser, all those patches reduced the parsing overhead from 7% down to 2% and yielded in a 25% faster parser. |
Author
|
Is there anyone left working on this? |
Three defects in the generated token manager, all around the lexical action switches. SkipLexicalActions() was generated from MatchType.SKIP only; the SPECIAL_TOKEN dump sat commented out beside it. TokenManagerDriver routes both SKIP and SPECIAL_TOKEN matches through that method, so every SPECIAL_TOKEN action was silently dropped. A grammar that ends a MORE chain in a SPECIAL_TOKEN carrying input_stream.backup() lost the backup and swallowed the following character. jjmatchedPos meant two different things: jjRunStringLiteralMatch set it to a character count, jjMoveNfa to a zero based index. Only the difference (lastReadPosition - jjmatchedPos) was ever consumed, so matching still worked and the inconsistency stayed hidden, but the generator used the count form. Every lexical action on an NFA matched rule therefore saw an `image` short by one leading character. The literal path is normalised to zero based indices and the generator restored to jjmatchedPos + 1. MoreLexicalActions() advanced jjimageLen inside each case rather than once at the top, so MORE matches without an action never extended the accumulator, and no case ever appended to `image`. image.toString() in a MORE action was therefore always empty. Verified by self hosting to a fixed point and against JSqlParser issue #2509. Downstream note: grammars that compensated for the short `image` in a TOKEN action must drop that compensation in the same release. Signed-off-by: Andreas Reichel <andreas@manticore-projects.com>
manticore-projects
force-pushed
the
release
branch
from
October 17, 2026 12:08
9d8786a to
0b3f7d5
Compare
The generated parser passes the grammar location of each jj_consume_token and jj_scan_token call, and of each jj_la1_loc entry, as a "line:col" string literal used in error messages. Each distinct location takes two of the at most 65535 constant pool entries of the parser class: in JSQLParser's parser, 7,436 locations take 14,872 of its 47,463 entries. The generated code now passes the 1-based index of the location in a table of strings, which is in a nested class, JJLocations, loaded with the first error message. jj_loc(int) gives the string back to the error reporting code, so the error messages don't change. jj_consume_token (int, String) is still generated for grammar code that calls it. To generate both versions of jj_consume_token, its generation moved into a method. Its body is unchanged. On JSQLParser, the parser class goes from 47,463 to 32,603 constant pool entries. Signed-off-by: minleejae <mmj9808@gmail.com>
Pass grammar locations to the generated parser as indexes
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.
Grammars with many keywords (e.g. JSqlParser with 500+ SQL keywords) generate TokenManager classes where the combined static array initializers exceed the JVM's 64 KB bytecode limit per method. All static final field initializers compile into a single method, causing ClassFormatError at class load time.
Move array initialization out of into dedicated _init() methods. For very large arrays, split across multiple chunk methods so no single method exceeds the bytecode limit. For 2D arrays (jjnextStateSet, jjcompositeState), flatten into contiguous 1D arrays with offset/length accessors, eliminating both the problem and the per-row object header overhead.
New file: JavaArrayHelper.java
Reusable utility for emitting chunked int[], String[] and flattened
int[][] array initializers via _init() methods.
Modified: TokenManagerCodeGenerator.java
Six arrays now emitted via JavaArrayHelper:
Modified: TokenManagerDriver.template
Two lines changed to use generated _row() accessors for the
flattened 2D arrays (jjcompositeState_row, jjnextStateSet_row).
Backward compatible: generated parser is functionally identical. Tested with JSqlParser (500+ keywords, 500+ productions).
Fixes javacc/javacc-8-core#3