使用gradle中的包声明生成ANTLR4语法文件

问题描述 投票:14回答:4

我尝试使用gradle antlr插件,但遇到了几个问题。

我有一个名为wls.g4的语法文件:

grammar WlsScript;

@header {
   package hu.pmi.wls.antlr.ws;
} 

program
  : 'statementList'? EOF
  ;

// Several more grammar and lexer rules

(注意:我将语句List设为一个关键字只是为了制作一个正确的语法而不包括整个语法。;-))

该文件位于/ src / main / antlr(作为antlr生成语法文件的默认源文件夹)。

以下是build.gradle的片段:

project('common') {

    apply plugin: 'antlr'

    dependencies {
       // Some dependencies

       antlr "org.antlr:antlr4:4.5"
    }
} 

当我使用qazxsw poi gradle任务(来自qazxsw poi插件)生成源文件时,它会生成generateGrammarSource文件夹中的文件,这是默认文件。

出了什么问题,它没有创建java包的文件夹(在我们的例子中是antlr)所以源代码将错误地放在Eclipse中。

我的主要问题是如何强制任务以包结构的方式生成源文件?换句话说,如何配置gradle任务以使用语法中的包声明?

谢谢!

gradle antlr4
4个回答
12
投票

我有完全相同的问题,我能够更改AntlrTask使用的build/generated-src/antlr/main来获取包名称。

hu/pmi/wls/antlr/ws

我发现没有简单的方法从文件中提取语法包,因此必须在任务中对其进行硬编码。


5
投票

将其添加到子项目build.gradle中

outputDirectory

在你的“语法”之后将它添加到你的语法中;

generateGrammarSource {
    outputDirectory = new File("${project.buildDir}/generated-src/antlr/main/net/example".toString())
}

经过测试并与generateGrammarSource { outputDirectory = file("src/main/java/com/example/parser") } 合作

其他链接:

@header { package com.example.parser; }

我没有在将它放在父项目中时进行测试,就像你看起来那样,但应该很容易扩展到这样做。 (我尝试将父项目保留为空,而不是使用存储库。)


0
投票

我使用antlr3有类似的问题。您可以将附加后处理的位置修复为generateGrammarSource任务:

Java8 grammar from antlr example grammars

0
投票

将生成的ANTLR文件传输到项目文件夹和ZZZ子文件夹。

antlr.g4

....

Here is a short guide of the Antlr plugin from docs.gradle.org

.....

build.gradle

/* Antlr generated files have wrong position so fix it with a post generation processing */
import groovy.io.FileType
generateGrammarSource << {
    logger.info("Antlr doesn't produce files to rigth place. Fix using package declaration")
    def move = [/*File wrong position*/:/*File rigth position*/]
    generateGrammarSource.outputDirectory.eachFileMatch( FileType.FILES, ~/.*\.java/ ) { f ->
        def pkg = f.readLines().find { it.trim() =~ /^package/ }
        if (pkg) {
            pkg = pkg.split( ' ' )[1].replace( ';','' )
            pkg = pkg.replace( '.','/' )
            move.put( f,new File("${generateGrammarSource.outputDirectory}/$pkg/${f.name}") )
        }
    }
    move.each { s,t ->
    logger.info( "Moving ${s.name} to right location .." )
    t.parentFile.mkdirs()
    s.renameTo( t.absolutePath )
}

Test.java

@header {
package XXX.YYY.ZZZ;
}

...

© www.soinside.com 2019 - 2024. All rights reserved.