If I call:
java org.antlr.Tool -o outdir sources/com/example/Jav开发者_运维技巧a5.g
...with antlr-3.1.3 the parser and lexer code will be generated in the directory outdir/sources/com/example
. But the generated classes don't have any package
statement. I need them to life in the package com.example
.
Is there a way to specify the target package?
ANTLR provides a header tool which allows you to include package and imports. You include this in your *.g grammar file:
@header {
package org.xmlcml.cml.converters.antlr;
import java.util.HashMap;
}
And you may need it in the Lexer as well:
@lexer::header {package org.xmlcml.cml.converters.antlr;}
and in case you need to add some members and code:
@members {
HashMap<String, Object> objectMap = new HashMap<String, Object>();
//...
private void addArrayValue(String content) {
//... code required by snippets in the grammar
}
}
An old question with a perfectly good answer, but since the comment on the question asked for a command line option (and that was what I was actually searching for when I got here), I thought I'd just chime in and say the following...
You can specifiy the package on the command line if you are using ANTLR 4. I checked and it seems to not be there in version 3 so the other answer is the way to 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 -package
option at ANTLR Tool Command Line Options for more information.
It may have changed in more recent versions.
I'm working on a DSL for a Savantly game service, and
I place my grammar files in subfolders.
The generated classes are in a package corresponding to the folder structure.
My plugin configuration 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 structure -
精彩评论