I have created new Gradle project, added
apply plugin: 'antlr'
and
dependencies {
antlr "org.antlr:antlr4:4.5.3"
to build.gradle
.
Created src/main/antlr/test.g4
file with the following content
grammar test;
r : 'hello' ID;
ID : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;
But it doesn't work. No java source files generated (and no error occurred).
What I missed?
Project is here: https://github.com/dims12/AntlrGradlePluginTest2
UPDATE
I found my sample is actually works, but it put code into \build\generated-src
which I was not expecting :shame:
Gradle STS plugin doesn't generate source files for antlr4. It generates the misleading output as:
Uninstalled this old plugin and used from command line..It works !
For Issue 2:
you can configure in the gradle.build:
I will add onto other answers here.
Issue 1: Generated source files are placed in
build/generated-src
folder.I found this discussion, but the solution there (setting
outputDirectory
property) is a bad idea. If you dogradle clean build
command, this will clear out your entire source directory. The discussion there gives a good explanation as to why you should notHowever, if you want to do this, you can add a gradle task to copy the generated files to the build directory.
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:
A sample is included in the Gradle "all" distribution under the "samples" folder. You can also simply browse the sample on GitHub.
https://github.com/gradle/gradle/tree/master/subprojects/docs/src/samples/antlr
What helped me is two things:
@header{ package com.example.something.antlrparser; }
to the top of the grammar file.src/main/antlr/com/example/something/antlrparser/grammar.g4
Now when I run the
generateGrammarSource
gradle task,.java
files are generated in/build/generated-src/antlr/main/com/example/something/antlrparser/*.java
and they are automatically picked up by IntelliJ as well as compilable by gradle.The
build.gradle
file is just:Add this to your build.gradle
add this to your grammar after your "grammar ";
Tested and working with Java8 grammar from antlr example grammars
Additional Link(s):
Here is a short guide of the Antlr plugin from docs.gradle.org