Tuesday, February 28, 2017

Antlr4, gradle, -package, outputDirectory

First, we enabled antlr4 in IntelliJ/gradle. Next we need to find a location for antlr4 files and correctly place its output files.  There is a couple of ways to configure antlr4 output directory in gradle.

The simplest way is specify package name in @header:

@header {
  package com.example.parser;
}

Then, if we place our grammar files to "$project.projectDir/src/main/antlr/com/example/parser", antlr4 will place its output files to "$project.buildDir/generated-src/antlr/main/com/example/parser".

The problem with specifying package name in the @header is that it ties the grammar to the target language.  There is another way to configure output directory.

First, we remove @header from grammar file to untie the grammar from the target language.
Second, we add the following to build.gradle:

generateGrammarSource {
    outputDirectory file("${project.buildDir}/generated-src/antlr/main/com/example/parser")
    arguments << '-package' << 'com.example.parser'
}

An optional step is to move the grammar files from "$project.projectDir/src/main/antlr/com/example/parser" to "$project.projectDir/src/main/antlr" so that we don't have to look for the files deep down the directory hierarchy.

When all this is setup, antlr4 will place its output files into the same directory as in the first example.

No comments:

Post a Comment