Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating ANTLR4 grammar files with package declaration in gradle

Tags:

gradle

antlr4

I try to use the gradle antlr plugin, but run into several problems.

I have a grammar file called wls.g4:

grammar WlsScript;

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

program
  : 'statementList'? EOF
  ;

// Several more grammar and lexer rules

(Note: I made the statementList to a keyword only to make a correct grammer without including the whole grammar. ;-))

This file is located in /src/main/antlr (as the default source folder of the antlr production grammar files).

Here is the snippet from build.gradle:

project('common') {

    apply plugin: 'antlr'

    dependencies {
       // Some dependencies

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

When I use the generateGrammarSource gradle task (comming from antlr plugin) to generate the source files it generates the files in build/generated-src/antlr/main folder which is the default.

What goes wrong, that it doesn't create the folders of the java package (hu/pmi/wls/antlr/ws in our case) so the source will be incorrectly located in Eclipse.

My primary question is how could I force the task to generate source files in a package-structured way? In other words, how can I configure the gradle task to use the package declaration from grammar?

Thanks!

like image 324
Balage1551 Avatar asked Jun 04 '15 11:06

Balage1551


1 Answers

I had the exact same question and I was able to change the outputDirectory used by the AntlrTask to get the package name in there.

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

I found no easy way to extract the grammar package from the files so had to hardcode it in the task.

like image 77
Nagesh Susarla Avatar answered Sep 28 '22 12:09

Nagesh Susarla