Search code examples
javaeclipseantlrantlrworks

Why is my ANTLR grammar file for Java not compiling?


I have been given an ANTLR grammar for a subset of the Java compiler known as the static Java compiler. I am trying to extend the grammar to include more of Java's features, for instance, I just added the grammar for For Loops.

Using Eclipse and an ANTLR plugin, I then did 'Compile ANTLR grammar'. Instead of compiling it produced two errors on the first bit of code:

grammar ExtendedStaticJava;

options { backtrack=true; memoize=true; }

@header
{
package sjc.parser.extended;
import java.math.BigInteger;

/**
 * Extended StaticJava parser.
 * @author <myname>
 */
}

// the rest of the grammar has been excluded.

The first error is on line 1: 'Unexpected Token: grammar' The second error is on line 5: 'Unexpected char: @'

Why does it not recognize this basic ANTLR syntax? My first thought was that I was missing something in the classpath, but I went to the project's properties and made sure that the following JARs were included under Libraries:

  • antlr-2.7.7.jar
  • stringtemplate-3.2.1.jar
  • antlr.jar
  • antlr-runtime-3.0.1.jar

Any ideas or suggestions?


Solution

  • antlr-2.7.7.jar is wrong: your grammar is in ANTLR v3+ syntax. Remove all:

    • antlr-2.7.7.jar
    • stringtemplate-3.2.1.jar
    • antlr.jar
    • antlr-runtime-3.0.1.jar

    from your project/classpath and only stick this ANTLR v3 JAR in it (which contains everything you need: runtime, stringtemplate, the works!).

    Good luck!


    EDIT

    Personally, I do my IDE integration with an Ant build script. I generate a lexer and parser like this:

    <target name="generate.parser" depends="init" description="Generates the lexer, parser and tree-walker from the grammar files.">
        <echo>Generating the lexer and parser...</echo>
        <java classname="org.antlr.Tool" fork="true" failonerror="true">
            <arg value="-fo" />
            <arg value="${main.src.dir}/${parser.package}" />
            <arg value="${parser.grammar.file}" />
            <classpath refid="classpath" />
        </java>
        <!-- snip -->
    </target>
    

    and the classpath refid looks like:

    <path id="classpath">
        <!-- snip -->
        <fileset dir="lib">
            <include name="*.jar" />
        </fileset>
    </path>
    

    and the lib/ directory contains the ANTLR v3 JAR (no other ANTLR JARs! (sorry for hammering on that :)))