Search code examples
javaannotationscode-generationjanino

Overriding line number in generated Java source


Is there any way to override the line numbers in Java (e.g., by using some kind of preprocessor directive)?

I am "compiling" a high-level language, down to Java byte code using Janino. I need compiler errors to report the line from the original file, not the generated Java code.

C# has the #line directive, and I've successfully exploited it to map line numbers from a source file to the compiled result. I need the same for Java.

Thanks!


Solution

  • Using Janino you can derive from Scanner and override the location() method. This method returns a Location object. You can override the read() method to look for annotations, within comments for instance (added during code generation), that hold line number information.

    You simply pass your scanner to the SimpleCompiler.cook() method and you can control what filename, line and column get reported on error.