什么是ANTLR4(带有antlr插件)的最小示例Gradle项目? [英] What is minimal sample Gradle project for ANTLR4 (with antlr plugin)?

查看:526
本文介绍了什么是ANTLR4(带有antlr插件)的最小示例Gradle项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个新的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文件

Created src/main/antlr/test.g4 file with the following content

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命令,这将清除您的 entire 源目录.那里的讨论很好地解释了为什么您不应该

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添加到Java 源集定义,以确保将其视为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(带有antlr插件)的最小示例Gradle项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆