JavaSuperAdapterLinker.java revision 1470:04ed602df062
1/*
2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package jdk.nashorn.internal.runtime.linker;
27
28import static jdk.nashorn.internal.lookup.Lookup.EMPTY_GETTER;
29import static jdk.nashorn.internal.runtime.linker.JavaAdapterBytecodeGenerator.SUPER_PREFIX;
30
31import java.lang.invoke.MethodHandle;
32import java.lang.invoke.MethodHandles;
33import java.lang.invoke.MethodType;
34import jdk.internal.dynalink.CallSiteDescriptor;
35import jdk.internal.dynalink.beans.BeansLinker;
36import jdk.internal.dynalink.linker.GuardedInvocation;
37import jdk.internal.dynalink.linker.LinkRequest;
38import jdk.internal.dynalink.linker.LinkerServices;
39import jdk.internal.dynalink.linker.TypeBasedGuardingDynamicLinker;
40import jdk.internal.dynalink.support.Lookup;
41import jdk.nashorn.internal.runtime.ScriptRuntime;
42
43/**
44 * A linker for instances of {@code JavaSuperAdapter}. Only links {@code getMethod} calls, by forwarding them to the
45 * bean linker for the adapter class and prepending {@code super$} to method names.
46 *
47 */
48final class JavaSuperAdapterLinker implements TypeBasedGuardingDynamicLinker {
49    private static final String GET_METHOD = "getMethod";
50    private static final String DYN_GET_METHOD = "dyn:" + GET_METHOD;
51    private static final String DYN_GET_METHOD_FIXED = DYN_GET_METHOD + ":" + SUPER_PREFIX;
52
53    private static final MethodHandle ADD_PREFIX_TO_METHOD_NAME;
54    private static final MethodHandle BIND_DYNAMIC_METHOD;
55    private static final MethodHandle GET_ADAPTER;
56    private static final MethodHandle IS_ADAPTER_OF_CLASS;
57
58    static {
59        final Lookup lookup = new Lookup(MethodHandles.lookup());
60        ADD_PREFIX_TO_METHOD_NAME = lookup.findOwnStatic("addPrefixToMethodName", Object.class, Object.class);
61        BIND_DYNAMIC_METHOD = lookup.findOwnStatic("bindDynamicMethod", Object.class, Object.class, Object.class);
62        GET_ADAPTER = lookup.findVirtual(JavaSuperAdapter.class, "getAdapter", MethodType.methodType(Object.class));
63        IS_ADAPTER_OF_CLASS = lookup.findOwnStatic("isAdapterOfClass", boolean.class, Class.class, Object.class);
64    }
65
66    @Override
67    public boolean canLinkType(final Class<?> type) {
68        return type == JavaSuperAdapter.class;
69    }
70
71    @Override
72    public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices)
73            throws Exception {
74        final Object objSuperAdapter = linkRequest.getReceiver();
75        if(!(objSuperAdapter instanceof JavaSuperAdapter)) {
76            return null;
77        }
78
79        final CallSiteDescriptor descriptor = linkRequest.getCallSiteDescriptor();
80        if(!descriptor.tokenizeOperators().contains(GET_METHOD)) {
81            // We only handle getMethod
82            return null;
83        }
84
85        final Object adapter = ((JavaSuperAdapter)objSuperAdapter).getAdapter();
86
87        // Replace argument (javaSuperAdapter, ...) => (adapter, ...) when delegating to BeansLinker
88        final Object[] args = linkRequest.getArguments();
89        args[0] = adapter;
90
91        // Use R(T0, ...) => R(adapter.class, ...) call site type when delegating to BeansLinker.
92        final MethodType type = descriptor.getMethodType();
93        final Class<?> adapterClass = adapter.getClass();
94        final boolean hasFixedName = descriptor.getNameTokenCount() > 2;
95        final String opName = hasFixedName ? (DYN_GET_METHOD_FIXED + descriptor.getNameToken(
96                CallSiteDescriptor.NAME_OPERAND)) : DYN_GET_METHOD;
97
98        final CallSiteDescriptor newDescriptor = NashornCallSiteDescriptor.get(descriptor.getLookup(), opName,
99                type.changeParameterType(0, adapterClass), 0);
100
101        // Delegate to BeansLinker
102        final GuardedInvocation guardedInv = NashornBeansLinker.getGuardedInvocation(
103                BeansLinker.getLinkerForClass(adapterClass), linkRequest.replaceArguments(newDescriptor, args),
104                linkerServices);
105
106        final MethodHandle guard = IS_ADAPTER_OF_CLASS.bindTo(adapterClass);
107        if(guardedInv == null) {
108            // Short circuit the lookup here for non-existent methods by linking an empty getter. If we just returned
109            // null instead, BeansLinker would find final methods on the JavaSuperAdapter instead: getClass() and
110            // wait().
111            return new GuardedInvocation(MethodHandles.dropArguments(EMPTY_GETTER, 1,type.parameterList().subList(1,
112                    type.parameterCount())), guard).asType(descriptor);
113        }
114
115        final MethodHandle invocation = guardedInv.getInvocation();
116        final MethodType invType = invocation.type();
117        // For invocation typed R(T0, ...) create a dynamic method binder of type Object(R, T0)
118        final MethodHandle typedBinder = BIND_DYNAMIC_METHOD.asType(MethodType.methodType(Object.class,
119                invType.returnType(), invType.parameterType(0)));
120        // For invocation typed R(T0, T1, ...) create a dynamic method binder of type Object(R, T0, T1, ...)
121        final MethodHandle droppingBinder = MethodHandles.dropArguments(typedBinder, 2,
122                invType.parameterList().subList(1, invType.parameterCount()));
123        // Finally, fold the invocation into the binder to produce a method handle that will bind every returned
124        // DynamicMethod object from dyn:getMethod calls to the actual receiver
125        // Object(R(T0, T1, ...), T0, T1, ...)
126        final MethodHandle bindingInvocation = MethodHandles.foldArguments(droppingBinder, invocation);
127
128        final MethodHandle typedGetAdapter = asFilterType(GET_ADAPTER, 0, invType, type);
129        final MethodHandle adaptedInvocation;
130        if(hasFixedName) {
131            adaptedInvocation = MethodHandles.filterArguments(bindingInvocation, 0, typedGetAdapter);
132        } else {
133            // Add a filter that'll prepend "super$" to each name passed to the variable-name "dyn:getMethod".
134            final MethodHandle typedAddPrefix = asFilterType(ADD_PREFIX_TO_METHOD_NAME, 1, invType, type);
135            adaptedInvocation = MethodHandles.filterArguments(bindingInvocation, 0, typedGetAdapter, typedAddPrefix);
136        }
137
138        return guardedInv.replaceMethods(adaptedInvocation, guard).asType(descriptor);
139    }
140
141    /**
142     * Adapts the type of a method handle used as a filter in a position from a source method type to a target method type.
143     * @param filter the filter method handle
144     * @param pos the position in the argument list that it's filtering
145     * @param targetType the target method type for filtering
146     * @param sourceType the source method type for filtering
147     * @return a type adapted filter
148     */
149    private static MethodHandle asFilterType(final MethodHandle filter, final int pos, final MethodType targetType, final MethodType sourceType) {
150        return filter.asType(MethodType.methodType(targetType.parameterType(pos), sourceType.parameterType(pos)));
151    }
152
153    @SuppressWarnings("unused")
154    private static Object addPrefixToMethodName(final Object name) {
155        return SUPER_PREFIX.concat(String.valueOf(name));
156    }
157
158    /**
159     * Used to transform the return value of getMethod; transform a {@code DynamicMethod} into a
160     * {@code BoundDynamicMethod} while also accounting for the possibility of a non-existent method.
161     * @param dynamicMethod the dynamic method to bind
162     * @param boundThis the adapter underlying a super adapter, to which the dynamic method is bound.
163     * @return a dynamic method bound to the adapter instance.
164     */
165    @SuppressWarnings("unused")
166    private static Object bindDynamicMethod(final Object dynamicMethod, final Object boundThis) {
167        return dynamicMethod == null ? ScriptRuntime.UNDEFINED : Bootstrap.bindCallable(dynamicMethod, boundThis, null);
168    }
169
170    /**
171     * Used as the guard of linkages, as the receiver is not guaranteed to be a JavaSuperAdapter.
172     * @param clazz the class the receiver's adapter is tested against.
173     * @param obj receiver
174     * @return true if the receiver is a super adapter, and its underlying adapter is of the specified class
175     */
176    @SuppressWarnings("unused")
177    private static boolean isAdapterOfClass(final Class<?> clazz, final Object obj) {
178        return obj instanceof JavaSuperAdapter && clazz == (((JavaSuperAdapter)obj).getAdapter()).getClass();
179    }
180}
181