How do I debug a javac internal error when compiling with gradle?

It’s very common to run into javac internal errors, and I just got one. Gradle reports the error like this:

> Task :syntax:compileJava
An exception has occurred in the compiler (22.0.2). Please file a bug against the Java compiler via the Java bug reporting page (https://bugreport.java.com) after checking the Bug Database (https://bugs.java.com) for duplicates. Include your program, the following diagnostic, and the parameters passed to the Java compiler in your report. Thank you.
java.lang.NullPointerException: Cannot invoke "com.sun.tools.javac.tree.JCTree.getKind()" because "enclTr" is null
        at jdk.compiler/com.sun.tools.javac.code.TypeAnnotations$TypeAnnotationPositions.typeWithAnnotations(TypeAnnotations.java:474)
        at jdk.compiler/com.sun.tools.javac.code.TypeAnnotations$TypeAnnotationPositions.separateAnnotationsKinds(TypeAnnotations.java:367)
        at jdk.compiler/com.sun.tools.javac.code.TypeAnnotations$TypeAnnotationPositions.visitVarDef(TypeAnnotations.java:1255)
        at jdk.compiler/com.sun.tools.javac.tree.JCTree$JCVariableDecl.accept(JCTree.java:1022)
        at jdk.compiler/com.sun.tools.javac.tree.TreeScanner.scan(TreeScanner.java:50)
        at jdk.compiler/com.sun.tools.javac.code.TypeAnnotations$TypeAnnotationPositions.scan(TypeAnnotations.java:295)
        at jdk.compiler/com.sun.tools.javac.tree.TreeScanner.visitBindingPattern(TreeScanner.java:309)
        at jdk.compiler/com.sun.tools.javac.tree.JCTree$JCBindingPattern.accept(JCTree.java:2310)
        at jdk.compiler/com.sun.tools.javac.tree.TreeScanner.scan(TreeScanner.java:50)

is there a way to know which file caused this compilation error, so I can workaround it?

:thinking: I ran into an issue like this before and I essentially read all of my project files and used my compiler instinct to guess where the issue is. But now the project has grown bigger and it’s no longer feasible to do that…

It’s very common to run into javac internal errors

I develop in Java since almost 25 years and had almost no internal javac error, so I wouldn’t support that statement unless you add a “for me” :slight_smile:

How do I debug a javac internal error when compiling with gradle?

Make sure the Compiler is started in a forked process, for example by using a toolchain differently from what you run Gradle with and then set the debugger option you want as jvm args, so for example like

tasks.compileJava {
    javaCompiler = javaToolchains.compilerFor { languageVersion.set(JavaLanguageVersion.of(17)) }
    options.forkOptions.jvmArgs = listOf("-agentlib:jdwp=transport=dt_socket,server=n,address=5005")
}
1 Like

Ah, stupid me, you can just tell it to fork:

tasks.compileJava {
    options.isFork = true
    options.forkOptions.jvmArgs = listOf("-agentlib:jdwp=transport=dt_socket,server=n,address=5005")
}
1 Like

Wow, that’s amazing!

1 Like