50

If I call:

java org.antlr.Tool -o outdir sources/com/example/Java5.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?

tangens
  • 37,881
  • 18
  • 117
  • 136
  • On http://www.jguru.com/faq/view.jsp?EID=16185 they explain how to embed the package inside the grammar. But is there a way to specify it as command line parameter? – tangens Oct 31 '09 at 23:17

2 Answers2

74

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

    }
}
Brad Mace
  • 26,397
  • 17
  • 98
  • 144
peter.murray.rust
  • 36,369
  • 41
  • 146
  • 215
28

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.

Community
  • 1
  • 1
kmp
  • 10,215
  • 10
  • 72
  • 122
  • 1
    The "ANTLR Tool Command Line Options" documentation requires credentials to access. Here's an open documentation of antlr4: https://github.com/antlr/antlr4/blob/master/doc/index.md – EFreak Mar 18 '16 at 21:11
  • ANTLR Tool Command Line Options: https://github.com/antlr/antlr4/blob/master/doc/tool-options.md – EFreak Mar 18 '16 at 21:12
  • Thanks @EFreak - I adjusted the link in the question to your suggestion – kmp Mar 20 '16 at 15:13
  • 3
    any idea why this isn't exposed in the gradle plugin? – Groostav Mar 30 '16 at 07:53
  • 3
    In gradle you can append the argument to the `arguments` property of the `generateGrammarSource` task: `generateGrammarSource {arguments += ["-package", "my.package"]}` – Askin Geeks Nov 04 '16 at 22:25
  • 1
    For an Eclipse newbie... how does one find the generateGrammerSource property? – Ross Youngblood Jan 27 '17 at 17:40