Java Code Examples for jdk.internal.dynalink.linker.LinkRequest#getArguments()

The following examples show how to use jdk.internal.dynalink.linker.LinkRequest#getArguments() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ContinuousArrayData.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return a fast linked array setter, or null if we have to dispatch to super class
 * @param desc     descriptor
 * @param request  link request
 * @return invocation or null if needs to be sent to slow relink
 */
@Override
public GuardedInvocation findFastSetIndexMethod(final Class<? extends ArrayData> clazz, final CallSiteDescriptor desc, final LinkRequest request) { // array, index, value
    final MethodType callType    = desc.getMethodType();
    final Class<?>   indexType   = callType.parameterType(1);
    final Class<?>   elementType = callType.parameterType(2);

    if (ContinuousArrayData.class.isAssignableFrom(clazz) && indexType == int.class) {
        final Object[]        args  = request.getArguments();
        final int             index = (int)args[args.length - 2];

        if (hasRoomFor(index)) {
            MethodHandle setElement = getElementSetter(elementType); //Z(continuousarraydata, int, int), return true if successful
            if (setElement != null) {
                //else we are dealing with a wider type than supported by this callsite
                MethodHandle getArray = ScriptObject.GET_ARRAY.methodHandle();
                getArray   = MH.asType(getArray, getArray.type().changeReturnType(getClass()));
                setElement = MH.filterArguments(setElement, 0, getArray);
                final MethodHandle guard = MH.insertArguments(FAST_ACCESS_GUARD, 0, clazz);
                return new GuardedInvocation(setElement, guard, (SwitchPoint)null, ClassCastException.class); //CCE if not a scriptObject anymore
            }
        }
    }

    return null;
}
 
Example 2
Source File: ContinuousArrayData.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return a fast linked array getter, or null if we have to dispatch to super class
 * @param desc     descriptor
 * @param request  link request
 * @return invocation or null if needs to be sent to slow relink
 */
@Override
public GuardedInvocation findFastGetIndexMethod(final Class<? extends ArrayData> clazz, final CallSiteDescriptor desc, final LinkRequest request) {
    final MethodType callType   = desc.getMethodType();
    final Class<?>   indexType  = callType.parameterType(1);
    final Class<?>   returnType = callType.returnType();

    if (ContinuousArrayData.class.isAssignableFrom(clazz) && indexType == int.class) {
        final Object[] args  = request.getArguments();
        final int      index = (int)args[args.length - 1];

        if (has(index)) {
            final MethodHandle getArray     = ScriptObject.GET_ARRAY.methodHandle();
            final int          programPoint = NashornCallSiteDescriptor.isOptimistic(desc) ? NashornCallSiteDescriptor.getProgramPoint(desc) : INVALID_PROGRAM_POINT;
            MethodHandle       getElement   = getElementGetter(returnType, programPoint);
            if (getElement != null) {
                getElement = MH.filterArguments(getElement, 0, MH.asType(getArray, getArray.type().changeReturnType(clazz)));
                final MethodHandle guard = MH.insertArguments(FAST_ACCESS_GUARD, 0, clazz);
                return new GuardedInvocation(getElement, guard, (SwitchPoint)null, ClassCastException.class);
            }
        }
    }

    return null;
}
 
Example 3
Source File: NativeArray.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean canLink(final Object self, final CallSiteDescriptor desc, final LinkRequest request) {
    final Object[] args = request.getArguments();

    if (args.length != 3) { //single argument check
        return false;
    }

    final ContinuousArrayData selfData = getContinuousArrayData(self);
    if (selfData == null) {
        return false;
    }

    final Object arg = args[2];
    //args[2] continuousarray or non arraydata, let past non array datas
    if (arg instanceof NativeArray) {
        final ContinuousArrayData argData = getContinuousArrayData(arg);
        if (argData == null) {
            return false;
        }
    }

    return true;
}
 
Example 4
Source File: NativeArray.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean canLink(final Object self, final CallSiteDescriptor desc, final LinkRequest request) {
    final Object[] args = request.getArguments();

    if (args.length != 3) { //single argument check
        return false;
    }

    final ContinuousArrayData selfData = getContinuousArrayData(self);
    if (selfData == null) {
        return false;
    }

    final Object arg = args[2];
    //args[2] continuousarray or non arraydata, let past non array datas
    if (arg instanceof NativeArray) {
        final ContinuousArrayData argData = getContinuousArrayData(arg);
        if (argData == null) {
            return false;
        }
    }

    return true;
}
 
Example 5
Source File: NashornStaticClassLinker.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
    final LinkRequest request = linkRequest.withoutRuntimeContext(); // Nashorn has no runtime context
    final Object self = request.getReceiver();
    if (self.getClass() != StaticClass.class) {
        return null;
    }
    final Class<?> receiverClass = ((StaticClass) self).getRepresentedClass();

    Bootstrap.checkReflectionAccess(receiverClass, true);
    final CallSiteDescriptor desc = request.getCallSiteDescriptor();
    // We intercept "new" on StaticClass instances to provide additional capabilities
    if ("new".equals(desc.getNameToken(CallSiteDescriptor.OPERATOR))) {
        if (! Modifier.isPublic(receiverClass.getModifiers())) {
            throw ECMAErrors.typeError("new.on.nonpublic.javatype", receiverClass.getName());
        }

        // make sure new is on accessible Class
        Context.checkPackageAccess(receiverClass);

        // Is the class abstract? (This includes interfaces.)
        if (NashornLinker.isAbstractClass(receiverClass)) {
            // Change this link request into a link request on the adapter class.
            final Object[] args = request.getArguments();
            args[0] = JavaAdapterFactory.getAdapterClassFor(new Class<?>[] { receiverClass }, null,
                    linkRequest.getCallSiteDescriptor().getLookup());
            final LinkRequest adapterRequest = request.replaceArguments(request.getCallSiteDescriptor(), args);
            final GuardedInvocation gi = checkNullConstructor(delegate(linkerServices, adapterRequest), receiverClass);
            // Finally, modify the guard to test for the original abstract class.
            return gi.replaceMethods(gi.getInvocation(), Guards.getIdentityGuard(self));
        }
        // If the class was not abstract, just delegate linking to the standard StaticClass linker. Make an
        // additional check to ensure we have a constructor. We could just fall through to the next "return"
        // statement, except we also insert a call to checkNullConstructor() which throws an ECMAScript TypeError
        // with a more intuitive message when no suitable constructor is found.
        return checkNullConstructor(delegate(linkerServices, request), receiverClass);
    }
    // In case this was not a "new" operation, just delegate to the the standard StaticClass linker.
    return delegate(linkerServices, request);
}
 
Example 6
Source File: NashornStaticClassLinker.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
    final LinkRequest request = linkRequest.withoutRuntimeContext(); // Nashorn has no runtime context
    final Object self = request.getReceiver();
    if (self.getClass() != StaticClass.class) {
        return null;
    }
    final Class<?> receiverClass = ((StaticClass) self).getRepresentedClass();

    Bootstrap.checkReflectionAccess(receiverClass, true);
    final CallSiteDescriptor desc = request.getCallSiteDescriptor();
    // We intercept "new" on StaticClass instances to provide additional capabilities
    if ("new".equals(desc.getNameToken(CallSiteDescriptor.OPERATOR))) {
        if (! Modifier.isPublic(receiverClass.getModifiers())) {
            throw ECMAErrors.typeError("new.on.nonpublic.javatype", receiverClass.getName());
        }

        // make sure new is on accessible Class
        Context.checkPackageAccess(receiverClass);

        // Is the class abstract? (This includes interfaces.)
        if (NashornLinker.isAbstractClass(receiverClass)) {
            // Change this link request into a link request on the adapter class.
            final Object[] args = request.getArguments();
            args[0] = JavaAdapterFactory.getAdapterClassFor(new Class<?>[] { receiverClass }, null,
                    linkRequest.getCallSiteDescriptor().getLookup());
            final LinkRequest adapterRequest = request.replaceArguments(request.getCallSiteDescriptor(), args);
            final GuardedInvocation gi = checkNullConstructor(delegate(linkerServices, adapterRequest), receiverClass);
            // Finally, modify the guard to test for the original abstract class.
            return gi.replaceMethods(gi.getInvocation(), Guards.getIdentityGuard(self));
        }
        // If the class was not abstract, just delegate linking to the standard StaticClass linker. Make an
        // additional check to ensure we have a constructor. We could just fall through to the next "return"
        // statement, except we also insert a call to checkNullConstructor() which throws an ECMAScript TypeError
        // with a more intuitive message when no suitable constructor is found.
        return checkNullConstructor(delegate(linkerServices, request), receiverClass);
    }
    // In case this was not a "new" operation, just delegate to the the standard StaticClass linker.
    return delegate(linkerServices, request);
}
 
Example 7
Source File: NashornStaticClassLinker.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
    final LinkRequest request = linkRequest.withoutRuntimeContext(); // Nashorn has no runtime context
    final Object self = request.getReceiver();
    if (self.getClass() != StaticClass.class) {
        return null;
    }
    final Class<?> receiverClass = ((StaticClass) self).getRepresentedClass();

    Bootstrap.checkReflectionAccess(receiverClass, true);
    final CallSiteDescriptor desc = request.getCallSiteDescriptor();
    // We intercept "new" on StaticClass instances to provide additional capabilities
    if ("new".equals(desc.getNameToken(CallSiteDescriptor.OPERATOR))) {
        if (! Modifier.isPublic(receiverClass.getModifiers())) {
            throw ECMAErrors.typeError("new.on.nonpublic.javatype", receiverClass.getName());
        }

        // make sure new is on accessible Class
        Context.checkPackageAccess(receiverClass);

        // Is the class abstract? (This includes interfaces.)
        if (NashornLinker.isAbstractClass(receiverClass)) {
            // Change this link request into a link request on the adapter class.
            final Object[] args = request.getArguments();
            args[0] = JavaAdapterFactory.getAdapterClassFor(new Class<?>[] { receiverClass }, null,
                    linkRequest.getCallSiteDescriptor().getLookup());
            final LinkRequest adapterRequest = request.replaceArguments(request.getCallSiteDescriptor(), args);
            final GuardedInvocation gi = checkNullConstructor(delegate(linkerServices, adapterRequest), receiverClass);
            // Finally, modify the guard to test for the original abstract class.
            return gi.replaceMethods(gi.getInvocation(), Guards.getIdentityGuard(self));
        }
        // If the class was not abstract, just delegate linking to the standard StaticClass linker. Make an
        // additional check to ensure we have a constructor. We could just fall through to the next "return"
        // statement, except we also insert a call to checkNullConstructor() which throws an ECMAScript TypeError
        // with a more intuitive message when no suitable constructor is found.
        return checkNullConstructor(delegate(linkerServices, request), receiverClass);
    }
    // In case this was not a "new" operation, just delegate to the the standard StaticClass linker.
    return delegate(linkerServices, request);
}
 
Example 8
Source File: NashornBeansLinker.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
    final Object self = linkRequest.getReceiver();
    final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
    if (self instanceof ConsString) {
        // In order to treat ConsString like a java.lang.String we need a link request with a string receiver.
        final Object[] arguments = linkRequest.getArguments();
        arguments[0] = "";
        final LinkRequest forgedLinkRequest = linkRequest.replaceArguments(desc, arguments);
        final GuardedInvocation invocation = getGuardedInvocation(beansLinker, forgedLinkRequest, linkerServices);
        // If an invocation is found we add a filter that makes it work for both Strings and ConsStrings.
        return invocation == null ? null : invocation.filterArguments(0, FILTER_CONSSTRING);
    }

    if (self != null && "call".equals(desc.getNameToken(CallSiteDescriptor.OPERATOR))) {
        // Support dyn:call on any object that supports some @FunctionalInterface
        // annotated interface. This way Java method, constructor references or
        // implementations of java.util.function.* interfaces can be called as though
        // those are script functions.
        final Method m = getFunctionalInterfaceMethod(self.getClass());
        if (m != null) {
            final MethodType callType = desc.getMethodType();
            // 'callee' and 'thiz' passed from script + actual arguments
            if (callType.parameterCount() != m.getParameterCount() + 2) {
                throw typeError("no.method.matches.args", ScriptRuntime.safeToString(self));
            }
            return new GuardedInvocation(
                    // drop 'thiz' passed from the script.
                    MH.dropArguments(linkerServices.filterInternalObjects(desc.getLookup().unreflect(m)), 1,
                            callType.parameterType(1)), Guards.getInstanceOfGuard(
                                    m.getDeclaringClass())).asTypeSafeReturn(
                                            new NashornBeansLinkerServices(linkerServices), callType);
        }
    }
    return getGuardedInvocation(beansLinker, linkRequest, linkerServices);
}
 
Example 9
Source File: NashornStaticClassLinker.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
    final LinkRequest request = linkRequest.withoutRuntimeContext(); // Nashorn has no runtime context
    final Object self = request.getReceiver();
    if (self.getClass() != StaticClass.class) {
        return null;
    }
    final Class<?> receiverClass = ((StaticClass) self).getRepresentedClass();

    Bootstrap.checkReflectionAccess(receiverClass, true);
    final CallSiteDescriptor desc = request.getCallSiteDescriptor();
    // We intercept "new" on StaticClass instances to provide additional capabilities
    if ("new".equals(desc.getNameToken(CallSiteDescriptor.OPERATOR))) {
        if (! Modifier.isPublic(receiverClass.getModifiers())) {
            throw ECMAErrors.typeError("new.on.nonpublic.javatype", receiverClass.getName());
        }

        // make sure new is on accessible Class
        Context.checkPackageAccess(receiverClass);

        // Is the class abstract? (This includes interfaces.)
        if (NashornLinker.isAbstractClass(receiverClass)) {
            // Change this link request into a link request on the adapter class.
            final Object[] args = request.getArguments();
            args[0] = JavaAdapterFactory.getAdapterClassFor(new Class<?>[] { receiverClass }, null,
                    linkRequest.getCallSiteDescriptor().getLookup());
            final LinkRequest adapterRequest = request.replaceArguments(request.getCallSiteDescriptor(), args);
            final GuardedInvocation gi = checkNullConstructor(delegate(linkerServices, adapterRequest), receiverClass);
            // Finally, modify the guard to test for the original abstract class.
            return gi.replaceMethods(gi.getInvocation(), Guards.getIdentityGuard(self));
        }
        // If the class was not abstract, just delegate linking to the standard StaticClass linker. Make an
        // additional check to ensure we have a constructor. We could just fall through to the next "return"
        // statement, except we also insert a call to checkNullConstructor() which throws an ECMAScript TypeError
        // with a more intuitive message when no suitable constructor is found.
        return checkNullConstructor(delegate(linkerServices, request), receiverClass);
    }
    // In case this was not a "new" operation, just delegate to the the standard StaticClass linker.
    return delegate(linkerServices, request);
}
 
Example 10
Source File: NashornBeansLinker.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
    final Object self = linkRequest.getReceiver();
    final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
    if (self instanceof ConsString) {
        // In order to treat ConsString like a java.lang.String we need a link request with a string receiver.
        final Object[] arguments = linkRequest.getArguments();
        arguments[0] = "";
        final LinkRequest forgedLinkRequest = linkRequest.replaceArguments(desc, arguments);
        final GuardedInvocation invocation = getGuardedInvocation(beansLinker, forgedLinkRequest, linkerServices);
        // If an invocation is found we add a filter that makes it work for both Strings and ConsStrings.
        return invocation == null ? null : invocation.filterArguments(0, FILTER_CONSSTRING);
    }

    if (self != null && "call".equals(desc.getNameToken(CallSiteDescriptor.OPERATOR))) {
        // Support dyn:call on any object that supports some @FunctionalInterface
        // annotated interface. This way Java method, constructor references or
        // implementations of java.util.function.* interfaces can be called as though
        // those are script functions.
        final String name = getFunctionalInterfaceMethodName(self.getClass());
        if (name != null) {
            final MethodType callType = desc.getMethodType();
            // drop callee (Undefined ScriptFunction) and change the request to be dyn:callMethod:<name>
            final NashornCallSiteDescriptor newDesc = NashornCallSiteDescriptor.get(desc.getLookup(),
                    "dyn:callMethod:" + name, desc.getMethodType().dropParameterTypes(1, 2),
                    NashornCallSiteDescriptor.getFlags(desc));
            final GuardedInvocation gi = getGuardedInvocation(beansLinker,
                    linkRequest.replaceArguments(newDesc, linkRequest.getArguments()),
                    new NashornBeansLinkerServices(linkerServices));

            // drop 'thiz' passed from the script.
            return gi.replaceMethods(
                MH.dropArguments(linkerServices.filterInternalObjects(gi.getInvocation()), 1, callType.parameterType(1)),
                gi.getGuard());
        }
    }
    return getGuardedInvocation(beansLinker, linkRequest, linkerServices);
}
 
Example 11
Source File: NashornBeansLinker.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
    final Object self = linkRequest.getReceiver();
    final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
    if (self instanceof ConsString) {
        // In order to treat ConsString like a java.lang.String we need a link request with a string receiver.
        final Object[] arguments = linkRequest.getArguments();
        arguments[0] = "";
        final LinkRequest forgedLinkRequest = linkRequest.replaceArguments(desc, arguments);
        final GuardedInvocation invocation = getGuardedInvocation(beansLinker, forgedLinkRequest, linkerServices);
        // If an invocation is found we add a filter that makes it work for both Strings and ConsStrings.
        return invocation == null ? null : invocation.filterArguments(0, FILTER_CONSSTRING);
    }

    if (self != null && "call".equals(desc.getNameToken(CallSiteDescriptor.OPERATOR))) {
        // Support dyn:call on any object that supports some @FunctionalInterface
        // annotated interface. This way Java method, constructor references or
        // implementations of java.util.function.* interfaces can be called as though
        // those are script functions.
        final String name = getFunctionalInterfaceMethodName(self.getClass());
        if (name != null) {
            final MethodType callType = desc.getMethodType();
            // drop callee (Undefined ScriptFunction) and change the request to be dyn:callMethod:<name>
            final NashornCallSiteDescriptor newDesc = NashornCallSiteDescriptor.get(desc.getLookup(),
                    "dyn:callMethod:" + name, desc.getMethodType().dropParameterTypes(1, 2),
                    NashornCallSiteDescriptor.getFlags(desc));
            final GuardedInvocation gi = getGuardedInvocation(beansLinker,
                    linkRequest.replaceArguments(newDesc, linkRequest.getArguments()),
                    new NashornBeansLinkerServices(linkerServices));

            // drop 'thiz' passed from the script.
            return gi.replaceMethods(
                MH.dropArguments(linkerServices.filterInternalObjects(gi.getInvocation()), 1, callType.parameterType(1)),
                gi.getGuard());
        }
    }
    return getGuardedInvocation(beansLinker, linkRequest, linkerServices);
}
 
Example 12
Source File: JavaSuperAdapterLinker.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices)
        throws Exception {
    final Object objSuperAdapter = linkRequest.getReceiver();
    if(!(objSuperAdapter instanceof JavaSuperAdapter)) {
        return null;
    }

    final CallSiteDescriptor descriptor = linkRequest.getCallSiteDescriptor();
    if(!CallSiteDescriptorFactory.tokenizeOperators(descriptor).contains(GET_METHOD)) {
        // We only handle getMethod
        return null;
    }

    final Object adapter = ((JavaSuperAdapter)objSuperAdapter).getAdapter();

    // Replace argument (javaSuperAdapter, ...) => (adapter, ...) when delegating to BeansLinker
    final Object[] args = linkRequest.getArguments();
    args[0] = adapter;

    // Use R(T0, ...) => R(adapter.class, ...) call site type when delegating to BeansLinker.
    final MethodType type = descriptor.getMethodType();
    final Class<?> adapterClass = adapter.getClass();
    final boolean hasFixedName = descriptor.getNameTokenCount() > 2;
    final String opName = hasFixedName ? (DYN_GET_METHOD_FIXED + descriptor.getNameToken(
            CallSiteDescriptor.NAME_OPERAND)) : DYN_GET_METHOD;

    final CallSiteDescriptor newDescriptor = NashornCallSiteDescriptor.get(descriptor.getLookup(), opName,
            type.changeParameterType(0, adapterClass), 0);

    // Delegate to BeansLinker
    final GuardedInvocation guardedInv = NashornBeansLinker.getGuardedInvocation(
            BeansLinker.getLinkerForClass(adapterClass), linkRequest.replaceArguments(newDescriptor, args),
            linkerServices);

    final MethodHandle guard = IS_ADAPTER_OF_CLASS.bindTo(adapterClass);
    if(guardedInv == null) {
        // Short circuit the lookup here for non-existent methods by linking an empty getter. If we just returned
        // null instead, BeansLinker would find final methods on the JavaSuperAdapter instead: getClass() and
        // wait().
        return new GuardedInvocation(MethodHandles.dropArguments(EMPTY_GETTER, 1,type.parameterList().subList(1,
                type.parameterCount())), guard).asType(descriptor);
    }

    final MethodHandle invocation = guardedInv.getInvocation();
    final MethodType invType = invocation.type();
    // For invocation typed R(T0, ...) create a dynamic method binder of type R(R, T0)
    final MethodHandle typedBinder = BIND_DYNAMIC_METHOD.asType(MethodType.methodType(invType.returnType(),
            invType.returnType(), invType.parameterType(0)));
    // For invocation typed R(T0, T1, ...) create a dynamic method binder of type R(R, T0, T1, ...)
    final MethodHandle droppingBinder = MethodHandles.dropArguments(typedBinder, 2,
            invType.parameterList().subList(1, invType.parameterCount()));
    // Finally, fold the invocation into the binder to produce a method handle that will bind every returned
    // DynamicMethod object from dyn:getMethod calls to the actual receiver
    // R(R(T0, T1, ...), T0, T1, ...)
    final MethodHandle bindingInvocation = MethodHandles.foldArguments(droppingBinder, invocation);

    final MethodHandle typedGetAdapter = asFilterType(GET_ADAPTER, 0, invType, type);
    final MethodHandle adaptedInvocation;
    if(hasFixedName) {
        adaptedInvocation = MethodHandles.filterArguments(bindingInvocation, 0, typedGetAdapter);
    } else {
        // Add a filter that'll prepend "super$" to each name passed to the variable-name "dyn:getMethod".
        final MethodHandle typedAddPrefix = asFilterType(ADD_PREFIX_TO_METHOD_NAME, 1, invType, type);
        adaptedInvocation = MethodHandles.filterArguments(bindingInvocation, 0, typedGetAdapter, typedAddPrefix);
    }

    return guardedInv.replaceMethods(adaptedInvocation, guard).asType(descriptor);
}
 
Example 13
Source File: JavaSuperAdapterLinker.java    From jdk8u_nashorn with GNU General Public License v2.0 4 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices)
        throws Exception {
    final Object objSuperAdapter = linkRequest.getReceiver();
    if(!(objSuperAdapter instanceof JavaSuperAdapter)) {
        return null;
    }

    final CallSiteDescriptor descriptor = linkRequest.getCallSiteDescriptor();
    if(!CallSiteDescriptorFactory.tokenizeOperators(descriptor).contains(GET_METHOD)) {
        // We only handle getMethod
        return null;
    }

    final Object adapter = ((JavaSuperAdapter)objSuperAdapter).getAdapter();

    // Replace argument (javaSuperAdapter, ...) => (adapter, ...) when delegating to BeansLinker
    final Object[] args = linkRequest.getArguments();
    args[0] = adapter;

    // Use R(T0, ...) => R(adapter.class, ...) call site type when delegating to BeansLinker.
    final MethodType type = descriptor.getMethodType();
    final Class<?> adapterClass = adapter.getClass();
    final boolean hasFixedName = descriptor.getNameTokenCount() > 2;
    final String opName = hasFixedName ? (DYN_GET_METHOD_FIXED + descriptor.getNameToken(
            CallSiteDescriptor.NAME_OPERAND)) : DYN_GET_METHOD;

    final CallSiteDescriptor newDescriptor = NashornCallSiteDescriptor.get(descriptor.getLookup(), opName,
            type.changeParameterType(0, adapterClass), 0);

    // Delegate to BeansLinker
    final GuardedInvocation guardedInv = NashornBeansLinker.getGuardedInvocation(
            BeansLinker.getLinkerForClass(adapterClass), linkRequest.replaceArguments(newDescriptor, args),
            linkerServices);

    final MethodHandle guard = IS_ADAPTER_OF_CLASS.bindTo(adapterClass);
    if(guardedInv == null) {
        // Short circuit the lookup here for non-existent methods by linking an empty getter. If we just returned
        // null instead, BeansLinker would find final methods on the JavaSuperAdapter instead: getClass() and
        // wait().
        return new GuardedInvocation(MethodHandles.dropArguments(EMPTY_GETTER, 1,type.parameterList().subList(1,
                type.parameterCount())), guard).asType(descriptor);
    }

    final MethodHandle invocation = guardedInv.getInvocation();
    final MethodType invType = invocation.type();
    // For invocation typed R(T0, ...) create a dynamic method binder of type Object(R, T0)
    final MethodHandle typedBinder = BIND_DYNAMIC_METHOD.asType(MethodType.methodType(Object.class,
            invType.returnType(), invType.parameterType(0)));
    // For invocation typed R(T0, T1, ...) create a dynamic method binder of type Object(R, T0, T1, ...)
    final MethodHandle droppingBinder = MethodHandles.dropArguments(typedBinder, 2,
            invType.parameterList().subList(1, invType.parameterCount()));
    // Finally, fold the invocation into the binder to produce a method handle that will bind every returned
    // DynamicMethod object from dyn:getMethod calls to the actual receiver
    // Object(R(T0, T1, ...), T0, T1, ...)
    final MethodHandle bindingInvocation = MethodHandles.foldArguments(droppingBinder, invocation);

    final MethodHandle typedGetAdapter = asFilterType(GET_ADAPTER, 0, invType, type);
    final MethodHandle adaptedInvocation;
    if(hasFixedName) {
        adaptedInvocation = MethodHandles.filterArguments(bindingInvocation, 0, typedGetAdapter);
    } else {
        // Add a filter that'll prepend "super$" to each name passed to the variable-name "dyn:getMethod".
        final MethodHandle typedAddPrefix = asFilterType(ADD_PREFIX_TO_METHOD_NAME, 1, invType, type);
        adaptedInvocation = MethodHandles.filterArguments(bindingInvocation, 0, typedGetAdapter, typedAddPrefix);
    }

    return guardedInv.replaceMethods(adaptedInvocation, guard).asType(descriptor);
}
 
Example 14
Source File: BoundCallableLinker.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
    final Object objBoundCallable = linkRequest.getReceiver();
    if(!(objBoundCallable instanceof BoundCallable)) {
        return null;
    }

    final CallSiteDescriptor descriptor = linkRequest.getCallSiteDescriptor();
    if (descriptor.getNameTokenCount() < 2 || !"dyn".equals(descriptor.getNameToken(CallSiteDescriptor.SCHEME))) {
        return null;
    }
    final String operation = descriptor.getNameToken(CallSiteDescriptor.OPERATOR);
    // We need to distinguish "dyn:new" from "dyn:call" because "dyn:call" sites have parameter list of the form
    // "callee, this, args", while "dyn:call" sites have "callee, args" -- they lack the "this" parameter.
    final boolean isCall;
    if ("new".equals(operation)) {
        isCall = false;
    } else if ("call".equals(operation)) {
        isCall = true;
    } else {
        // Only dyn:call and dyn:new are supported.
        return null;
    }
    final BoundCallable boundCallable = (BoundCallable)objBoundCallable;
    final Object callable = boundCallable.getCallable();
    final Object boundThis = boundCallable.getBoundThis();

    // We need to ask the linker services for a delegate invocation on the target callable.

    // Replace arguments (boundCallable[, this], args) => (callable[, boundThis], boundArgs, args) when delegating
    final Object[] args = linkRequest.getArguments();
    final Object[] boundArgs = boundCallable.getBoundArgs();
    final int argsLen = args.length;
    final int boundArgsLen = boundArgs.length;
    final Object[] newArgs = new Object[argsLen + boundArgsLen];
    newArgs[0] = callable;
    final int firstArgIndex;
    if (isCall) {
        newArgs[1] = boundThis;
        firstArgIndex = 2;
    } else {
        firstArgIndex = 1;
    }
    System.arraycopy(boundArgs, 0, newArgs, firstArgIndex, boundArgsLen);
    System.arraycopy(args, firstArgIndex, newArgs, firstArgIndex + boundArgsLen, argsLen - firstArgIndex);

    // Use R(T0, T1, T2, ...) => R(callable.class, boundThis.class, boundArg0.class, ..., boundArgn.class, T2, ...)
    // call site type when delegating to underlying linker (for dyn:new, there's no this).
    final MethodType type = descriptor.getMethodType();
    // Use R(T0, ...) => R(callable.class, ...)
    MethodType newMethodType = descriptor.getMethodType().changeParameterType(0, callable.getClass());
    if (isCall) {
        // R(callable.class, T1, ...) => R(callable.class, boundThis.class, ...)
        newMethodType = newMethodType.changeParameterType(1, boundThis == null? Object.class : boundThis.getClass());
    }
    // R(callable.class[, boundThis.class], T2, ...) => R(callable.class[, boundThis.class], boundArg0.class, ..., boundArgn.class, T2, ...)
    for(int i = boundArgs.length; i-- > 0;) {
        newMethodType = newMethodType.insertParameterTypes(firstArgIndex, boundArgs[i] == null ? Object.class : boundArgs[i].getClass());
    }
    final CallSiteDescriptor newDescriptor = descriptor.changeMethodType(newMethodType);

    // Delegate to target's linker
    final GuardedInvocation inv = linkerServices.getGuardedInvocation(linkRequest.replaceArguments(newDescriptor, newArgs));
    if(inv == null) {
        return null;
    }

    // Bind (callable[, boundThis], boundArgs) to the delegate handle
    final MethodHandle boundHandle = MethodHandles.insertArguments(inv.getInvocation(), 0,
            Arrays.copyOf(newArgs, firstArgIndex + boundArgs.length));
    final Class<?> p0Type = type.parameterType(0);
    final MethodHandle droppingHandle;
    if (isCall) {
        // Ignore incoming boundCallable and this
        droppingHandle = MethodHandles.dropArguments(boundHandle, 0, p0Type, type.parameterType(1));
    } else {
        // Ignore incoming boundCallable
        droppingHandle = MethodHandles.dropArguments(boundHandle, 0, p0Type);
    }
    // Identity guard on boundCallable object
    final MethodHandle newGuard = Guards.getIdentityGuard(boundCallable);
    return inv.replaceMethods(droppingHandle, newGuard.asType(newGuard.type().changeParameterType(0, p0Type)));
}
 
Example 15
Source File: JavaSuperAdapterLinker.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices)
        throws Exception {
    final Object objSuperAdapter = linkRequest.getReceiver();
    if(!(objSuperAdapter instanceof JavaSuperAdapter)) {
        return null;
    }

    final CallSiteDescriptor descriptor = linkRequest.getCallSiteDescriptor();
    if(!CallSiteDescriptorFactory.tokenizeOperators(descriptor).contains(GET_METHOD)) {
        // We only handle getMethod
        return null;
    }

    final Object adapter = ((JavaSuperAdapter)objSuperAdapter).getAdapter();

    // Replace argument (javaSuperAdapter, ...) => (adapter, ...) when delegating to BeansLinker
    final Object[] args = linkRequest.getArguments();
    args[0] = adapter;

    // Use R(T0, ...) => R(adapter.class, ...) call site type when delegating to BeansLinker.
    final MethodType type = descriptor.getMethodType();
    final Class<?> adapterClass = adapter.getClass();
    final boolean hasFixedName = descriptor.getNameTokenCount() > 2;
    final String opName = hasFixedName ? (DYN_GET_METHOD_FIXED + descriptor.getNameToken(
            CallSiteDescriptor.NAME_OPERAND)) : DYN_GET_METHOD;

    final CallSiteDescriptor newDescriptor = NashornCallSiteDescriptor.get(descriptor.getLookup(), opName,
            type.changeParameterType(0, adapterClass), 0);

    // Delegate to BeansLinker
    final GuardedInvocation guardedInv = NashornBeansLinker.getGuardedInvocation(
            BeansLinker.getLinkerForClass(adapterClass), linkRequest.replaceArguments(newDescriptor, args),
            linkerServices);

    final MethodHandle guard = IS_ADAPTER_OF_CLASS.bindTo(adapterClass);
    if(guardedInv == null) {
        // Short circuit the lookup here for non-existent methods by linking an empty getter. If we just returned
        // null instead, BeansLinker would find final methods on the JavaSuperAdapter instead: getClass() and
        // wait().
        return new GuardedInvocation(MethodHandles.dropArguments(EMPTY_GETTER, 1,type.parameterList().subList(1,
                type.parameterCount())), guard).asType(descriptor);
    }

    final MethodHandle invocation = guardedInv.getInvocation();
    final MethodType invType = invocation.type();
    // For invocation typed R(T0, ...) create a dynamic method binder of type Object(R, T0)
    final MethodHandle typedBinder = BIND_DYNAMIC_METHOD.asType(MethodType.methodType(Object.class,
            invType.returnType(), invType.parameterType(0)));
    // For invocation typed R(T0, T1, ...) create a dynamic method binder of type Object(R, T0, T1, ...)
    final MethodHandle droppingBinder = MethodHandles.dropArguments(typedBinder, 2,
            invType.parameterList().subList(1, invType.parameterCount()));
    // Finally, fold the invocation into the binder to produce a method handle that will bind every returned
    // DynamicMethod object from dyn:getMethod calls to the actual receiver
    // Object(R(T0, T1, ...), T0, T1, ...)
    final MethodHandle bindingInvocation = MethodHandles.foldArguments(droppingBinder, invocation);

    final MethodHandle typedGetAdapter = asFilterType(GET_ADAPTER, 0, invType, type);
    final MethodHandle adaptedInvocation;
    if(hasFixedName) {
        adaptedInvocation = MethodHandles.filterArguments(bindingInvocation, 0, typedGetAdapter);
    } else {
        // Add a filter that'll prepend "super$" to each name passed to the variable-name "dyn:getMethod".
        final MethodHandle typedAddPrefix = asFilterType(ADD_PREFIX_TO_METHOD_NAME, 1, invType, type);
        adaptedInvocation = MethodHandles.filterArguments(bindingInvocation, 0, typedGetAdapter, typedAddPrefix);
    }

    return guardedInv.replaceMethods(adaptedInvocation, guard).asType(descriptor);
}
 
Example 16
Source File: BoundDynamicMethodLinker.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(LinkRequest linkRequest, LinkerServices linkerServices) throws Exception {
    final Object objBoundDynamicMethod = linkRequest.getReceiver();
    if(!(objBoundDynamicMethod instanceof BoundDynamicMethod)) {
        return null;
    }

    final BoundDynamicMethod boundDynamicMethod = (BoundDynamicMethod)objBoundDynamicMethod;
    final Object dynamicMethod = boundDynamicMethod.getDynamicMethod();
    final Object boundThis = boundDynamicMethod.getBoundThis();

    // Replace arguments (boundDynamicMethod, this, ...) => (dynamicMethod, boundThis, ...) when delegating to
    // BeansLinker
    final Object[] args = linkRequest.getArguments();
    args[0] = dynamicMethod;
    args[1] = boundThis;

    // Use R(T0, T1, ...) => R(dynamicMethod.class, boundThis.class, ...) call site type when delegating to
    // BeansLinker.
    final CallSiteDescriptor descriptor = linkRequest.getCallSiteDescriptor();
    final MethodType type = descriptor.getMethodType();
    final Class<?> dynamicMethodClass = dynamicMethod.getClass();
    final CallSiteDescriptor newDescriptor = descriptor.changeMethodType(
            type.changeParameterType(0, dynamicMethodClass).changeParameterType(1, boundThis.getClass()));

    // Delegate to BeansLinker
    final GuardedInvocation inv = NashornBeansLinker.getGuardedInvocation(BeansLinker.getLinkerForClass(dynamicMethodClass),
            linkRequest.replaceArguments(newDescriptor, args), linkerServices);
    if(inv == null) {
        return null;
    }

    // Bind (dynamicMethod, boundThis) to the handle
    final MethodHandle boundHandle = MethodHandles.insertArguments(inv.getInvocation(), 0, dynamicMethod, boundThis);
    final Class<?> p0Type = type.parameterType(0);
    // Ignore incoming (boundDynamicMethod, this)
    final MethodHandle droppingHandle = MethodHandles.dropArguments(boundHandle, 0, p0Type, type.parameterType(1));
    // Identity guard on boundDynamicMethod object
    final MethodHandle newGuard = Guards.getIdentityGuard(boundDynamicMethod);

    return inv.replaceMethods(droppingHandle, newGuard.asType(newGuard.type().changeParameterType(0, p0Type)));
}
 
Example 17
Source File: BoundCallableLinker.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
    final Object objBoundCallable = linkRequest.getReceiver();
    if(!(objBoundCallable instanceof BoundCallable)) {
        return null;
    }

    final CallSiteDescriptor descriptor = linkRequest.getCallSiteDescriptor();
    if (descriptor.getNameTokenCount() < 2 || !"dyn".equals(descriptor.getNameToken(CallSiteDescriptor.SCHEME))) {
        return null;
    }
    final String operation = descriptor.getNameToken(CallSiteDescriptor.OPERATOR);
    // We need to distinguish "dyn:new" from "dyn:call" because "dyn:call" sites have parameter list of the form
    // "callee, this, args", while "dyn:call" sites have "callee, args" -- they lack the "this" parameter.
    final boolean isCall;
    if ("new".equals(operation)) {
        isCall = false;
    } else if ("call".equals(operation)) {
        isCall = true;
    } else {
        // Only dyn:call and dyn:new are supported.
        return null;
    }
    final BoundCallable boundCallable = (BoundCallable)objBoundCallable;
    final Object callable = boundCallable.getCallable();
    final Object boundThis = boundCallable.getBoundThis();

    // We need to ask the linker services for a delegate invocation on the target callable.

    // Replace arguments (boundCallable[, this], args) => (callable[, boundThis], boundArgs, args) when delegating
    final Object[] args = linkRequest.getArguments();
    final Object[] boundArgs = boundCallable.getBoundArgs();
    final int argsLen = args.length;
    final int boundArgsLen = boundArgs.length;
    final Object[] newArgs = new Object[argsLen + boundArgsLen];
    newArgs[0] = callable;
    final int firstArgIndex;
    if (isCall) {
        newArgs[1] = boundThis;
        firstArgIndex = 2;
    } else {
        firstArgIndex = 1;
    }
    System.arraycopy(boundArgs, 0, newArgs, firstArgIndex, boundArgsLen);
    System.arraycopy(args, firstArgIndex, newArgs, firstArgIndex + boundArgsLen, argsLen - firstArgIndex);

    // Use R(T0, T1, T2, ...) => R(callable.class, boundThis.class, boundArg0.class, ..., boundArgn.class, T2, ...)
    // call site type when delegating to underlying linker (for dyn:new, there's no this).
    final MethodType type = descriptor.getMethodType();
    // Use R(T0, ...) => R(callable.class, ...)
    MethodType newMethodType = descriptor.getMethodType().changeParameterType(0, callable.getClass());
    if (isCall) {
        // R(callable.class, T1, ...) => R(callable.class, boundThis.class, ...)
        newMethodType = newMethodType.changeParameterType(1, boundThis == null? Object.class : boundThis.getClass());
    }
    // R(callable.class[, boundThis.class], T2, ...) => R(callable.class[, boundThis.class], boundArg0.class, ..., boundArgn.class, T2, ...)
    for(int i = boundArgs.length; i-- > 0;) {
        newMethodType = newMethodType.insertParameterTypes(firstArgIndex, boundArgs[i] == null ? Object.class : boundArgs[i].getClass());
    }
    final CallSiteDescriptor newDescriptor = descriptor.changeMethodType(newMethodType);

    // Delegate to target's linker
    final GuardedInvocation inv = linkerServices.getGuardedInvocation(linkRequest.replaceArguments(newDescriptor, newArgs));
    if(inv == null) {
        return null;
    }

    // Bind (callable[, boundThis], boundArgs) to the delegate handle
    final MethodHandle boundHandle = MethodHandles.insertArguments(inv.getInvocation(), 0,
            Arrays.copyOf(newArgs, firstArgIndex + boundArgs.length));
    final Class<?> p0Type = type.parameterType(0);
    final MethodHandle droppingHandle;
    if (isCall) {
        // Ignore incoming boundCallable and this
        droppingHandle = MethodHandles.dropArguments(boundHandle, 0, p0Type, type.parameterType(1));
    } else {
        // Ignore incoming boundCallable
        droppingHandle = MethodHandles.dropArguments(boundHandle, 0, p0Type);
    }
    // Identity guard on boundCallable object
    final MethodHandle newGuard = Guards.getIdentityGuard(boundCallable);
    return inv.replaceMethods(droppingHandle, newGuard.asType(newGuard.type().changeParameterType(0, p0Type)));
}
 
Example 18
Source File: BoundCallableLinker.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
    final Object objBoundCallable = linkRequest.getReceiver();
    if(!(objBoundCallable instanceof BoundCallable)) {
        return null;
    }

    final CallSiteDescriptor descriptor = linkRequest.getCallSiteDescriptor();
    if (descriptor.getNameTokenCount() < 2 || !"dyn".equals(descriptor.getNameToken(CallSiteDescriptor.SCHEME))) {
        return null;
    }
    final String operation = descriptor.getNameToken(CallSiteDescriptor.OPERATOR);
    // We need to distinguish "dyn:new" from "dyn:call" because "dyn:call" sites have parameter list of the form
    // "callee, this, args", while "dyn:call" sites have "callee, args" -- they lack the "this" parameter.
    final boolean isCall;
    if ("new".equals(operation)) {
        isCall = false;
    } else if ("call".equals(operation)) {
        isCall = true;
    } else {
        // Only dyn:call and dyn:new are supported.
        return null;
    }
    final BoundCallable boundCallable = (BoundCallable)objBoundCallable;
    final Object callable = boundCallable.getCallable();
    final Object boundThis = boundCallable.getBoundThis();

    // We need to ask the linker services for a delegate invocation on the target callable.

    // Replace arguments (boundCallable[, this], args) => (callable[, boundThis], boundArgs, args) when delegating
    final Object[] args = linkRequest.getArguments();
    final Object[] boundArgs = boundCallable.getBoundArgs();
    final int argsLen = args.length;
    final int boundArgsLen = boundArgs.length;
    final Object[] newArgs = new Object[argsLen + boundArgsLen];
    newArgs[0] = callable;
    final int firstArgIndex;
    if (isCall) {
        newArgs[1] = boundThis;
        firstArgIndex = 2;
    } else {
        firstArgIndex = 1;
    }
    System.arraycopy(boundArgs, 0, newArgs, firstArgIndex, boundArgsLen);
    System.arraycopy(args, firstArgIndex, newArgs, firstArgIndex + boundArgsLen, argsLen - firstArgIndex);

    // Use R(T0, T1, T2, ...) => R(callable.class, boundThis.class, boundArg0.class, ..., boundArgn.class, T2, ...)
    // call site type when delegating to underlying linker (for dyn:new, there's no this).
    final MethodType type = descriptor.getMethodType();
    // Use R(T0, ...) => R(callable.class, ...)
    MethodType newMethodType = descriptor.getMethodType().changeParameterType(0, callable.getClass());
    if (isCall) {
        // R(callable.class, T1, ...) => R(callable.class, boundThis.class, ...)
        newMethodType = newMethodType.changeParameterType(1, boundThis == null? Object.class : boundThis.getClass());
    }
    // R(callable.class[, boundThis.class], T2, ...) => R(callable.class[, boundThis.class], boundArg0.class, ..., boundArgn.class, T2, ...)
    for(int i = boundArgs.length; i-- > 0;) {
        newMethodType = newMethodType.insertParameterTypes(firstArgIndex, boundArgs[i] == null ? Object.class : boundArgs[i].getClass());
    }
    final CallSiteDescriptor newDescriptor = descriptor.changeMethodType(newMethodType);

    // Delegate to target's linker
    final GuardedInvocation inv = linkerServices.getGuardedInvocation(linkRequest.replaceArguments(newDescriptor, newArgs));
    if(inv == null) {
        return null;
    }

    // Bind (callable[, boundThis], boundArgs) to the delegate handle
    final MethodHandle boundHandle = MethodHandles.insertArguments(inv.getInvocation(), 0,
            Arrays.copyOf(newArgs, firstArgIndex + boundArgs.length));
    final Class<?> p0Type = type.parameterType(0);
    final MethodHandle droppingHandle;
    if (isCall) {
        // Ignore incoming boundCallable and this
        droppingHandle = MethodHandles.dropArguments(boundHandle, 0, p0Type, type.parameterType(1));
    } else {
        // Ignore incoming boundCallable
        droppingHandle = MethodHandles.dropArguments(boundHandle, 0, p0Type);
    }
    // Identity guard on boundCallable object
    final MethodHandle newGuard = Guards.getIdentityGuard(boundCallable);
    return inv.replaceMethods(droppingHandle, newGuard.asType(newGuard.type().changeParameterType(0, p0Type)));
}
 
Example 19
Source File: JavaSuperAdapterLinker.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices)
        throws Exception {
    final Object objSuperAdapter = linkRequest.getReceiver();
    if(!(objSuperAdapter instanceof JavaSuperAdapter)) {
        return null;
    }

    final CallSiteDescriptor descriptor = linkRequest.getCallSiteDescriptor();
    if(!CallSiteDescriptorFactory.tokenizeOperators(descriptor).contains(GET_METHOD)) {
        // We only handle getMethod
        return null;
    }

    final Object adapter = ((JavaSuperAdapter)objSuperAdapter).getAdapter();

    // Replace argument (javaSuperAdapter, ...) => (adapter, ...) when delegating to BeansLinker
    final Object[] args = linkRequest.getArguments();
    args[0] = adapter;

    // Use R(T0, ...) => R(adapter.class, ...) call site type when delegating to BeansLinker.
    final MethodType type = descriptor.getMethodType();
    final Class<?> adapterClass = adapter.getClass();
    final boolean hasFixedName = descriptor.getNameTokenCount() > 2;
    final String opName = hasFixedName ? (DYN_GET_METHOD_FIXED + descriptor.getNameToken(
            CallSiteDescriptor.NAME_OPERAND)) : DYN_GET_METHOD;

    final CallSiteDescriptor newDescriptor = NashornCallSiteDescriptor.get(descriptor.getLookup(), opName,
            type.changeParameterType(0, adapterClass), 0);

    // Delegate to BeansLinker
    final GuardedInvocation guardedInv = NashornBeansLinker.getGuardedInvocation(
            BeansLinker.getLinkerForClass(adapterClass), linkRequest.replaceArguments(newDescriptor, args),
            linkerServices);

    final MethodHandle guard = IS_ADAPTER_OF_CLASS.bindTo(adapterClass);
    if(guardedInv == null) {
        // Short circuit the lookup here for non-existent methods by linking an empty getter. If we just returned
        // null instead, BeansLinker would find final methods on the JavaSuperAdapter instead: getClass() and
        // wait().
        return new GuardedInvocation(MethodHandles.dropArguments(EMPTY_GETTER, 1,type.parameterList().subList(1,
                type.parameterCount())), guard).asType(descriptor);
    }

    final MethodHandle invocation = guardedInv.getInvocation();
    final MethodType invType = invocation.type();
    // For invocation typed R(T0, ...) create a dynamic method binder of type Object(R, T0)
    final MethodHandle typedBinder = BIND_DYNAMIC_METHOD.asType(MethodType.methodType(Object.class,
            invType.returnType(), invType.parameterType(0)));
    // For invocation typed R(T0, T1, ...) create a dynamic method binder of type Object(R, T0, T1, ...)
    final MethodHandle droppingBinder = MethodHandles.dropArguments(typedBinder, 2,
            invType.parameterList().subList(1, invType.parameterCount()));
    // Finally, fold the invocation into the binder to produce a method handle that will bind every returned
    // DynamicMethod object from dyn:getMethod calls to the actual receiver
    // Object(R(T0, T1, ...), T0, T1, ...)
    final MethodHandle bindingInvocation = MethodHandles.foldArguments(droppingBinder, invocation);

    final MethodHandle typedGetAdapter = asFilterType(GET_ADAPTER, 0, invType, type);
    final MethodHandle adaptedInvocation;
    if(hasFixedName) {
        adaptedInvocation = MethodHandles.filterArguments(bindingInvocation, 0, typedGetAdapter);
    } else {
        // Add a filter that'll prepend "super$" to each name passed to the variable-name "dyn:getMethod".
        final MethodHandle typedAddPrefix = asFilterType(ADD_PREFIX_TO_METHOD_NAME, 1, invType, type);
        adaptedInvocation = MethodHandles.filterArguments(bindingInvocation, 0, typedGetAdapter, typedAddPrefix);
    }

    return guardedInv.replaceMethods(adaptedInvocation, guard).asType(descriptor);
}
 
Example 20
Source File: BoundCallableLinker.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
    final Object objBoundCallable = linkRequest.getReceiver();
    if(!(objBoundCallable instanceof BoundCallable)) {
        return null;
    }

    final CallSiteDescriptor descriptor = linkRequest.getCallSiteDescriptor();
    if (descriptor.getNameTokenCount() < 2 || !"dyn".equals(descriptor.getNameToken(CallSiteDescriptor.SCHEME))) {
        return null;
    }
    final String operation = descriptor.getNameToken(CallSiteDescriptor.OPERATOR);
    // We need to distinguish "dyn:new" from "dyn:call" because "dyn:call" sites have parameter list of the form
    // "callee, this, args", while "dyn:call" sites have "callee, args" -- they lack the "this" parameter.
    final boolean isCall;
    if ("new".equals(operation)) {
        isCall = false;
    } else if ("call".equals(operation)) {
        isCall = true;
    } else {
        // Only dyn:call and dyn:new are supported.
        return null;
    }
    final BoundCallable boundCallable = (BoundCallable)objBoundCallable;
    final Object callable = boundCallable.getCallable();
    final Object boundThis = boundCallable.getBoundThis();

    // We need to ask the linker services for a delegate invocation on the target callable.

    // Replace arguments (boundCallable[, this], args) => (callable[, boundThis], boundArgs, args) when delegating
    final Object[] args = linkRequest.getArguments();
    final Object[] boundArgs = boundCallable.getBoundArgs();
    final int argsLen = args.length;
    final int boundArgsLen = boundArgs.length;
    final Object[] newArgs = new Object[argsLen + boundArgsLen];
    newArgs[0] = callable;
    final int firstArgIndex;
    if (isCall) {
        newArgs[1] = boundThis;
        firstArgIndex = 2;
    } else {
        firstArgIndex = 1;
    }
    System.arraycopy(boundArgs, 0, newArgs, firstArgIndex, boundArgsLen);
    System.arraycopy(args, firstArgIndex, newArgs, firstArgIndex + boundArgsLen, argsLen - firstArgIndex);

    // Use R(T0, T1, T2, ...) => R(callable.class, boundThis.class, boundArg0.class, ..., boundArgn.class, T2, ...)
    // call site type when delegating to underlying linker (for dyn:new, there's no this).
    final MethodType type = descriptor.getMethodType();
    // Use R(T0, ...) => R(callable.class, ...)
    MethodType newMethodType = descriptor.getMethodType().changeParameterType(0, callable.getClass());
    if (isCall) {
        // R(callable.class, T1, ...) => R(callable.class, boundThis.class, ...)
        newMethodType = newMethodType.changeParameterType(1, boundThis == null? Object.class : boundThis.getClass());
    }
    // R(callable.class[, boundThis.class], T2, ...) => R(callable.class[, boundThis.class], boundArg0.class, ..., boundArgn.class, T2, ...)
    for(int i = boundArgs.length; i-- > 0;) {
        newMethodType = newMethodType.insertParameterTypes(firstArgIndex, boundArgs[i] == null ? Object.class : boundArgs[i].getClass());
    }
    final CallSiteDescriptor newDescriptor = descriptor.changeMethodType(newMethodType);

    // Delegate to target's linker
    final GuardedInvocation inv = linkerServices.getGuardedInvocation(linkRequest.replaceArguments(newDescriptor, newArgs));
    if(inv == null) {
        return null;
    }

    // Bind (callable[, boundThis], boundArgs) to the delegate handle
    final MethodHandle boundHandle = MethodHandles.insertArguments(inv.getInvocation(), 0,
            Arrays.copyOf(newArgs, firstArgIndex + boundArgs.length));
    final Class<?> p0Type = type.parameterType(0);
    final MethodHandle droppingHandle;
    if (isCall) {
        // Ignore incoming boundCallable and this
        droppingHandle = MethodHandles.dropArguments(boundHandle, 0, p0Type, type.parameterType(1));
    } else {
        // Ignore incoming boundCallable
        droppingHandle = MethodHandles.dropArguments(boundHandle, 0, p0Type);
    }
    // Identity guard on boundCallable object
    final MethodHandle newGuard = Guards.getIdentityGuard(boundCallable);
    return inv.replaceMethods(droppingHandle, newGuard.asType(newGuard.type().changeParameterType(0, p0Type)));
}