DLR Expression Tree like in Java
Two months ago, I was discussing with a friend about
dynamic languages and JSR 292 when he mentions
DLR Expression Trees.
At that time, I had a vague memory,
mostly because I was under the effect of a
persisting jet lag, when I attend the talk of Mads Torgersen
about it at last year JVM Summit.
By the way, I will attend the next
JVM Summit in September,
I have some good results with
JSR 292 backport.
I had finished the debate with my friend saying that an
expression tree like that can be easily implemented
in one hour on top of JSR 292 API.
In fact, it takes me a little more than one day to just sketch
a prototype. And Yes, I have some free times,
I'm in vacation and my wife allow me to took
my laptop with me :)
An Expression Tree
The main idea is to be able to create an AST and to
transform it into runnable code at runtime.
The following example create a kind of anonymous method
(a lambda, etc) that takes two integers and returns their sum.
The class ExprBuilder use a stack based notation
like by example the
because I'm too lenient to implement a real AST
(with automatic type conversions).
MethodType methodType = MethodType.make(int.class, int.class, int.class);
ExprBuilder builder = new ExprBuilder(methodType);
Var a = builder.parameter(0);
Var b = builder.parameter(1);
MethodHandle mh = builder.createMethodHandle(Main.class);
Also notice that createMethodhandle takes a class as argument
because the anonymous method will be able to access to all
fields, methods, etc even if they are declared private
(thanks to the
anonymous class loader)
like a classical member of this class.
/usr/jdk/jdk1.7.0/bin/java -cp classes:lib/asm-all-3.2.jar -XX:+EnableInvokeDynamic Main