Its been a long coding weekend, but after much head scratching, I might finally be getting the hang of changing the java compiler. My goal? to implement First class methods (FCM).
Currently, on my home laptop I have an altered version of javac, originally sourced from the KSL project which supports Method literals (section 2.1 of the spec). What this means in practice is that you can write:
Method m = String#substring(int,int);
This will now compile and return the correct Method object.
The left hand side can be a reference to an inner class such as
Map.Entry without problem.
It will also validate the standard access rules, preventing you from referencing a private/package/protected method when you shouldn't.
In fact, the implementation is currently more generous than this, as the left hand side can also be a variable. This is needed for later phases of FCM, but isn't really appropriate for a method literal.
Making a language change like this is definitely intimidating though, and mostly because the compiler feels like such a big scary beast.
The first two parts -
Parser are actually pretty easy.
Once those are done you have an AST (Abstract Syntax Tree) representing your code.
In this case that involves a new node, currently called 'MethodReference'.
After that it gets more confusing.
The main piece of work should be in
Lower, which is where syntax sugar is converted to 'normal' Java.
For example the new foreach loop is converted to the old one here.
Since method literals are just syntax sugar,
Lower is where the change goes.
Unfortunately, to get to
Lower, you also have to fight with
Attr which is where the types get allocated, checked and validated.
That was a real head scratcher, and I'm sure a compiler expert would laugh at my final code.
It does work though, and after all thats the main thing.
The next step will be to convert 'MethodReference' to 'MemberReference' and enable Field and Constructor literals. After that, the real FCM work begins!
So, by now you probably want to have a download link. But I'm not going to provide one. As the code is GPL, I can't just publish a binary, the source has to come too. And personally, I'd rather actually have it in a SVN repo somewhere before I let it escape at all (because that can probably count as the GPL source publication). So, I'm afraid you'll have to be patient :-)
This probably should go in the KSL, but right now I don't know whether it will. The trouble with the KSL is that it still has a few guards and protections around it. And to date, no-one other than Sun has committed there, even in a branch. I'm feeling more comfortable in creating a separate, 'fewer rules', project at sourceforge. In fact, it would be great if other javac hackers like Remi wanted to join too ;-)
One final thing... if anyone wants to help out with this work I'd much appreciate it - scolebourne|joda|org. Compiler hacking isn't easy, but its a great feeling when you get it working!