If this project saved you some time or made your day a little easier, a star would mean a lot — it helps others find it too.
Fork of JavaCC 7.0.3 because the original code base has poor quality and PRs were not really merged. The overall goal is to maintain compatibility to JavaCC but
- The code itself should be better maintainable
- The code itself should conform to best-practices
- Because this is NOT JavaCC the class names are similar, but the base package name changed from
net.javacctocom.helger.pgcc - The created code requires at least Java 1.8 by default (
JDK_VERSION, values from 1.5 upwards are accepted)
See https://github.com/phax/ph-javacc-maven-plugin/ for a Maven plugin that uses this CC.
This fork is not really actively maintained, except some severe problems arise. I mainly use it to power my ph-css CSS parser.
Add the following to your pom.xml to use this artifact (replacing x.y.z with the actual version number):
<dependency>
<groupId>com.helger</groupId>
<artifactId>parser-generator-cc</artifactId>
<version>x.y.z</version>
</dependency>docs/internals/- how the generator works: the pipeline, the generator state, the template language and the bootstrap loopwww/doc/- the JavaCC language reference
Controls which CharStream implementation is generated for Java:
simple(default) -SimpleCharStreamon top ofAbstractCharStream, reading the input into an internal circular buffer that is relocated and doubled for tokens larger than the buffer.charsequence-CharSequenceCharStream, keeping the whole input in memory and reading directly from it. There is no buffer, so token length is never limited by a buffer size and no buffer relocation ever takes place. Line and column numbers are calculated on demand instead of being recorded for every single character.
The generated parser gets an additional CharSequence based constructor and ReInit method with
charsequence. Restrictions:
- Not available in combination with
JAVA_UNICODE_ESCAPE=true-JavaCharStreamis used instead and a warning is emitted. - The input is read completely up front, so an
IOExceptionof the underlyingReadersurfaces as anIllegalStateExceptionin the constructor and the input may not exceedInteger.MAX_VALUEcharacters. adjustBeginLineColumnis not available because line and column numbers are not recorded per character.
Everything below is a source level change to code that drives the generator. Grammar files and
generated parsers are unaffected: .jj / .jjt syntax is unchanged, and the generated parser still
exposes token.kind, t.image, the jj_ and trace_ methods under their old names.
Most users consume this through ph-javacc-maven-plugin and need to change nothing but the plugin version.
| 2.x | 3.0 |
|---|---|
com.helger.pgcc.parser.LexGenJava |
com.helger.pgcc.output.java.LexGenJava |
com.helger.pgcc.parser.ParseGenJava |
com.helger.pgcc.output.java.ParseGenJava |
com.helger.pgcc.parser.LexGenCpp |
com.helger.pgcc.output.cpp.LexGenCpp |
com.helger.pgcc.parser.ParseGenCPP |
com.helger.pgcc.output.cpp.ParseGenCpp |
com.helger.pgcc.output.cpp.OtherFilesGenCPP |
com.helger.pgcc.output.cpp.OtherFilesGenCpp |
com.helger.pgcc.parser.CodeGenerator |
com.helger.pgcc.parser.AbstractCodeGenerator (now abstract) |
com.helger.pgcc.parser.NormalProduction |
com.helger.pgcc.parser.AbstractNormalProduction |
com.helger.pgcc.parser.JavaCCParserInternals |
com.helger.pgcc.parser.AbstractJavaCCParserInternals |
com.helger.pgcc.EJDKVersion |
com.helger.base.system.EJavaVersion (from ph-commons) |
com.helger.pgcc.parser no longer contains anything that writes a file. The C++ generators do not
extend the Java ones any more: LexGenCpp and LexGenJava share
com.helger.pgcc.output.AbstractLexGenJavaLike, and ParseGenCpp extends AbstractCodeGenerator
directly.
Removed without replacement: ParserData, parser.table.TokenManagerCodeGenerator and
parser.table.TableDrivenJavaCodeGenerator - the table driven token manager and the two
undocumented options TOKEN_MANAGER_CODE_GENERATOR and PARSER_CODE_GENERATOR are gone.
The generator keeps one state object per run and per thread in com.helger.pgcc.context.PGCCContext,
so two generator runs can happen at the same time in one JVM. Options, JavaCCErrors and
JavaCCGlobals are still used exactly as before, but the public static fields of JavaCCGlobals are
now reached through grammar ():
| 2.x | 3.0 |
|---|---|
JavaCCGlobals.s_fileName |
grammar ().getFileName () |
JavaCCGlobals.s_jjtreeGenerated |
grammar ().isJJTreeGenerated () |
JavaCCGlobals.s_toolNames |
grammar ().getToolNameList () |
JavaCCGlobals.s_cu_name |
grammar ().getParserName () |
JavaCCGlobals.s_token_mgr_decls |
grammar ().getTokenMgrDecls () |
JavaCCGlobals.s_tokenCount |
grammar ().getTokenCount () |
JavaCCGlobals.s_cline / s_ccol |
grammar ().getCurrentLine () / getCurrentColumn () |
s_origFileName is gone. JavaCCErrors.reInit () is gone - Main.reInitAll () drops the whole
context instead.
The public and protected snake_case methods were renamed; the jj_ and trace_ methods of
generated parsers keep their names, because grammar action code calls them.
| 2.x | 3.0 | on |
|---|---|---|
parse_error |
parseError |
JavaCCErrors |
semantic_error |
semanticError |
JavaCCErrors |
add_inline_regexpr |
addInlineRegexpr |
AbstractJavaCCParserInternals |
add_token_manager_decls |
addTokenManagerDecls |
AbstractJavaCCParserInternals |
character_descriptor_assign |
characterDescriptorAssign |
AbstractJavaCCParserInternals |
remove_escapes_and_quotes |
removeEscapesAndQuotes |
AbstractJavaCCParserInternals |
set_initial_cu_token |
setInitialCuToken |
AbstractJavaCCParserInternals |
gen_CharStream |
genCharStream |
FilesJava, FilesCpp |
gen_ParseException |
genParseException |
FilesJava, FilesCpp |
gen_Token |
genToken |
FilesJava, FilesCpp |
gen_TokenManager |
genTokenManager |
FilesJava, FilesCpp |
gen_TokenMgrError |
genTokenMgrError |
FilesJava, FilesCpp |
gen_AbstractCharStream |
genAbstractCharStream |
FilesJava |
gen_CharSequenceCharStream |
genCharSequenceCharStream |
FilesJava |
gen_JavaCharStream |
genJavaCharStream |
FilesJava |
gen_SimpleCharStream |
genSimpleCharStream |
FilesJava |
gen_JavaModernFiles |
genJavaModernFiles |
FilesJava |
gen_ErrorHandler |
genErrorHandler |
FilesCpp |
gen_JavaCCDefs |
genJavaCCDefs |
FilesCpp |
generateDefaultVisitor_java |
generateDefaultVisitorJava |
NodeFilesJava |
generateTreeConstants_java |
generateTreeConstantsJava |
NodeFilesJava |
generateVisitor_java |
generateVisitorJava |
NodeFilesJava |
generateTreeState_java |
generateTreeStateJava |
JJTreeStateJava |
create_output_stream |
createOutputStream |
BNFGenerator |
BNFGenerator.get_id was removed.
| 2.x | 3.0 |
|---|---|
JavaCCErrors.parse_error (Object, String) |
parseError (IGrammarLocation, String) |
JavaCCErrors.semantic_error (Object, String) |
semanticError (IGrammarLocation, String) |
JavaCCErrors.warning (Object, String) |
warning (IGrammarLocation, String) |
Options.setInputFileOption (Object, ...) |
takes IGrammarLocation |
Options.getJdkVersion () returns EJDKVersion |
returns com.helger.base.system.EJavaVersion |
Container holding Object |
Container <T>, typed getMember () / setMember (T) |
com.helger.pgcc.parser.IGrammarLocation extends com.helger.base.location.ILocation and is
implemented by AbstractNormalProduction, TokenProduction, Expansion, ICCCharacter and both
Token classes - the six types the old instanceof cascade tested for.
On AbstractNormalProduction, TokenProduction, Expansion, ICCCharacter and both Token
classes:
| 2.x | 3.0 |
|---|---|
getLine () / setLine (int) |
getLineNumber () / setLineNumber (int) |
getColumn () / setColumn (int) |
getColumnNumber () / setColumnNumber (int) |
Nfa and the two carriers inside TokenizerData are records, so their fields are accessors:
TokenizerData.NfaState.m_aCharacters reads characters (), and likewise index (),
nextStates (), compositeStates () and kind ().
JavaCCLauncher, JJTreeLauncher and JJDocLauncher in com.helger.pgcc.main are the properly
named entry points. The lower case javacc, jjtree and jjdoc classes still work but are
deprecated.
- The default of
JDK_VERSIONmoved from1.5to1.8, so generated code uses theCharsetbased constructors and the diamond operator unless you set it back. PARSER_SUPER_CLASSandTOKEN_MANAGER_SUPER_CLASSnow warn when set with a Java target - they are read by the C++ backend only and were silently ignored before.TOKEN_MANAGER_SUPERCLASSis accepted and ignored; the option that works isTOKEN_MANAGER_SUPER_CLASS.- Regenerating into a directory that already contains generated files now actually rewrites them. The staleness checksum was computed before the writer was flushed, so it never matched. Hand edited files are still protected.
v3.0.0 - 2026-09-09
- Breaking API change
Containeris generic -Container <T>with a typedgetMember ()andsetMember (T)instead ofObject. The grammar passes it as an out parameter through nine productions; they are typedContainer<Expansion>for the BNF and regular expression chain andContainer<ICCCharacter>for the character descriptors, which are an unrelated hierarchy. 17 of the 37 casts ongetMember ()inJavaCC.jjare gone, plus one inmakeTryBlock. The remaining 19AbstractExpRegularExpressioncasts stay becauseexpansion_unithands itsContainer<Expansion>toregular_expression, and generics are invariant - that pins the whole regular expression chain toExpansion - The code generators resolve
lexer (),grammar (),tokenizerBuild ()andoptionValues ()into a local variable instead of calling them once per use. Each call is aThreadLocallookup, and they sat in the innermost loops -LexGenJava.startalone made 184 of them, 175 inside loops, andLexGenCpp.start157. 1069 calls across 35 methods became 35 locals; generatinggrammars/JavaCC.jjdrops from 13.3 ms to 11.3 ms andgrammars/CobolParser.jjfrom 20.2 ms to 17.0 ms (best of 25 runs after 8 warm ups). Generated output is unchanged - The remaining
instanceoftests that were followed by a cast use pattern matching now, inParseEngine,Semanticize,ExpRCharacterList,ExpRChoice,ExpRStringLiteral,JJDoc,LexGenCppandOptions.LexGenCpphad three casts oflexer ().getCurRE ()in one condition where the Java backend already had one binding, so the two backends read alike again. This also removes a latentClassCastExceptioninOptions.setInputFileOption, which testedaObject instanceof Integerbut castaRealSrc; only&&short circuiting kept it unreachable, because the grammar can produce aList<String>but never aList<Integer>. The action blocks inJavaCC.jjandConditionParser.jjkeep their casts on purpose - the Java grammar the generator parses them with has no production forinstanceof Type name - The reworked classes declare their members in one consistent order: nested types, then the fields, then the constructor, then the instance methods, with the static factory methods last.
PGCCContext.current (),PGCCContext.reset ()andProcessState.getInstance ()moved to the end of their class, matchingLookaheadState.current (), andTokenizerData's three nested types moved above the fields whose types they are. Pure reordering; no API and no behaviour change - Generating a large lexer is around 3x faster. The epsilon closure walked the whole state list twice per call purely to record which states a pass had visited, which is quadratic in the token count; the passes are numbered now and the walks are gone. On a synthetic 1280 token grammar that loop ran 690 million times and was 70% of the run, and generation drops from 1344 ms to 413 ms. Generated output is unchanged
- Every public and protected member of the generator carries javadoc now, and
mvn javadoc:javadocreports no warnings. Writing it up turned up 16 members with no caller left and two option constants that were never registered, all removed.TOKEN_MANAGER_SUPERCLASSis documented as accepted and ignored - the option that works isTOKEN_MANAGER_SUPER_CLASS - Fixed the generated C++ token manager not compiling for a grammar with
'or\in a string literal. The switch over the current character gotcase ''':andcase '\':, because only the Java backend escaped those two characters in a case label - Fixed two token manager debug messages in the generated C++ running into the following line, and one being indented outside the
ifthat guards it.DEBUG_TOKEN_MANAGERonly - Breaking API change Replaced the internal
EJDKVersionenum withEJavaVersionfrom ph-commons, so thatJDK_VERSIONvalues above 14 are supported.Options.getJdkVersion ()returnscom.helger.base.system.EJavaVersionnow - Potentially breaking The default value of
JDK_VERSIONmoved from1.5to1.8, so that generated code uses theCharsetbased constructors and the diamond operator unless configured otherwise - Breaking API change
LexGenJava,ParseGenJava,LexGenCppandParseGenCppmoved fromcom.helger.pgcc.parsertocom.helger.pgcc.output.javaandcom.helger.pgcc.output.cpp, so that the package says which target language a class writes.com.helger.pgcc.parserno longer contains anything that writes a file - Breaking API change The generator state moved from static fields into
com.helger.pgcc.context.PGCCContext, one instance per run and per thread. The old classes remain as facades, soOptions,JavaCCErrorsandJavaCCGlobalsare used exactly as before, butJavaCCGlobalsexposes the grammar throughgrammar ()instead of public static fields. Two generator runs can now happen at the same time in one JVM - Added
JavaCCLauncher,JJTreeLauncherandJJDocLauncheras properly named command line entry points; the lower casejavacc,jjtreeandjjdocclasses remain as deprecated aliases - Fixed generated files never being rebuilt when regenerating into a directory that already contains them. The checksum that decides this was computed before the writer had been flushed, so for anything but a very large file it was the checksum of nothing and never matched. Hand edited files are still protected, as intended
- Fixed
JavaCCGlobals.getToolNamesthrowing aNullPointerExceptioninstead of returning an empty list when the file does not exist - Fixed
JDK_VERSIONvalues above 14 silently falling back to the default - Breaking Removed the undocumented and untested
TOKEN_MANAGER_CODE_GENERATORandPARSER_CODE_GENERATORoptions together with the table driven token manager behind them - Removed the dead
test/(upstream Ant build) anddocs/directories, and trimmedwww/doc/to the reference pages - Fixed
OUTPUT_LANGUAGE(and every other option with an indirect effect) being ignored when set on the command line instead of in the grammar file - Fixed the JJDoc
-BNFoutput dropping every terminal from the productions, so that<NUMBER> ( <PLUS> <NUMBER> )* <EOF>was written as( )* <EOF> - Fixed JJTree carrying node types from one run into the next when several grammars are processed in the same JVM, so that the second grammar's output contained the first grammar's node classes. The C++ node files were affected most visibly
- Fixed
JavaCCInterpreterfailing on the first character of any input for grammars with more than one character class token. The composite state the tokenizer starts in had no entry in theTokenizerData, so the NFA was skipped entirely. Only the interpreter is affected; generated code never used this path - Fixed
JavaCCInterpreterlosing the characters aMOREproduction consumed, so that a token assembled across a lexical state switch reported only its last piece - a string literal came out as its closing quote - Breaking API change No
staticnon final field is left in the code base. The last per run collections -ASTNodeDescriptor's node tables andJJTreeGlobals.TOOL_LIST- moved intoPGCCContext, and the two genuinely process wide settings moved to the newcom.helger.pgcc.context.ProcessState.PGPrinter.initandFilesJava.setReadFromClassPathare unchanged - Fixed a
NullPointerExceptionwhen settingPARSER_SUPER_CLASSorTOKEN_MANAGER_SUPER_CLASSon the command line. They are the only two options with anulldefault, so there was no existing value to take the expected type from. Setting them in the grammar file always worked PARSER_SUPER_CLASSandTOKEN_MANAGER_SUPER_CLASSnow warn when set with a Java target. Both are read by the C++ backend only and were silently ignored otherwise- Fixed the
jjtreehelp output advertisingJDK_VERSION (default "1.5")andOUTPUT_DIRECTORY (default ""), neither of which was the actual default - Removed a leftover debug line that made
jjtreeprintopt:javaon every run - Local variables and parameters throughout the code base now use the project's Hungarian notation.
The public fields of
Tokenkeep their names - generated parsers and grammar action code readtoken.kindandt.image - Breaking API change
JavaCCErrors.parse_error,semantic_errorandwarningtake acom.helger.pgcc.parser.IGrammarLocationinstead of anObject. The new interface extendscom.helger.base.location.ILocationand is implemented byNormalProduction,TokenProduction,Expansion,ICCCharacterand bothTokenclasses - the six types the oldinstanceofcascade tested for.Options.setInputFileOptiontakes it too - Breaking API change The grammar model spells its position the ph-commons way:
getLineNumber ()/getColumnNumber ()andsetLineNumber ()/setColumnNumber ()onNormalProduction,TokenProduction,Expansion,ICCCharacterand bothTokenclasses.IGrammarLocationis nowILocationplus the resource id - Breaking API change Renamed the two abstract classes that did not say so:
NormalProductionisAbstractNormalProductionandJavaCCParserInternalsisAbstractJavaCCParserInternals - Breaking API change
Nfaand the two carriers insideTokenizerDataare records.TokenizerData.NfaState.m_aCharactersand friends are accessors now, so they readcharacters () - JJDoc's HTML output is HTML5 instead of HTML 3.2.
Lower case tags,
<meta charset>,idanchors instead of<a name>, and a small default stylesheet in place of theALIGNandVALIGNattributes - a stylesheet given with theCSSoption is linked after it and still wins. Token productions with nothing to show no longer leave an empty table row behind - The generated
CharStreamandAbstractCharStreamare fully documented.javadocreported 28 warnings on them and now reports none, so a project that runsjavadocover its generated parser no longer inherits them. The parameternewColofadjustBeginLineColumnisnNewCol - Generation of grammars whose tokens are built from character classes is about three times faster.
The NFA construction was resolving the
ThreadLocalthat holds the run's state once per element rather than once per call - in one case for every state, for every state - Breaking API change Method names use camel case throughout:
JavaCCErrors.parse_errorisparseError,semantic_errorissemanticError,FilesJava.gen_TokenisgenTokenand so on for 27 names. Thejj_andtrace_methods of generated parsers keep their names - grammar action code calls them - Breaking API change
CodeGeneratorisAbstractCodeGeneratorand is abstract - nothing outside the tests ever instantiated it. The two C++ only methods it carried,genStringLiteralArrayCPPandgenStringLiteralInCPP, moved intoLexGenCpp- their only caller - as_genStringLiteralArrayInCppand_genStringLiteralInCpp - Breaking API change The C++ generators no longer extend the Java ones.
LexGenCppandLexGenJavashare the newcom.helger.pgcc.output.AbstractLexGenJavaLike, andParseGenCppextendsAbstractCodeGeneratordirectly - it inherited nothing fromParseGenJavaat all - Breaking API change Removed
JavaCCErrors.reInit (), deprecated since the error counters moved intoPGCCContext
v2.0.3 - 2026-09-08
- Added the new option
JAVA_CHAR_STREAM_TYPEthat allows to generate aCharSequenceCharStreamthat needs no internal buffer at all (issue #21) - Fixed the tool names in the
Generated by:header not being trimmed, so that a parser generated by JavaCC from a JJTree generated grammar did not reset the JJTree state in itsReInitmethods (issue #45)
v2.0.2 - 2026-09-08
- Removed OSGI bundling
- Fixed
JavaCharStreamreusing the inheritedmaxNextCharIndfield for its raw input buffer, leading toArrayIndexOutOfBoundsExceptionor silently altered characters withJAVA_UNICODE_ESCAPE=true- thanks to @wilx - Fixed
AbstractCharStream.expandBuffnot updatingmaxNextCharIndwhen relocating token data, leading to NUL gaps inSimpleCharStreamfor nonzero token starts - thanks to @wilx
v2.0.1 - 2025-11-16
- Updated to ph-commons 12.1.0
- Using JSpecify annotations
v2.0.0 - 2025-09-19
- Using Java 17 as the baseline
- Updated to ph-commons 12
v1.1.4 - 2022-01-10
- Updated to ph-commons 10
- Java non-modern style no longer creates constructors without a Charset. See issue #29 - thanks @sfuhrm
- Improved the code of the
jj_ntk_fmethod to be more efficient
v1.1.3 - 2020-05-13
- Allow
finalwhen catching exceptions - issue #24 - Changed Automatic-Module-Name to
com.helger.pgcc - Fixed internal buffer corruption in generated code - issue #26
v1.1.2 - 2019-05-02
- JavaCC grammar can parse Java 7 language features (JavaCC PR 71)
- Backported a CPP output fix from JavaCC
- Fixed an error in
JavaCharStream.templateifKEEP_LINE_COLUMNis turned off
v1.1.1 - 2019-01-28
- Fixed an error in Java modern template
SimpleCharStream- thanks to @nbauma109
v1.1.0 - 2018-10-25
- Focus is on improving the quality and consistency of the template files - this may cause interoperability problem because names change etc.
- This version assumes that the created code uses at least Java 1.5 - JDK versions below 1.5 are no longer supported!
- The option
STATICwas removed - it caused too many variations in the templates which decreases maintainability. STATIC is now alwaysfalse! - Added new option
OUTPUT_ENCODINGto define the character set for the output files - If JDK version is at least 1.6 than
java.nio.Charset encodingis used and notString encodingin generated Streams. - The Java templates were modified so that the interface methods start with a lowercase character (
beginTokeninstead ofBeginToken) - the created code may need to be adopted! - A masking issue for
'and\characters was resolved (issue #20)
v1.0.2 - 2018-01-08
- Fixed an error in jump-patching that was originally only considered if legacy exception handling was enabled - now ParserGeneratorCC can create itself using itself!
v1.0.1 - 2018-01-05
- Initial release with expected output compatibility to JavaCC 7.0.3
- The JavaCC option
GENERATE_STRING_BUILDERwas removed - it was never evaluated - The JavaCC option
LEGACY_EXCEPTION_HANDLINGwas removed - that was too much 1990 ;) - see issue #7. This implies that the classTokenMgrErroris no longer available! - The JavaCC option
GENERATE_CHAINED_EXCEPTIONwas replaced with deduction from the Java version (≥ 1.4) - The JavaCC option
GENERATE_GENERICSwas replaced with deduction from the Java version (≥ 1.5) - The JavaCC option
GENERATE_ANNOTATIONSwas replaced with deduction from the Java version (≥ 1.5) - The main applications previously located in the root packaged were moved to package
com.helger.pgcc.main - Minor improvements for Java output if JDK level is ≥ 1.7
- https://github.com/phax/ph-javacc-maven-plugin/ starting from v4 will use this package instead of JavaCC.
- No pure
RuntimeExceptionorErrorclasses are thrown inside the code
v1.0.0 - 2018-01-05 - had a regression and was therefore never released binary
My personal Coding Styleguide | It is appreciated if you star the GitHub project if you like it.