Almost one year ago, I published a thread here on Reddit explaining a project that I had just completed to add Named and Optional parameters to Java. Some days ago, I made some modifications to the project to make it better thanks to some new things that I have learned in the past year. The project is on GitHub, star it if you want. Over there are instructions on how to use it: it’s just a Maven/Gradle dependency, nothing more. It works out of the box anywhere with whatever IDE you use, just no lining for now. I’ll now go over each class to understand how the project works in detail. Javac isn’t documented, it all comes down to reading its source to find cues to make these things work.
The building blocks - Reflection
To add named and optional parameters to Java, this project uses a Javac Compiler Plugin.
The public API exposes an immutable AST that can be used, for example, to add custom checks.
Though, this is not good enough to accomplish the goal of this project.
Before the modularization of the JDK(Java 9), the private compiler API(com.sun.javac.tools.*) could be imported freely to modify the AST, which is exactly what’s needed here.
Because the project is written in Java 17, though, you would need a bunch of —add-opens to access this API and, more importantly, reflection will not work because the jdk.unsupported module is not marked as open. Though using some Unsafe magic the compiler modules can be opened without any additional arguments and reflection use can be restored. Obviously, this is in no way officially supported, but it works on all versions of Java. This is the source of the Reflection class
Custom diagnostics - Diagnostics
The AST generated by Javac is modified by this plugin to be valid, but until then the code isn’t syntactically valid. Here are the various phases that the compiler goes through
- Parse
This step essentially generates an object-oriented representation of the input java files called AST(Abstract Syntax Tree) - Enter
At this point, the compiler adds some important metadata to the AST and checks that the code is syntactically valid. Here it would fail because named parameters aren’t valid for Java. - Analyze
Now the compiler resolves types, classes, references and much more to make the AST ready for class generation. At this point, the logic of my compiler plugin runs to modify the AST into something that can be actually compiled to bytecode. - Annotation processing
At this point, annotations processors are called to do their job - Generate
Finally, the AST is translated into bytecode and written to the correct class file
The AST could be modified before the “enter” phase to prevent the compiler from erroring out, but it would be next to impossible to do as processing the named parameters requires the AST to be entered and analyzed either by Javac, which is impossible in this case, or something else. As far as I know, Lombok went with the second option and reimplemented the whole attribution phase to have a custom AST, but this is impractical in my opinion. The approach I came up with is to make Javac enter and attribute the AST, but without its error detection system. In short, inside Javac’s logger implementation, there are two fields(diagnosticHandler and deferredDiagnosticHandler) that are responsible for receiving and reporting errors coming from other components of the compiler. Using reflection, we can set these fields to a custom implementation that stores the errors in a collection instead of reporting them straight away. Then, after the attribution process is completed and the plugin’s work is completed, we can report the errors that weren’t solved, if any remain. This is the source of the Diagnostics class
Make the AST complete - PrepareTypesScanner
While Javac enters the AST to the best of its ability, it doesn’t resolve everything because it’s not needed when it works as intended. Because of this, some bogus types to satisfy a couple of asserts here and there need to be added manually to method invocations(for example hello(name=“Ale”)) or class initializations(for example new Hello(name=“Ale”)). This is the source of the PrepareTypesScanner class
Default values - PrepareTypesScanner
To add default values to parameters, I added an annotation called Option. Ideally, I’d want my annotation to look like this:
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.SOURCE)
public @interface Option {
Constable value();
}
The Constable type though cannot be used there, I don’t really know why as it makes sense in my opinion. To fix this issue, I used a String as the type of value() and added an annotation visitor that removes that argument from the AST and caches it so that the compilation won’t fail. For example \@Option(value = 123) int parameter is transformed into \@Option int parameter and 123 is stored in a map for the plugin to fill it in later. This approach works also for dynamic values, which I only see as a bonus. For example \@Option(someMethod(123)) int parameter is valid. This is the source of the PrepareTypesScanner class
Transforming the AST - NamedParameterTransformer
At this point, the plugin is finally ready to transform the AST.
This invalid Java code
import it.auties.named.annotation.Option;
public class Main {
public static void main(String[] args) {
sayHello(name="Alessandro");
}
private static void sayHello(String name, @Option(18) int age){
System.out.printf("Hello, %s(age: %s)%n", name, age);
}
}
Will be transformed into:
public class Main {
public Main() {
super();
}
public static void main(String[] args) {
sayHello("Alessandro", 18);
}
private static void sayHello(String name, int age) {
System.out.printf("Hello, %s(age: %s)%n", name, age);
}
}
(this code is decompiled obviously)
Here you can find the class that handles this process, all the methods are commented so it should be understandable. It took me some time to make it work well, but in short here the issues that the compiler found previously related to the illegal syntax of named parameters and default values inside \@Option are marked as resolved in the Diagnostics. If for example the wrong types, unknown named parameters, … are used to call a method or a class they are still reported by Javac normally. No weird messages or crashes. This seems easy in theory, but it took me so much time to make it work as it’s supposed. This is the source of the NamedParameterTransformer class
Reattribute the AST
After everything is completed, NamedParameterPlugin reattributes the AST that was modified to make it compilable by Javac. To prepare for this process some symbols have to be removed from its metadata to make sure that Javac actually reattributes them. This happens both in NamedParameterPlugin and RemoveTypesScanner
Originally posted on r/java on January 15, 2023.