java 如何为 ANTLR 指定目标包?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1655854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:27:02  来源:igfitidea点击:

How to specify a target package for ANTLR?

javaantlr

提问by tangens

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 packagestatement. I need them to life in the package com.example.

...使用 antlr-3.1.3,解析器和词法分析器代码将在目录中生成outdir/sources/com/example。但是生成的类没有任何package声明。我需要它们在包裹中存活com.example

Is there a way to specify the target package?

有没有办法指定目标包?

回答by peter.murray.rust

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

ANTLR 提供了一个头文件工具,允许您包含包和导入。您将其包含在 *.g 语法文件中:

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

And you may need it in the Lexer as well:

您可能也需要在 Lexer 中使用它:

@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

    }
}

回答by kmp

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 checkedand it seems to not be there in version 3 so the otheranswer is the way to go for ANTLR 3.

如果您使用的是 ANTLR 4,您可以在命令行上指定该包。我检查过,它似乎不在版本 3 中,所以另一个答案是 ANTLR 3 的方法。

Here is an example:

下面是一个例子:

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

See the -packageoption at ANTLR Tool Command Line Optionsfor more information.

-package在选择ANTLR工具命令行选项的详细信息。