use of java.lang.invoke.MethodHandle in project elasticsearch by elastic.
the class Definition method addMethodInternal.
private void addMethodInternal(String struct, String name, boolean augmentation, Type rtn, Type[] args) {
final Struct owner = structsMap.get(struct);
if (owner == null) {
throw new IllegalArgumentException("Owner struct [" + struct + "] not defined" + " for method [" + name + "].");
}
if (!name.matches("^[_a-zA-Z][_a-zA-Z0-9]*$")) {
throw new IllegalArgumentException("Invalid method name" + " [" + name + "] with the struct [" + owner.name + "].");
}
MethodKey methodKey = new MethodKey(name, args.length);
if (owner.constructors.containsKey(methodKey)) {
throw new IllegalArgumentException("Constructors and methods" + " may not have the same signature [" + methodKey + "] within the same struct" + " [" + owner.name + "].");
}
if (owner.staticMethods.containsKey(methodKey) || owner.methods.containsKey(methodKey)) {
throw new IllegalArgumentException("Duplicate method signature [" + methodKey + "] found within the struct [" + owner.name + "].");
}
final Class<?> implClass;
final Class<?>[] params;
if (augmentation == false) {
implClass = owner.clazz;
params = new Class<?>[args.length];
for (int count = 0; count < args.length; ++count) {
params[count] = args[count].clazz;
}
} else {
implClass = Augmentation.class;
params = new Class<?>[args.length + 1];
params[0] = owner.clazz;
for (int count = 0; count < args.length; ++count) {
params[count + 1] = args[count].clazz;
}
}
final java.lang.reflect.Method reflect;
try {
reflect = implClass.getMethod(name, params);
} catch (NoSuchMethodException exception) {
throw new IllegalArgumentException("Method [" + name + "] not found for class [" + implClass.getName() + "]" + " with arguments " + Arrays.toString(params) + ".");
}
if (!reflect.getReturnType().equals(rtn.clazz)) {
throw new IllegalArgumentException("Specified return type class [" + rtn.clazz + "]" + " does not match the found return type class [" + reflect.getReturnType() + "] for the" + " method [" + name + "]" + " within the struct [" + owner.name + "].");
}
final org.objectweb.asm.commons.Method asm = org.objectweb.asm.commons.Method.getMethod(reflect);
MethodHandle handle;
try {
handle = MethodHandles.publicLookup().in(implClass).unreflect(reflect);
} catch (final IllegalAccessException exception) {
throw new IllegalArgumentException("Method [" + name + "]" + " not found for class [" + implClass.getName() + "]" + " with arguments " + Arrays.toString(params) + ".");
}
final int modifiers = reflect.getModifiers();
final Method method = new Method(name, owner, augmentation, rtn, Arrays.asList(args), asm, modifiers, handle);
if (augmentation == false && java.lang.reflect.Modifier.isStatic(modifiers)) {
owner.staticMethods.put(methodKey, method);
} else {
owner.methods.put(methodKey, method);
}
}
use of java.lang.invoke.MethodHandle in project elasticsearch by elastic.
the class Def method lookupReferenceInternal.
/** Returns a method handle to an implementation of clazz, given method reference signature. */
private static MethodHandle lookupReferenceInternal(Lookup lookup, Definition.Type clazz, String type, String call, Class<?>... captures) throws Throwable {
final FunctionRef ref;
if ("this".equals(type)) {
// user written method
Method interfaceMethod = clazz.struct.getFunctionalMethod();
if (interfaceMethod == null) {
throw new IllegalArgumentException("Cannot convert function reference [" + type + "::" + call + "] " + "to [" + clazz.name + "], not a functional interface");
}
int arity = interfaceMethod.arguments.size() + captures.length;
final MethodHandle handle;
try {
MethodHandle accessor = lookup.findStaticGetter(lookup.lookupClass(), getUserFunctionHandleFieldName(call, arity), MethodHandle.class);
handle = (MethodHandle) accessor.invokeExact();
} catch (NoSuchFieldException | IllegalAccessException e) {
// because the arity does not match the expected interface type.
if (call.contains("$")) {
throw new IllegalArgumentException("Incorrect number of parameters for [" + interfaceMethod.name + "] in [" + clazz.clazz + "]");
}
throw new IllegalArgumentException("Unknown call [" + call + "] with [" + arity + "] arguments.");
}
ref = new FunctionRef(clazz, interfaceMethod, handle, captures.length);
} else {
// whitelist lookup
ref = new FunctionRef(clazz, type, call, captures.length);
}
final CallSite callSite;
if (ref.needsBridges()) {
callSite = LambdaMetafactory.altMetafactory(lookup, ref.invokedName, ref.invokedType, ref.samMethodType, ref.implMethod, ref.samMethodType, LambdaMetafactory.FLAG_BRIDGES, 1, ref.interfaceMethodType);
} else {
callSite = LambdaMetafactory.altMetafactory(lookup, ref.invokedName, ref.invokedType, ref.samMethodType, ref.implMethod, ref.samMethodType, 0);
}
return callSite.dynamicInvoker().asType(MethodType.methodType(clazz.clazz, captures));
}
use of java.lang.invoke.MethodHandle in project elasticsearch by elastic.
the class Def method lookupMethod.
/**
* Looks up handle for a dynamic method call, with lambda replacement
* <p>
* A dynamic method call for variable {@code x} of type {@code def} looks like:
* {@code x.method(args...)}
* <p>
* This method traverses {@code recieverClass}'s class hierarchy (including interfaces)
* until it finds a matching whitelisted method. If one is not found, it throws an exception.
* Otherwise it returns a handle to the matching method.
* <p>
* @param lookup caller's lookup
* @param callSiteType callsite's type
* @param receiverClass Class of the object to invoke the method on.
* @param name Name of the method.
* @param args bootstrap args passed to callsite
* @return pointer to matching method to invoke. never returns null.
* @throws IllegalArgumentException if no matching whitelisted method was found.
* @throws Throwable if a method reference cannot be converted to an functional interface
*/
static MethodHandle lookupMethod(Lookup lookup, MethodType callSiteType, Class<?> receiverClass, String name, Object[] args) throws Throwable {
String recipeString = (String) args[0];
int numArguments = callSiteType.parameterCount();
// simple case: no lambdas
if (recipeString.isEmpty()) {
return lookupMethodInternal(receiverClass, name, numArguments - 1).handle;
}
// convert recipe string to a bitset for convenience (the code below should be refactored...)
BitSet lambdaArgs = new BitSet();
for (int i = 0; i < recipeString.length(); i++) {
lambdaArgs.set(recipeString.charAt(i));
}
// otherwise: first we have to compute the "real" arity. This is because we have extra arguments:
// e.g. f(a, g(x), b, h(y), i()) looks like f(a, g, x, b, h, y, i).
int arity = callSiteType.parameterCount() - 1;
int upTo = 1;
for (int i = 1; i < numArguments; i++) {
if (lambdaArgs.get(i - 1)) {
String signature = (String) args[upTo++];
int numCaptures = Integer.parseInt(signature.substring(signature.indexOf(',') + 1));
arity -= numCaptures;
}
}
// lookup the method with the proper arity, then we know everything (e.g. interface types of parameters).
// based on these we can finally link any remaining lambdas that were deferred.
Method method = lookupMethodInternal(receiverClass, name, arity);
MethodHandle handle = method.handle;
int replaced = 0;
upTo = 1;
for (int i = 1; i < numArguments; i++) {
// its a functional reference, replace the argument with an impl
if (lambdaArgs.get(i - 1)) {
// decode signature of form 'type.call,2'
String signature = (String) args[upTo++];
int separator = signature.lastIndexOf('.');
int separator2 = signature.indexOf(',');
String type = signature.substring(1, separator);
String call = signature.substring(separator + 1, separator2);
int numCaptures = Integer.parseInt(signature.substring(separator2 + 1));
Class<?>[] captures = new Class<?>[numCaptures];
for (int capture = 0; capture < captures.length; capture++) {
captures[capture] = callSiteType.parameterType(i + 1 + capture);
}
MethodHandle filter;
Definition.Type interfaceType = method.arguments.get(i - 1 - replaced);
if (signature.charAt(0) == 'S') {
// the implementation is strongly typed, now that we know the interface type,
// we have everything.
filter = lookupReferenceInternal(lookup, interfaceType, type, call, captures);
} else if (signature.charAt(0) == 'D') {
// the interface type is now known, but we need to get the implementation.
// this is dynamically based on the receiver type (and cached separately, underneath
// this cache). It won't blow up since we never nest here (just references)
MethodType nestedType = MethodType.methodType(interfaceType.clazz, captures);
CallSite nested = DefBootstrap.bootstrap(lookup, call, nestedType, 0, DefBootstrap.REFERENCE, interfaceType.name);
filter = nested.dynamicInvoker();
} else {
throw new AssertionError();
}
// the filter now ignores the signature (placeholder) on the stack
filter = MethodHandles.dropArguments(filter, 0, String.class);
handle = MethodHandles.collectArguments(handle, i, filter);
i += numCaptures;
replaced += numCaptures;
}
}
return handle;
}
use of java.lang.invoke.MethodHandle in project elasticsearch by elastic.
the class DefMath method dynamicCast.
/** Looks up generic method, with a dynamic cast to the receiver's type. (compound assignment) */
public static MethodHandle dynamicCast(MethodHandle target) {
// adapt dynamic receiver cast to the generic method
MethodHandle cast = DYNAMIC_RECEIVER_CAST.asType(MethodType.methodType(target.type().returnType(), target.type().returnType(), target.type().parameterType(0)));
// drop the RHS parameter
cast = MethodHandles.dropArguments(cast, 2, target.type().parameterType(1));
// combine: f(x,y) -> g(f(x,y), x, y);
return MethodHandles.foldArguments(cast, target);
}
use of java.lang.invoke.MethodHandle in project elasticsearch by elastic.
the class ArrayTests method assertArrayLength.
private void assertArrayLength(int length, Object array) throws Throwable {
final MethodHandle mh = Def.arrayLengthGetter(array.getClass());
assertSame(array.getClass(), mh.type().parameterType(0));
assertEquals(length, (int) mh.asType(MethodType.methodType(int.class, Object.class)).invokeExact(array));
}
Aggregations