JavaCC - a parser generator for building parsers from grammars. It can generate code in Java, C++ and C#.

Overview

JavaCC

Maven Central Javadocs

Java Compiler Compiler (JavaCC) is the most popular parser generator for use with Java applications.

A parser generator is a tool that reads a grammar specification and converts it to a Java program that can recognize matches to the grammar.

In addition to the parser generator itself, JavaCC provides other standard capabilities related to parser generation such as tree building (via a tool called JJTree included with JavaCC), actions and debugging.

All you need to run a JavaCC parser, once generated, is a Java Runtime Environment (JRE).

This README is meant as a brief overview of the core features and how to set things up to get yourself started with JavaCC. For a fully detailed documentation, please see https://javacc.github.io/javacc/.

Contents

Introduction

Features

  • JavaCC generates top-down (recursive descent) parsers as opposed to bottom-up parsers generated by YACC-like tools. This allows the use of more general grammars, although left-recursion is disallowed. Top-down parsers have a number of other advantages (besides more general grammars) such as being easier to debug, having the ability to parse to any non-terminal in the grammar, and also having the ability to pass values (attributes) both up and down the parse tree during parsing.

  • By default, JavaCC generates an LL(1) parser. However, there may be portions of grammar that are not LL(1). JavaCC offers the capabilities of syntactic and semantic lookahead to resolve shift-shift ambiguities locally at these points. For example, the parser is LL(k) only at such points, but remains LL(1) everywhere else for better performance. Shift-reduce and reduce-reduce conflicts are not an issue for top-down parsers.

  • JavaCC generates parsers that are 100% pure Java, so there is no runtime dependency on JavaCC and no special porting effort required to run on different machine platforms.

  • JavaCC allows extended BNF specifications - such as (A)*, (A)+ etc - within the lexical and the grammar specifications. Extended BNF relieves the need for left-recursion to some extent. In fact, extended BNF is often easier to read as in A ::= y(x)* versus A ::= Ax|y.

  • The lexical specifications (such as regular expressions, strings) and the grammar specifications (the BNF) are both written together in the same file. It makes grammars easier to read since it is possible to use regular expressions inline in the grammar specification, and also easier to maintain.

  • The lexical analyzer of JavaCC can handle full Unicode input, and lexical specifications may also include any Unicode character. This facilitates descriptions of language elements such as Java identifiers that allow certain Unicode characters (that are not ASCII), but not others.

  • JavaCC offers Lex-like lexical state and lexical action capabilities. Specific aspects in JavaCC that are superior to other tools are the first class status it offers concepts such as TOKEN, MORE, SKIP and state changes. This allows cleaner specifications as well as better error and warning messages from JavaCC.

  • Tokens that are defined as special tokens in the lexical specification are ignored during parsing, but these tokens are available for processing by the tools. A useful application of this is in the processing of comments.

  • Lexical specifications can define tokens not to be case-sensitive either at the global level for the entire lexical specification, or on an individual lexical specification basis.

  • JavaCC comes with JJTree, an extremely powerful tree building pre-processor.

  • JavaCC also includes JJDoc, a tool that converts grammar files to documentation files, optionally in HTML.

  • JavaCC offers many options to customize its behavior and the behavior of the generated parsers. Examples of such options are the kinds of Unicode processing to perform on the input stream, the number of tokens of ambiguity checking to perform etc.

  • JavaCC error reporting is among the best in parser generators. JavaCC generated parsers are able to clearly point out the location of parse errors with complete diagnostic information.

  • Using options DEBUG_PARSER, DEBUG_LOOKAHEAD, and DEBUG_TOKEN_MANAGER, users can get in-depth analysis of the parsing and the token processing steps.

  • The JavaCC release includes a wide range of examples including Java and HTML grammars. The examples, along with their documentation, are a great way to get acquainted with JavaCC.

Example

This example recognizes matching braces followed by zero or more line terminators and then an end of file.

Examples of legal strings in this grammar are:

{}, {{{{{}}}}} // ... etc

Examples of illegal strings are:

{}{}, }{}}, { }, {x} // ... etc

Grammar

PARSER_BEGIN(Example)

/** Simple brace matcher. */
public class Example {

  /** Main entry point. */
  public static void main(String args[]) throws ParseException {
    Example parser = new Example(System.in);
    parser.Input();
  }

}

PARSER_END(Example)

/** Root production. */
void Input() :
{}
{
  MatchedBraces() ("\n"|"\r")* <EOF>
}

/** Brace matching production. */
void MatchedBraces() :
{}
{
  "{" [ MatchedBraces() ] "}"
}

Output

$ java Example
{{}}<return>
$ java Example
{x<return>
Lexical error at line 1, column 2.  Encountered: "x"
TokenMgrError: Lexical error at line 1, column 2.  Encountered: "x" (120), after : ""
        at ExampleTokenManager.getNextToken(ExampleTokenManager.java:146)
        at Example.getToken(Example.java:140)
        at Example.MatchedBraces(Example.java:51)
        at Example.Input(Example.java:10)
        at Example.main(Example.java:6)
$ java Example
{}}<return>
ParseException: Encountered "}" at line 1, column 3.
Was expecting one of:
    <EOF>
    "\n" ...
    "\r" ...
        at Example.generateParseException(Example.java:184)
        at Example.jj_consume_token(Example.java:126)
        at Example.Input(Example.java:32)
        at Example.main(Example.java:6)

Getting Started

Follow the steps here to get started with JavaCC.

This guide will walk you through locally building the project, running an existing example, and setup to start developing and testing your own JavaCC application.

Download & Installation

JavaCC 7.0.10 is our latest stable release.

All JavaCC releases are available via GitHub and Maven including checksums and cryptographic signatures.

For all previous releases, please see stable releases.

The GitHub 8.0 branch contains the next generation of JavaCC that splits the frontend -- the JavaCC parser -- from the backends -- the code generator targeted for Java, C++ &and C# --. Status of JavaCC is experimental and not production ready.

Installation

To install JavaCC, navigate to the download directory and type:

$ unzip javacc-7.0.10.zip
or
$ tar xvf javacc-7.0.10.tar.gz

Then place the binary javacc-7.0.10.jar in a new target/ folder, and rename to javacc.jar.

Once you have completed installation add the scripts/ directory in the JavaCC installation to your PATH. The JavaCC, JJTree, and JJDoc invocation scripts/executables reside in this directory.

On UNIX based systems, the scripts may not be executable immediately. This can be solved by using the command from the javacc-7.0.10/ directory:

chmod +x scripts/javacc

Building JavaCC from Source

The source contain the JavaCC, JJTree and JJDoc sources, launcher scripts, example grammars and documentation. It also contains a bootstrap version of JavaCC needed to build JavaCC.

Prerequisites for building JavaCC:

  • Git
  • Ant (we require version 1.5.3 or above - you can get ant from http://ant.apache.org)
  • Maven
  • Java 8 (Java 9 and 10 are not yet supported)
$ git clone https://github.com/javacc/javacc.git
$ cd javacc
$ ant

This will build the javacc.jar file in the target/ directory

Developing JavaCC

Minimal requirements for an IDE are:

  • Support for Java
  • Support for Maven with Java

IntelliJ IDEA

The IntelliJ IDE supports Maven out of the box and offers a plugin for JavaCC development.

Eclipse IDE

Community

JavaCC is by far the most popular parser generator used with Java applications with an estimated user base of over 1,000 users and more than 100,000 downloads to date.

It is maintained by the developer community which includes the original authors and Chris Ainsley, Tim Pizney and Francis Andre.

Support

Don’t hesitate to ask!

Contact the developers and community on the Google user group or email us at JavaCC Support if you need any help.

Open an issue if you found a bug in JavaCC.

For questions relating to development please join our Slack channel.

Documentation

The documentation of JavaCC is located on the website https://javacc.github.io/javacc/ and in the docs/ directory of the source code on GitHub.

It includes detailed documentation for JavaCC, JJTree, and JJDoc.

Resources

Books

  • Dos Reis, Anthony J., Compiler Construction Using Java, JavaCC, and Yacc., Wiley-Blackwell 2012. ISBN 0-4709495-9-7 (book, pdf).
  • Copeland, Tom, Generating Parsers with JavaCC., Centennial Books, 2007. ISBN 0-9762214-3-8 (book).

Tutorials

Articles

Parsing theory

  • Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers: Principles, Techniques, and Tools, 2nd Edition, Addison-Wesley, 2006, ISBN 0-3211314-3-6 (book, pdf).
  • Charles N. Fischer and Richard J. Leblanc, Jr., Crafting a Compiler with C., Pearson, 1991. ISBN 0-8053216-6-7 (book).

Powered by JavaCC

JavaCC is used in many commercial applications and open source projects.

The following list highlights a few notable JavaCC projects that run interesting use cases in production, with links to the relevant grammar specifications.

User Use Case Grammar File(s)
Apache ActiveMQ Parsing JMS selector statements SelectorParser.jj, HyphenatedParser.jj
Apache Avro Parsing higher-level languages into Avro Schema idl.jj
Apache Calcite Parsing SQL statements Parser.jj
Apache Camel Parsing stored SQL templates sspt.jj
Apache Jena Parsing queries written in SPARQL, ARQ, SSE, Turtle and JSON sparql_10, sparql_11, arq.jj, sse.jj, turtle.jj, json.jj
Apache Lucene Parsing search queries QueryParser.jj
Apache Tomcat Parsing Expression Language (EL) and JSON ELParser.jjt, JSONParser.jj
Apache Zookeeper Optimising serialisation/deserialisation of Hadoop I/O records rcc.jj
Java Parser Parsing Java language files java.jj

License

JavaCC is an open source project released under the BSD License 2.0. The JavaCC project was originally developed at Sun Microsystems Inc. by Sreeni Viswanadha and Sriram Sankar.



Top


Comments
  • minimumSize=1 generated for choice that contains child with zero size

    minimumSize=1 generated for choice that contains child with zero size

    Following code lines seem to cause lookahead problems:

    https://github.com/javacc/javacc/blob/ca275162a5d98d3bd4f2317efd9c19ad2144b5ef/src/main/java/org/javacc/parser/ParseEngine.java#L1377-L1381

    The minimum consumed size will be limited to at least 1 for a choice. As a result sometimes the lookahead is finished too early. E.g. consider an production:

    Syntax() -> {
      (
      LOOKAHEAD(2) 
      (<FOO> | {}) <BAR> <DUMMY>
      |
      <BAR> <BAR>
      )
    }
    

    If the input tokens is <BAR> <BAR>, apparently we should choose <BAR> <BAR> because of the lookahead for the former expansion is specified to 2. But with the code logic pasted above, the expansion [<FOO>] <BAR> will consume all the 2 lookahead count so that the generated parser code will never consider the token <DUMMY>. After all the former expansion will be chosen incorrectly. :(

    To me it is definitely like a bug so I have opened a PR #87. If it is something by design (which means we should always use lookahead=3 in the case) please let me know.

    opened by zhztheplayer 35
  • Add Gradle build scripts

    Add Gradle build scripts

    This is almost feature-complete, so feel free to try it out.

    See GitHub Actions CI here: https://github.com/vlsi/javacc/actions

    Overview

    This PR implements all the tasks that existed previously (in both Ant and Maven), and the PR adds lots of features:

    • Project loads to IDE automatically
    • Reproducible builds (the resulting jar, zip, and tar files are the same in case the same Java version is used)
    • Build script provides help for the command line
    • Code style is managed via Autostyle. For now, it trims trailing whitespace. It prints human-understandable messages on failures, and it provides a command to automatically fix violations.
    • Release to Central is just a couple of commands (prepareVote + publishDist)
    • JavaCC is incremental now. In other words, if a clas (or grammar) is changed, then one can launch ./gradlew test, and Gradle would build the jar before it starts testing

    CI

    GitHub Actions (Linux, macOS, Windows): https://github.com/vlsi/javacc/actions Travis (Linux): https://travis-ci.com/javacc/javacc/pull_requests

    Note: Travis builds with Java 8, and Java 11 fail for some reason. Java 8 gets blocked at test/javaFiles for some reason. Java 11 fails to download junit3 (it is probably Maven Central or Travis issue)

    Files to be removed as the build is migrated to Gradle

    Note: the migration makes Maven and some Ant files obsolete, so I would recommend to remove them, otherwise it would take significant time to maintain multiple build scripts.

    The last commit in the PR removes the files. If you want to compare how Ant or Maven build worked, then skip Remove redundant build files commit.

    • **/pom.xml, mvn.bat. Those files are obsolete
    • /build.xml fully (?) migrated to Gradle + part of it are moved to examples/build.xml and {examples,test}/build.gradle.kts
    • lib/**. Dependency management is migrated to Gradle, so lib is obsolete

    Testing JavaCC

    ./gradlew test builds the project, and launches all the tests.

    test and examples folders

    I would recommend to eventually migrate the tests to JUnit (or something like that). Current folder structure makes maintenance really complicated, so I would suggest to execute those folders via Ant (see ./gradlew :javacc-examples:antTest, and ./gradlew :javacc-test:antTest)

    Review pom files

    pom.xml are generated on the fly, and ./gradlew generatePom can be used to review the pom. It will generate the pom files to build/publications/*/pom*.xml

    Release to Central

    CI job (validates that publish to Central tasks work): https://github.com/vlsi/vlsi-release-plugins/runs/406605437

    Instructions: https://github.com/vlsi/vlsi-release-plugins/tree/master/plugins/stage-vote-release-plugin#making-a-release-candidate

    TL;DR:

    # -Pgh means "push to GitHub + Sonatype"
    # if -Pgh is omitted, then it would expect asflike-release-environment and push to localhost
    
    ./gradlew prepareVote -Prc=1 -Pgh # prepares a release candidate
    
    ./gradlew publishDist -Prc=1 -Pgh # promotes the candidate
    

    Note: there's a playground that launches mock implementations of Git and Nexus in a Docker container, so you can try how release works without pushing to real GitHub / Sonatype servers.

    fixes #141

    opened by vlsi 25
  • Is there a possibility to switch off tokens via options?

    Is there a possibility to switch off tokens via options?

    I have the need to build a parser for two different language versions. I want to avoid to build two parsers and have two grammar files. Using semantic Lookahead one is able to switch production on/off. The same would be nice for tokens.

    I tried token modes, but in reality, I have multiple options/flags that could be combined. Therefore this is not a valid way.

    As mentioned I would like to skip to build a parser for each of my options combinations.

    opened by wumpz 24
  • 8.0.0/cpp: SimpleNode is not generated anymore

    8.0.0/cpp: SimpleNode is not generated anymore

    Hi

    Be;low the classes generated by JavaCC 7.0.2

    Z:\git\SPLC\JJTree\VST>..\..\gradlew compileJJtree
    :JJTree:VST:compileJjtree
    Java Compiler Compiler Version 7.0.2 (Tree Builder)
    (type "jjtree" with no arguments for help)
    Reading from file Z:\git\SPLC\JJTree\VST\jjt\SPL.jjt . . .
    opt:c++
    File "Node.h" does not exist.  Will create one.
    File "SimpleNode.h" does not exist.  Will create one.
    File "SimpleNode.cc" does not exist.  Will create one.
    File "ASTDivNode.h" does not exist.  Will create one.
    File "ASTNENode.h" does not exist.  Will create one.
    File "ASTCompilationUnit.h" does not exist.  Will create one.
    File "ASTMulNode.h" does not exist.  Will create one.
    File "ASTIntConstNode.h" does not exist.  Will create one.
    File "ASTWriteStatement.h" does not exist.  Will create one.
    File "ASTBitwiseComplNode.h" does not exist.  Will create one.
    File "ASTBitwiseXorNode.h" does not exist.  Will create one.
    File "ASTOrNode.h" does not exist.  Will create one.
    File "ASTBitwiseAndNode.h" does not exist.  Will create one.
    File "ASTNotNode.h" does not exist.  Will create one.
    File "ASTGENode.h" does not exist.  Will create one.
    File "ASTId.h" does not exist.  Will create one.
    File "ASTTrueNode.h" does not exist.  Will create one.
    File "ASTAssignment.h" does not exist.  Will create one.
    File "ASTModNode.h" does not exist.  Will create one.
    File "ASTGTNode.h" does not exist.  Will create one.
    File "ASTSubtractNode.h" does not exist.  Will create one.
    File "ASTLTNode.h" does not exist.  Will create one.
    File "ASTBitwiseOrNode.h" does not exist.  Will create one.
    File "ASTLENode.h" does not exist.  Will create one.
    File "ASTReadStatement.h" does not exist.  Will create one.
    File "ASTEQNode.h" does not exist.  Will create one.
    File "ASTFalseNode.h" does not exist.  Will create one.
    File "ASTAddNode.h" does not exist.  Will create one.
    File "ASTVarDeclaration.h" does not exist.  Will create one.
    File "ASTAndNode.h" does not exist.  Will create one.
    File "ASTDivNode.cc" does not exist.  Will create one.
    File "ASTNENode.cc" does not exist.  Will create one.
    File "ASTCompilationUnit.cc" does not exist.  Will create one.
    File "ASTMulNode.cc" does not exist.  Will create one.
    File "ASTIntConstNode.cc" does not exist.  Will create one.
    File "ASTWriteStatement.cc" does not exist.  Will create one.
    File "ASTBitwiseComplNode.cc" does not exist.  Will create one.
    File "ASTBitwiseXorNode.cc" does not exist.  Will create one.
    File "ASTOrNode.cc" does not exist.  Will create one.
    File "ASTBitwiseAndNode.cc" does not exist.  Will create one.
    File "ASTNotNode.cc" does not exist.  Will create one.
    File "ASTGENode.cc" does not exist.  Will create one.
    File "ASTId.cc" does not exist.  Will create one.
    File "ASTTrueNode.cc" does not exist.  Will create one.
    File "ASTAssignment.cc" does not exist.  Will create one.
    File "ASTModNode.cc" does not exist.  Will create one.
    File "ASTGTNode.cc" does not exist.  Will create one.
    File "ASTSubtractNode.cc" does not exist.  Will create one.
    File "ASTLTNode.cc" does not exist.  Will create one.
    File "ASTBitwiseOrNode.cc" does not exist.  Will create one.
    File "ASTLENode.cc" does not exist.  Will create one.
    File "ASTReadStatement.cc" does not exist.  Will create one.
    File "ASTEQNode.cc" does not exist.  Will create one.
    File "ASTFalseNode.cc" does not exist.  Will create one.
    File "ASTAddNode.cc" does not exist.  Will create one.
    File "ASTVarDeclaration.cc" does not exist.  Will create one.
    File "ASTAndNode.cc" does not exist.  Will create one.
    File "SPLParserTree.h" does not exist.  Will create one.
    File "SPLParserTreeConstants.h" does not exist.  Will create one.
    File "SPLParserVisitor.h" does not exist.  Will create one.
    File "JJTSPLParserState.h" does not exist.  Will create one.
    File "JJTSPLParserState.cc" does not exist.  Will create one.
    Annotated grammar generated successfully in Z:\git\SPLC\JJTree\VST\gen\tmp\SPL.jj
    

    and below, the classes generated by JavaCC 8.0.0:

    Z:\git\SPLC\JJTree\VST>..\..\gradlew compileJJtree
    :JJTree:VST:compileJjtree
    Java Compiler Compiler Version 8.0.0 (Tree Builder)
    (type "jjtree" with no arguments for help)
    Warning: VISITOR_RETURN_TYPE option will be ignored since VISITOR is false
    Reading from file Z:\git\SPLC\JJTree\VST\jjt\SPL.jjt . . .
    File "Node.h" does not exist.  Will create one.
    File "SPLParserTree.h" does not exist.  Will create one.
    File "SPLParserTree.cc" does not exist.  Will create one.
    File "SPLParserTreeConstants.h" does not exist.  Will create one.
    File "SPLParserVisitor.h" does not exist.  Will create one.
    File "JJTSPLParserState.h" does not exist.  Will create one.
    File "JJTSPLParserState.cc" does not exist.  Will create one.
    Annotated grammar generated successfully in Z:\git\SPLC\JJTree\VST\gen\tmp\SPL.jj
    

    The SPL.jjt grammar: SPL.jjt.txt

    opened by zosrothko 15
  • Is it somehow possible to use this javacc jar to parse a jjt and jj file

    Is it somehow possible to use this javacc jar to parse a jjt and jj file

    I want to construct some tests depending on the tokens used in a specific rule of my grammar.

    void myrule() : {} {
    <K_MYKEYWORD1>
    | <K_MYKEYWORD2>
    }
    

    So I have a jjt file and need to transform this in a jj file and then parse this and get the AST - node tree, to traverse it.

    My first attempt was this:

    var parser = new JJTreeParser(
                    Files.newInputStream(Paths.get("src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt"))
    ) {
        public ASTGrammar getRoot() {
            return (ASTGrammar)jjtree.rootNode());
        }
    };
    parser.javacc_input();
    
    new JavaCodeGenerator().visit(parser.getRoot(), io);
    

    But I have to fight method and class visibility issues:

    IO is only package private, ASTGrammer.generate is package private as well.

    opened by wumpz 14
  • Use Gradle for the build

    Use Gradle for the build

    Hi,

    I see you have code movement in 8.0.0 branch, so I wonder what do you think of using Gradle as the build system?

    It makes lots of things simpler to do (e.g. when compared with Ant and Maven), it and it improves development experience.

    I've migrated Apache JMeter from Ant to Gradle, and Apache Calcite from Maven to Gradle. In both cases, it resulted in significant improvements when it comes to day-to-day development. In both cases, Gradle made it simpler to release new versions.

    opened by vlsi 12
  • Rename tag for

    Rename tag for "release" 6.1.3

    See this issue https://github.com/simonpoole/OpeningHoursParser/issues/72

    tl;dr Debian unstable switched to 6.1.3 this month, this causes a compile fail in a not totally unimportant downstream project included in Debian. The root cause seems to be down to the naming of the relevant tag, this could be avoided by renaming it.

    opened by simonpoole 11
  • Spaghetti code fix ?

    Spaghetti code fix ?

    Simple change to create "non nesting" logic. Existing solution created if (...) -> if (...) -> if (...) ->if (...) multiple nested construction. I stumbled on that when compiler raised error of too big level of if-nesting (JavaCC created nested logic higher than 256 if i remember correctly) ...

    opened by Risavk 11
  • Codegenerator implementation for C++

    Codegenerator implementation for C++

    One-to-one migration from the CppOutput to the C++ CodeGenerator. The CppOutput mechanism is still available for crosschecks. The next step is to remove all CPP parts from the core. Should we do the same for Java?

    opened by mbrigl 10
  • Fix annotations for JavaCharStream

    Fix annotations for JavaCharStream

    The same problem as in SimpleCharStream (fixed in #222) also occured in JavaCharStream, fixed in this PR. I was also able to add some tests to verify that the GWT-compatible templates now produce valid Java code with both stream implementations.

    opened by zbynek 8
  • Discuss: javax.tools.JavaCompiler or Janino for grammar tests

    Discuss: javax.tools.JavaCompiler or Janino for grammar tests

    See https://github.com/javacc/javacc/pull/143#issuecomment-578058816

    /cc @martinswanson

    A part of JavaCC testing complexity comes from the fact that it requires Java compiler to compile the generated grammar.

    The current tests are written in Ant build files, which makes it complicated to debug, understand, maintain, etc, etc.

    I suggest that most tests should be written like unit tests, so they can be executed from IDE.

    I see the following possibilities: A) javax.tools.JavaCompiler can be used since Java 1.6. That is the compiler can be accessed programatically. Then a test can first call JavaCC to generate the code, then test framework compiles it, then it executes it.

    B) https://github.com/janino-compiler/janino can probably be used as well. They have https://janino-compiler.github.io/janino/apidocs/org/codehaus/janino/JavaSourceClassLoader.html which enables to use Java source files as if it were compiled bytecode.

    C) Eclipse Compiler for Java (ECJ) is an option as well.

    D) https://github.com/google/compile-testing

    Any thoughts?

    opened by vlsi 8
  • Master vs Tag 7.0.12

    Master vs Tag 7.0.12

    Greetings.

    As promised I started to look into the deployment and documentation. Naturally, I would have expected the branch MASTER is the latest, however it points to 7.0.11-SNAPSHOT. Then there is a Tag 7.0.12 which points to 7.0.12 correctly. I do not see a DEVELOPMENT branch either.

    Am I misunderstanding something here? What branch will hold the latest changes and development?

    Suggestion:

    Would you accept a PR, which derives the actual Version from GIT Tags and updates the POM and the documentation accordingly?

    opened by manticore-projects 3
  • JDK_VERSION option possible values

    JDK_VERSION option possible values

    java -cp ~/Downloads/javacc.jar javacc -JDK_VERSION=1.8 -OUTPUT_DIRECTORY=~/Desktop/javacc -STATIC=false ~/Desktop/cypher.jj
    

    Using Java Compiler Compiler Version 7.0.5.

    Using -JDK_VERSION=8 makes no difference.

    The generated file Cypher.java contains List.of invocations which don't compile with Java 8.

    Cypher.java.txt cypher.jj.txt

    opened by asarkar 3
  • Small point

    Small point

    In the JavaCC.jj grammar, a CompilationUnit can have zero TypeDeclaration. But when so, JavaCC outputs an error : Parser class has not been defined between PARSER_BEGIN and PARSER_END.

    void CompilationUnit() :
    /*
     * The <EOF> is deleted since the compilation unit is embedded
     * within grammar code.
     */
    	{
    	  set_initial_cu_token(getToken(1));
    	}
    {
      [ LOOKAHEAD( ( Annotation() )* "package" ) PackageDeclaration() ]
      ( ImportDeclaration() )*
      ( TypeDeclaration() )*
    	{
              if (Options.isOutputLanguageJava()) {
    	    insertionpointerrors(getToken(1));
              }
    	}
    }
    
    opened by MarcMazas 0
  • Incorrect examples for MatchedBraces

    Incorrect examples for MatchedBraces

    Open: https://javacc.github.io/javacc/#example

    Observed:

    Examples of legal strings in this grammar are:
    
    {}, }}} // … etc
    

    Expected:

    Examples of legal strings in this grammar are:
    
    {}, {{{}}} // … etc
    

    I think there is an issue with the documentation processor, because the example is correct on GitHub:

    https://github.com/javacc/javacc/blob/master/docs/index.md#example

    opened by MasseGuillaume 0
  • Warning with no obvious reason

    Warning with no obvious reason

    In the following small grammar, we have a compile warning for which I see no reason. It looks to me it is a bug (well, I found this while building a very big set of test cases for JavaCC).. Any idea? TIA. Marc

    TOKEN :
    {
      < a : "a" >
    | < bB : "b" ("B")* >
    }
    
    int one_line() : {}
    {
      p1() p2() p3() ";" { return 0; }
    | ";"  { return 1; }
    }
    
    void p1() : {}
    { < ID1 : < bB > < a > > { System.out.println("got ID1"); } }
    
    // here we have a JJ compile warning: ... Regular Expression choice : bB can never be matched as : ID2
    // Why? We don't have it in p4() with the direct formulation nor in p3() when not single in the choice
    void p2() : {}
    { < ID2 : < bB > | "c" > { System.out.println("got ID2"); } }
    
    void p3() : {}
    { < ID3 : < bB > "!" | "c" > { System.out.println("got ID3"); } }
    
    void p4() : {}
    { < ID4 : "b" ("B")* | "c" > { System.out.println("got ID4"); } }
    

    Following is the remaining of the grammar, if someone wants to test. Running the test cases shows that the parser does not accept the input corresponding to the warning.

    options
    {
      static = true;
      UNICODE_INPUT = true; // (default false)
    
    }
    
    PARSER_BEGIN(QuickTests)
    
    public class QuickTests
    {
      public static void main(String args []) throws ParseException
      {
        QuickTests parser = new QuickTests(System.in);
        boolean done = false;
        while (!done)
        {
          System.out.println("Reading from standard input...");
          System.out.println("Ex1: babb!; / Ex2: babc; / Ex3: bacb!; / Ex4: bacc;");
          try
          {
            switch (QuickTests.one_line())
            {
              case 0 : 
              System.out.println("OK.");
              break;
              case 1 : 
              System.out.println("Goodbye.");
              done = true;
              break;
              default : 
              break;
            }
          }
          catch (Exception e)
          {
            System.out.println("NOK.");
            System.out.println(e.getMessage());
            QuickTests.ReInit(System.in);
          }
          catch (Error e)
          {
            System.out.println("Oops.");
            System.out.println(e.getMessage());
            break;
          }
        }
      }
    }
    
    PARSER_END(QuickTests)
    
    SKIP :
    {
      " "
    | "\t"
    | "\n"
    | "\r"
    }
    
    opened by MarcMazas 0
  • Unreachable statement while using modern templates

    Unreachable statement while using modern templates

    I just tried using javacc 7.0.10 on my javacc 6.0 code base using the modern template (primarily because I wanted to get TokenMgrException instead of TokenMgrError). Here is the JAVACC option that I used:

      JAVA_TEMPLATE_TYPE = "modern";
    

    After updating my .jj file for the expected things (e.g. Provider) I got an unexpected unreachable statement error from BNF productions that contain code similar to the following:

    private TableSpec.CrosstabSpec crosstab() :
    { TableSpec t1;
    String resel;
    int[] periods;
    ArrayList cats;
    }
    {
       t1=parse() resel=expression() periods=periods() cats=categories()
          {
             if (periods == null)
                throw new ParseException("Crosstab periods expression was null");
             return new TableSpec.CrosstabSpec(t1, resel, periods, cats);
          }
    }
    

    The generated code from this production is

      final private TableSpec.CrosstabSpec crosstab() throws ParseException {TableSpec t1;
    String resel;
    int[] periods;
    ArrayList cats;
        t1 = parse();
        resel = expression();
        periods = periods();
        cats = categories();
    if (periods == null)
                {if (true) throw new ParseException("Crosstab periods expression was null");}
             return new TableSpec.CrosstabSpec(t1, resel, periods, cats);
        throw new RuntimeException("Missing return statement in function");
    }
    

    I had a quick look around in the javacc source code and noticed that the unreachable throw statement is being injected at these lines in ParserGenerator. Apparently the jumpPatched flag is being set because the throw statement is being unconditionally jumpPatched.

    I had a look as to how the return statement is being handled, and it seem to be here in the javacc jj file. It looks like if not using legacy handling (which I specified to not use) then the return statement is not 'jumpPatched'.

    So perhaps there is something inconsistent about how 'throw' and 'return' are being 'jumpPatched'?

    Or do the modern templates expect something different here?

    Or are the modern templates not ready for prime time?

    opened by opeongo 1
Releases(javacc-7.0.12)
The fast scanner generator for Java™ with full Unicode support

JFlex JFlex is a lexical analyzer generator (also known as scanner generator) for Java. JFlex takes as input a specification with a set of regular exp

JFlex 500 Dec 18, 2022
uniVocity-parsers is a suite of extremely fast and reliable parsers for Java. It provides a consistent interface for handling different file formats, and a solid framework for the development of new parsers.

Welcome to univocity-parsers univocity-parsers is a collection of extremely fast and reliable parsers for Java. It provides a consistent interface for

univocity 874 Dec 15, 2022
cglib - Byte Code Generation Library is high level API to generate and transform Java byte code. It is used by AOP, testing, data access frameworks to generate dynamic proxy objects and intercept field access.

cglib Byte Code Generation Library is high level API to generate and transform JAVA byte code. It is used by AOP, testing, data access frameworks to g

Code Generation Library 4.5k Jan 8, 2023
A JNI code generator based on the JNI generator used by the eclipse SWT project

HawtJNI Description HawtJNI is a code generator that produces the JNI code needed to implement java native methods. It is based on the jnigen code gen

FuseSource 153 Nov 17, 2022
A fast JSON parser/generator for Java.

fastjson Fastjson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON str

Alibaba 25.1k Dec 31, 2022
A command line parser generator

jbock is a command line parser that works similar to airline and picocli. While most of these other tools scan for annotations at runtime, jbock is an

H90 73 Dec 13, 2022
ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files.

ANTLR v4 Build status ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating

Antlr Project 13.6k Dec 28, 2022
ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files.

ANTLR v4 Build status ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating

Antlr Project 13.6k Jan 3, 2023
Rekex parser generator - grammar as algebraic datatypes

Rekex PEG parser generator for Java 17 grammar as algebraic datatypes A context-free grammar has the form of A = A1 | A2 A1 = B C ... which looks ex

Zhong Yu 41 Dec 18, 2022
Nokogiri (鋸) is a Rubygem providing HTML, XML, SAX, and Reader parsers with XPath and CSS selector support.

Nokogiri Nokogiri (鋸) makes it easy and painless to work with XML and HTML from Ruby. It provides a sensible, easy-to-understand API for reading, writ

Sparkle Motion 6k Jan 8, 2023
Write parsers for arbitrary text inputs, entirely in Java, with no preprocessing phase

Read me first The license of this project is Apache 2.0. Requires Java 7 or later. The latest versions are: development: 2.1.0-beta.3; requires Java 8

Francis Galiegue 62 Oct 13, 2022
Build parsers in Java

jparsec Builds mini parsers in pure Java. Latest version: 3.0 (requires Java 8+) News 2016-12-05 Removed references to Codehaus in copyright and packa

null 324 Dec 31, 2022
Log4j-payload-generator - Log4j jndi injects the Payload generator

0x01 简介 log4j-payload-generator是 woodpecker框架 生产log4 jndi注入漏洞payload的插件。目前可以一键生产以下5类payload。 原始payload {[upper|lower]:x}类型随机混payload {[upper|lower]:x}

null 469 Dec 30, 2022
OpenApi Generator - REST Client Generator

Quarkus - Openapi Generator Welcome to Quarkiverse! Congratulations and thank you for creating a new Quarkus extension project in Quarkiverse! Feel fr

Quarkiverse Hub 46 Jan 3, 2023
Development Driven Testing (DDT) lets you generate unit tests from a running application. Reproduce a bug, generate a properly mocked test

DDTJ: It kills bugs DDT is the flip side of TDD (Test-driven development). It stands for "Development Driven Tests". Notice that it doesn’t contradict

null 4 Dec 30, 2021
Create your Java crypto trading bot in minutes. Our Spring boot starter takes care of exchange connections, accounts, orders, trades, and positions so you can focus on building your strategies.

Quick Start | Documentation | Discord | Twitter Create and run your java crypto trading bot in minutes Our Spring boot starter takes care of exchange

Cassandre 442 Jan 3, 2023
Java SQL (JDBC) code generator with GUI. SQL and OOP finally united.

jSQL-Gen Java SQL (JDBC) code generator with GUI. SQL and OOP finally united. Usage Install the latest release. Create a database, tables and their co

Osiris-Team 11 Nov 14, 2022
source code of the live coding demo for "Building resilient and scalable API backends with Apache Pulsar and Spring Reactive" talk held at ApacheCon@Home 2021

reactive-iot-backend The is the source code of the live coding demo for "Building resilient and scalable API backends with Apache Pulsar and Spring Re

Lari Hotari 4 Jan 13, 2022