Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a target package for ANTLR?

Tags:

java

antlr

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?

like image 735
tangens Avatar asked Oct 31 '09 22:10

tangens


People also ask

What languages use ANTLR?

While Version 3 supported generating code in the programming languages Ada95, ActionScript, C, C#, Java, JavaScript, Objective-C, Perl, Python, Ruby, and Standard ML, Version 4 at present targets C#, C++, Dart, Java, JavaScript, Go, PHP, Python (2 and 3), and Swift.

How does an ANTLR work?

ANTLR (ANother Tool for Language Recognition) is a tool for processing structured text. It does this by giving us access to language processing primitives like lexers, grammars, and parsers as well as the runtime to process text against them. It's often used to build tools and frameworks.

What does ANTLR stand for?

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


2 Answers

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      } } 
like image 172
peter.murray.rust Avatar answered Oct 01 '22 19:10

peter.murray.rust


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.

like image 20
kmp Avatar answered Oct 01 '22 19:10

kmp