Search in sources :

Example 1 with CallSite

use of java.lang.invoke.CallSite 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));
}
Also used : CallSite(java.lang.invoke.CallSite) Method(org.elasticsearch.painless.Definition.Method) MethodHandle(java.lang.invoke.MethodHandle)

Example 2 with CallSite

use of java.lang.invoke.CallSite 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;
}
Also used : MethodType(java.lang.invoke.MethodType) BitSet(java.util.BitSet) RuntimeClass(org.elasticsearch.painless.Definition.RuntimeClass) CallSite(java.lang.invoke.CallSite) Method(org.elasticsearch.painless.Definition.Method) MethodHandle(java.lang.invoke.MethodHandle)

Example 3 with CallSite

use of java.lang.invoke.CallSite in project elasticsearch by elastic.

the class DefBootstrapTests method testOneType.

/** calls toString() on integers, twice */
public void testOneType() throws Throwable {
    CallSite site = DefBootstrap.bootstrap(MethodHandles.publicLookup(), "toString", MethodType.methodType(String.class, Object.class), 0, DefBootstrap.METHOD_CALL, "");
    MethodHandle handle = site.dynamicInvoker();
    assertDepthEquals(site, 0);
    // invoke with integer, needs lookup
    assertEquals("5", (String) handle.invokeExact((Object) 5));
    assertDepthEquals(site, 1);
    // invoked with integer again: should be cached
    assertEquals("6", (String) handle.invokeExact((Object) 6));
    assertDepthEquals(site, 1);
}
Also used : CallSite(java.lang.invoke.CallSite) MethodHandle(java.lang.invoke.MethodHandle)

Example 4 with CallSite

use of java.lang.invoke.CallSite in project elasticsearch by elastic.

the class DefBootstrapTests method testTooManyTypes.

public void testTooManyTypes() throws Throwable {
    // if this changes, test must be rewritten
    assertEquals(5, DefBootstrap.PIC.MAX_DEPTH);
    CallSite site = DefBootstrap.bootstrap(MethodHandles.publicLookup(), "toString", MethodType.methodType(String.class, Object.class), 0, DefBootstrap.METHOD_CALL, "");
    MethodHandle handle = site.dynamicInvoker();
    assertDepthEquals(site, 0);
    assertEquals("5", (String) handle.invokeExact((Object) 5));
    assertDepthEquals(site, 1);
    assertEquals("1.5", (String) handle.invokeExact((Object) 1.5f));
    assertDepthEquals(site, 2);
    assertEquals("6", (String) handle.invokeExact((Object) 6L));
    assertDepthEquals(site, 3);
    assertEquals("3.2", (String) handle.invokeExact((Object) 3.2d));
    assertDepthEquals(site, 4);
    assertEquals("foo", (String) handle.invokeExact((Object) "foo"));
    assertDepthEquals(site, 5);
    assertEquals("c", (String) handle.invokeExact((Object) 'c'));
    assertDepthEquals(site, 5);
}
Also used : CallSite(java.lang.invoke.CallSite) MethodHandle(java.lang.invoke.MethodHandle)

Example 5 with CallSite

use of java.lang.invoke.CallSite in project jdk8u_jdk by JetBrains.

the class SerializedLambdaTest method testDirectStdNonser.

// standard MF: nonserializable supertype
public void testDirectStdNonser() throws Throwable {
    MethodHandle fooMH = MethodHandles.lookup().findStatic(SerializedLambdaTest.class, "foo", predicateMT);
    // Standard metafactory, non-serializable target: not serializable
    CallSite cs = LambdaMetafactory.metafactory(MethodHandles.lookup(), "test", MethodType.methodType(Predicate.class), predicateMT, fooMH, stringPredicateMT);
    Predicate<String> p = (Predicate<String>) cs.getTarget().invokeExact();
    assertNotSerial(p, fooAsserter);
}
Also used : CallSite(java.lang.invoke.CallSite) MethodHandle(java.lang.invoke.MethodHandle) Predicate(java.util.function.Predicate) BiPredicate(java.util.function.BiPredicate)

Aggregations

CallSite (java.lang.invoke.CallSite)18 MethodHandle (java.lang.invoke.MethodHandle)15 MethodType (java.lang.invoke.MethodType)6 MethodHandles (java.lang.invoke.MethodHandles)5 LambdaReceiver_A (LambdaReceiver_anotherpkg.LambdaReceiver_A)2 Method (java.lang.reflect.Method)2 BiConsumer (java.util.function.BiConsumer)2 BiPredicate (java.util.function.BiPredicate)2 Predicate (java.util.function.Predicate)2 Supplier (java.util.function.Supplier)2 Method (org.elasticsearch.painless.Definition.Method)2 SystemClock (android.os.SystemClock)1 AndroidJUnit4 (androidx.test.ext.junit.runners.AndroidJUnit4)1 Truth.assertThat (com.google.common.truth.Truth.assertThat)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileDescriptor (java.io.FileDescriptor)1 PrintStream (java.io.PrintStream)1 Serializable (java.io.Serializable)1 Field (java.lang.reflect.Field)1 Socket (java.net.Socket)1