Search code examples
gradleintellij-ideaantlr

ANTLR generated sources not found by IntelliJ


For some reason, even though Gradle builds fine, IntelliJ errors when building. I have ANTLR generating my parser code, but IntelliJ can't find the generated code. My build.gradle:

apply plugin: 'antlr'
apply plugin: 'idea'

def generatedDirectory = 'src/main/generated'

dependencies {
    antlr "org.antlr:antlr4:4.7.2"
    implementation "org.antlr:antlr4-runtime:4.7.2"
    implementation fileTree(generatedDirectory)
}

generateGrammarSource {
    maxHeapSize = "64m"
    arguments += ['-package', 'software.bigbade.fractioncalculator.generated']
    outputDirectory = new File(generatedDirectory + "/software/bigbade/fractioncalculator/generated")
}

compileJava.dependsOn generateGrammarSource

sourceSets {
    generated {
        java {
            srcDir generatedDirectory
        }
        compileClasspath += sourceSets.main.runtimeClasspath
    }
}

compileJava.source = sourceSets.generated.java + sourceSets.main.java

idea {
    module {
        generatedSourceDirs += file(generatedDirectory)
    }
}

clean {
    delete generatedDirectory
}

My run configuration: Run Configuration

IntelliJ even recognizes the package with the auto-import but compiling breaks it. I tried IntelliJ IDEA Gradle project not recognizing/locating Antlr generated sources. After fiddling with the package names, reloading Gradle, and invalidating caches/restarting, it worked for a whole two seconds. IntelliJ also recognizes the folder as a "generated source root".


Solution

  • Where do you expect generated sources to be? When you just add antlr Gradle plugin - it automatically adds generated sources in build output directory, and IDE detects them correctly:

    enter image description here

    There is no need to additionally define generated source set. I would recommend to consult antlr plugin documentation.