[ACCEPTED]-How to specify a target package for ANTLR?-antlr

Accepted answer
Score: 74

ANTLR provides a header tool which allows 5 you to include package and imports. You 4 include this in your *.g grammar file:

@header {
    package org.xmlcml.cml.converters.antlr;
    import java.util.HashMap;
}

And 3 you may need it in the Lexer as well:

@lexer::header {package org.xmlcml.cml.converters.antlr;}

and 2 in case you need to add some members and 1 code:

@members {
    HashMap<String, Object> objectMap = new HashMap<String, Object>();
    //...

    private void addArrayValue(String content) {
    //... code required by snippets in the grammar

    }
}
Score: 29

An old question with a perfectly good answer, but 10 since the comment on the question asked 9 for a command line option (and that was 8 what I was actually searching for when I 7 got here), I thought I'd just chime in and 6 say the following...

You can specifiy the 5 package on the command line if you are using 4 ANTLR 4. I checked and it seems to not be there 3 in version 3 so the other answer is the way to 2 go for ANTLR 3.

Here is an example:

java -cp antlr-4.4-complete.jar org.antlr.v4.Tool -package my.package MyGram.g4

See the 1 -package option at ANTLR Tool Command Line Options for more information.

Score: 0

It may have changed in more recent versions.
I'm 6 working on a DSL for a Savantly game service, and I 5 place my grammar files in subfolders. The 4 generated classes are in a package corresponding 3 to the folder structure.

My plugin configuration 2 looks like this -

<plugin>
    <groupId>org.antlr</groupId>
    <artifactId>antlr4-maven-plugin</artifactId>
    <version>${antlr.version}</version>
    <configuration>
        <sourceDirectory>${basedir}</sourceDirectory>
        <includes>
           <include>**/*.g4</include>
        </includes>
        <visitor>true</visitor>
        <listener>true</listener>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>antlr4</goal>
            </goals>
        </execution>
    </executions>
</plugin>

And the resulting folder 1 structure -

enter image description here

More Related questions