MethodHandles for Kawa and other functional languages?

Per Bothner per at bothner.com
Wed Sep 29 17:00:06 PDT 2010


I'm interested into (at least) evaluating MethodHandles for
Kawa (and similar languages with first-class functions).
But I'm not quite sure where to start, or what is the right
abstraction.

Kawa's function implementation is fairly efficient.  Calls
to known functions compile to direct method calls.  Calls
to unknown methods call an "apply" method that does argument
checking/conversion and then calls the method.  The most
obvious overhead which MethodHandles could fix is boxing
followed by unboxing.  It could also help when a Procedure
is defined as a set of multiple "MethodProcs".

Right now Procedure is an abstract class, with various
implementations.  Directly replacing Procedure by MethodHandle
would probably be most efficient, but difficult.  Note that
Procedure may have properties (such as its name)

Another alternative is to store the MethodHandle in the Procedure
- i.e. Procedure is a wrapper around Methodhandle.  However,
I suspect that might not give the full performance benefit.

I'm considering something like:

public abstract class Procedure {
   MethodHandle mh; // initialized by sub-class
   public abstract MethodHandle asMethodHandle() { return mh; }
}

The default implementation of asMethodHandle just results
something that calls Procedure's apply method.  For example:

/* 1-argument function */
public abstract class Procedure1 extends Procedure {
   Procedure1() {
     MethodType mt = MethodType.methodType(Object.class, Object.class);
     return MethodHandles.lookup().findVirtual(getClass(), "apply1", mt);
   }

   public abstract Object apply1 (Object arg1);
}

A Procedure that corresponds to a user-written procedure could have
a specialized MethodType that points directly to the implementation
method.

When you call an unknwon procedure, you would first call
asMethodHandle() before calling invoke on the MethodHandle.
(If the same Procedure variable is called multiple times (like
in a loop) it makes sense to call asMethodHandle() once.

If there was a way to associate properties with a MethodHandle then
the runtime could use MethodHandles directly, since Kawa could always
get the Procedure back from the MethodHandle.  But that assumes
that (some) MethodHandles have identity.

Fundamentally, the question is: When the Scheme programmer passes
of function to a higher-level function (like map), what is the type
of the object passed: A MethodHandle?  A Procedure?  Something else?
There seem to be different kind of MethodHandles, so perhaps something
is appropriate.  Is there some blog article or cookbook discussing this?
-- 
	--Per Bothner
per at bothner.com   http://per.bothner.com/


More information about the mlvm-dev mailing list