ANTLR4 的最小示例 Gradle 项目是什么(带有 antlr 插件)? [英] What is minimal sample Gradle project for ANTLR4 (with antlr plugin)?
问题描述
我已经创建了新的 Gradle 项目,添加了
I have created new Gradle project, added
apply plugin: 'antlr'
和
dependencies {
antlr "org.antlr:antlr4:4.5.3"
到build.gradle
.
创建src/main/antlr/test.g4
文件,内容如下
grammar test;
r : 'hello' ID;
ID : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;
但它不起作用.没有生成java源文件(也没有发生错误).
But it doesn't work. No java source files generated (and no error occurred).
我错过了什么?
项目在这里:https://github.com/dims12/AntlrGradlePluginTest2
更新
我发现我的示例确实有效,但它将代码放入了 \build\generated-src
中,这是我没想到的 :shame:
I found my sample is actually works, but it put code into \build\generated-src
which I was not expecting :shame:
推荐答案
我会在这里添加其他答案.
I will add onto other answers here.
问题 1:生成的源文件放置在 build/generated-src
文件夹中.
Issue 1: Generated source files are placed in build/generated-src
folder.
我找到了 这个讨论,但那里的解决方案(设置 outputDirectory
属性)是一个坏想法.如果您执行 gradle clean build
命令,这将清除您的整个源目录.那里的讨论很好地解释了为什么你不应该
I found this discussion, but the solution there (setting outputDirectory
property) is a bad idea. If you do gradle clean build
command, this will clear out your entire source directory. The discussion there gives a good explanation as to why you should not
antlr 生成的源码被生成到一个build"文件夹的子目录,就像所有其他工件一样,它们是在构建过程中生成.此外您生成的目录projectRoot/build/generated-src/antlr/main 添加到javasourceset 定义以确保其考虑 compileJava 任务.如果将antlr生成的源码直接写到src/main/java您正在使用构建输出污染源文件夹的文件夹过程....在构建过程中污染源文件夹是一个我认为是反模式.
the antlr generated sources are generated into a subdirectory of the "build" folder like all other artifacts, which are generated during the build. Furthermore your generated directory projectRoot/build/generated-src/antlr/main is added to the java sourceset definition to be sure its considered compileJava task. If you write the antlr generated source directly to the src/main/java folder you're polluting your source folder with output of your build process. ... Polluting your source folder during your build is an antipattern I think.
但是,如果你想这样做,你可以添加一个gradle任务将生成的文件复制到构建目录中.
However, if you want to do this, you can add a gradle task to copy the generated files to the build directory.
generateGrammarSource << {
println "Copying generated grammar lexer/parser files to main directory."
copy {
from "${buildDir}/generated-src/antlr/main"
into "src/main/java"
}
}
<小时>
问题 2:生成的源文件没有设置包属性.
Issue 2: Generated source files do not have package attribute set.
要解决此问题,请在语法文件顶部附近添加如下内容:
To solve this issue, add something like the following near the top of the grammar file:
@header {
package com.example.my.package;
}
这篇关于ANTLR4 的最小示例 Gradle 项目是什么(带有 antlr 插件)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!