Matt
Matt

Reputation: 898

How can a gradle build handle both antlr3 and antlr4 grammars?

I have got a legacy project in which both ANTLR3 and ANTLR4 grammars are used. We want to update the ant build system to gradle. There is a antlr plugin for gradle that supports ANTLR2/3/4. However, apparently it supports only one of the three at a time (depending on the added dependencies).

In our project, antlr3 files have suffix .g while antlr4 grammars are suffixed .g4.

Is there an option to the plugin or an alternative plugin which allows me to use grammars of both ANTLR versions at a time?

Thanks for any hint.

plugins {
    id 'java-library'
    id 'antlr'
}

dependencies {
    // ...

    // If both are mentioned, then "X.g" is also treated as antlr4
    antlr "org.antlr:antlr:3.5.2" // use ANTLR version 3
    antlr "org.antlr:antlr4:4.5" // use ANTLR version 4
}

Upvotes: 0

Views: 848

Answers (1)

wadoon
wadoon

Reputation: 51

Currently the antlr plugin does not support multiple versions. A workaround is to use JavaExec tasks to call antlr3 or antlr4. Here is a way how to do it.

  1. Create configurations for using gradle dependency management for retrieving antlr3 or antlr4.
configurations{
  antlr3,
  antlr4
}

dependencies {
    antlr3 "org.antlr:antlr:3.5.2"
    antlr4 "org.antlr:antlr4:4.7.1" 

    compile "org.antlr:antlr-runtime:3.5.2"
    compile "org.antlr:antlr4-runtime:4.7.1" 
}

  1. Define the tasks.
task runAntlr4(type:JavaExec) {
   //see incremental task api, prevents rerun if nothing has changed.
   inputs.dir "src/main/antlr4/"
   outputs.dir "$projectDir/build/generated/antlr/main/"

   classpath = configurations.antlr4

   main = "org.antlr.v4.Tool" 

   args = [ "-verbose", "-visitor", 
            "-o",  "$projectDir/build/generated/antlr/main/",  
            "-package", <my-package>,
            "src/main/antlr4/MyLanguage.g4"]
}

compileJava.dependsOn runAntlr4
  • Analog for antlr3 with configurations.antlr3 and "org.antlr.Tool".
  • Add the output directory to sourceSets.main.java

Upvotes: 1

Related Questions