JSObjectLinker.java revision 1147:889c5b47de69
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 java.lang.invoke.MethodHandle;
29import java.lang.invoke.MethodHandles;
30import java.lang.invoke.MethodType;
31import java.util.HashMap;
32import java.util.Map;
33import javax.script.Bindings;
34import jdk.internal.dynalink.CallSiteDescriptor;
35import jdk.internal.dynalink.linker.GuardedInvocation;
36import jdk.internal.dynalink.linker.GuardedTypeConversion;
37import jdk.internal.dynalink.linker.GuardingTypeConverterFactory;
38import jdk.internal.dynalink.linker.LinkRequest;
39import jdk.internal.dynalink.linker.LinkerServices;
40import jdk.internal.dynalink.linker.TypeBasedGuardingDynamicLinker;
41import jdk.internal.dynalink.support.CallSiteDescriptorFactory;
42import jdk.nashorn.api.scripting.JSObject;
43import jdk.nashorn.internal.lookup.MethodHandleFactory;
44import jdk.nashorn.internal.lookup.MethodHandleFunctionality;
45import jdk.nashorn.internal.runtime.ConsString;
46import jdk.nashorn.internal.runtime.JSType;
47
48/**
49 * A Dynalink linker to handle web browser built-in JS (DOM etc.) objects as well
50 * as ScriptObjects from other Nashorn contexts.
51 */
52final class JSObjectLinker implements TypeBasedGuardingDynamicLinker, GuardingTypeConverterFactory {
53    private final NashornBeansLinker nashornBeansLinker;
54
55    JSObjectLinker(final NashornBeansLinker nashornBeansLinker) {
56        this.nashornBeansLinker = nashornBeansLinker;
57    }
58
59    @Override
60    public boolean canLinkType(final Class<?> type) {
61        return canLinkTypeStatic(type);
62    }
63
64    static boolean canLinkTypeStatic(final Class<?> type) {
65        // can link JSObject also handles Map, Bindings to make
66        // sure those are not JSObjects.
67        return Map.class.isAssignableFrom(type) ||
68               Bindings.class.isAssignableFrom(type) ||
69               JSObject.class.isAssignableFrom(type);
70    }
71
72    @Override
73    public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception {
74        final LinkRequest requestWithoutContext = request.withoutRuntimeContext(); // Nashorn has no runtime context
75        final Object self = requestWithoutContext.getReceiver();
76        final CallSiteDescriptor desc = requestWithoutContext.getCallSiteDescriptor();
77
78        if (desc.getNameTokenCount() < 2 || !"dyn".equals(desc.getNameToken(CallSiteDescriptor.SCHEME))) {
79            // We only support standard "dyn:*[:*]" operations
80            return null;
81        }
82
83        final GuardedInvocation inv;
84        if (self instanceof JSObject) {
85            inv = lookup(desc, request, linkerServices);
86        } else if (self instanceof Map || self instanceof Bindings) {
87            // guard to make sure the Map or Bindings does not turn into JSObject later!
88            final GuardedInvocation beanInv = nashornBeansLinker.getGuardedInvocation(request, linkerServices);
89            inv = new GuardedInvocation(beanInv.getInvocation(),
90                NashornGuards.combineGuards(beanInv.getGuard(), NashornGuards.getNotJSObjectGuard()));
91        } else {
92            throw new AssertionError(); // Should never reach here.
93        }
94
95        return Bootstrap.asTypeSafeReturn(inv, linkerServices, desc);
96    }
97
98    @Override
99    public GuardedTypeConversion convertToType(final Class<?> sourceType, final Class<?> targetType) throws Exception {
100        final boolean sourceIsAlwaysJSObject = JSObject.class.isAssignableFrom(sourceType);
101        if(!sourceIsAlwaysJSObject && !sourceType.isAssignableFrom(JSObject.class)) {
102            return null;
103        }
104
105        final MethodHandle converter = CONVERTERS.get(targetType);
106        if(converter == null) {
107            return null;
108        }
109
110        return new GuardedTypeConversion(new GuardedInvocation(converter, sourceIsAlwaysJSObject ? null : IS_JSOBJECT_GUARD).asType(MethodType.methodType(targetType, sourceType)), true);
111    }
112
113
114    private GuardedInvocation lookup(final CallSiteDescriptor desc, final LinkRequest request, final LinkerServices linkerServices) throws Exception {
115        final String operator = CallSiteDescriptorFactory.tokenizeOperators(desc).get(0);
116        final int c = desc.getNameTokenCount();
117
118        switch (operator) {
119            case "getProp":
120            case "getElem":
121            case "getMethod":
122                if (c > 2) {
123                    return findGetMethod(desc);
124                }
125            // For indexed get, we want get GuardedInvocation beans linker and pass it.
126            // JSObjectLinker.get uses this fallback getter for explicit signature method access.
127            return findGetIndexMethod(nashornBeansLinker.getGuardedInvocation(request, linkerServices));
128            case "setProp":
129            case "setElem":
130                return c > 2 ? findSetMethod(desc) : findSetIndexMethod();
131            case "call":
132                return findCallMethod(desc);
133            case "new":
134                return findNewMethod(desc);
135            default:
136                return null;
137        }
138    }
139
140    private static GuardedInvocation findGetMethod(final CallSiteDescriptor desc) {
141        final String name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
142        final MethodHandle getter = MH.insertArguments(JSOBJECT_GETMEMBER, 1, name);
143        return new GuardedInvocation(getter, IS_JSOBJECT_GUARD);
144    }
145
146    private static GuardedInvocation findGetIndexMethod(final GuardedInvocation inv) {
147        final MethodHandle getter = MH.insertArguments(JSOBJECTLINKER_GET, 0, inv.getInvocation());
148        return inv.replaceMethods(getter, inv.getGuard());
149    }
150
151    private static GuardedInvocation findSetMethod(final CallSiteDescriptor desc) {
152        final MethodHandle getter = MH.insertArguments(JSOBJECT_SETMEMBER, 1, desc.getNameToken(2));
153        return new GuardedInvocation(getter, IS_JSOBJECT_GUARD);
154    }
155
156    private static GuardedInvocation findSetIndexMethod() {
157        return new GuardedInvocation(JSOBJECTLINKER_PUT, IS_JSOBJECT_GUARD);
158    }
159
160    private static GuardedInvocation findCallMethod(final CallSiteDescriptor desc) {
161        // TODO: if call site is already a vararg, don't do asCollector
162        MethodHandle mh = JSOBJECT_CALL;
163        if (NashornCallSiteDescriptor.isApplyToCall(desc)) {
164            mh = MH.insertArguments(JSOBJECT_CALL_TO_APPLY, 0, JSOBJECT_CALL);
165        }
166        return new GuardedInvocation(MH.asCollector(mh, Object[].class, desc.getMethodType().parameterCount() - 2), IS_JSOBJECT_GUARD);
167    }
168
169    private static GuardedInvocation findNewMethod(final CallSiteDescriptor desc) {
170        final MethodHandle func = MH.asCollector(JSOBJECT_NEW, Object[].class, desc.getMethodType().parameterCount() - 1);
171        return new GuardedInvocation(func, IS_JSOBJECT_GUARD);
172    }
173
174    @SuppressWarnings("unused")
175    private static boolean isJSObject(final Object self) {
176        return self instanceof JSObject;
177    }
178
179    @SuppressWarnings("unused")
180    private static Object get(final MethodHandle fallback, final Object jsobj, final Object key)
181        throws Throwable {
182        if (key instanceof Integer) {
183            return ((JSObject)jsobj).getSlot((Integer)key);
184        } else if (key instanceof Number) {
185            final int index = getIndex((Number)key);
186            if (index > -1) {
187                return ((JSObject)jsobj).getSlot(index);
188            }
189        } else if (key instanceof String || key instanceof ConsString) {
190            final String name = key.toString();
191            // get with method name and signature. delegate it to beans linker!
192            if (name.indexOf('(') != -1) {
193                return fallback.invokeExact(jsobj, (Object) name);
194            }
195            return ((JSObject)jsobj).getMember(name);
196        }
197        return null;
198    }
199
200    @SuppressWarnings("unused")
201    private static void put(final Object jsobj, final Object key, final Object value) {
202        if (key instanceof Integer) {
203            ((JSObject)jsobj).setSlot((Integer)key, value);
204        } else if (key instanceof Number) {
205            ((JSObject)jsobj).setSlot(getIndex((Number)key), value);
206        } else if (key instanceof String || key instanceof ConsString) {
207            ((JSObject)jsobj).setMember(key.toString(), value);
208        }
209    }
210
211    @SuppressWarnings("unused")
212    private static int toInt32(final JSObject obj) {
213        return JSType.toInt32(toNumber(obj));
214    }
215
216    @SuppressWarnings("unused")
217    private static long toLong(final JSObject obj) {
218        return JSType.toLong(toNumber(obj));
219    }
220
221    private static double toNumber(final JSObject obj) {
222        return obj == null ? 0 : obj.toNumber();
223    }
224
225    @SuppressWarnings("unused")
226    private static boolean toBoolean(final JSObject obj) {
227        return obj != null;
228    }
229
230    private static int getIndex(final Number n) {
231        final double value = n.doubleValue();
232        return JSType.isRepresentableAsInt(value) ? (int)value : -1;
233    }
234
235    @SuppressWarnings("unused")
236    private static Object callToApply(final MethodHandle mh, final JSObject obj, final Object thiz, final Object... args) {
237        assert args.length >= 2;
238        final Object   receiver  = args[0];
239        final Object[] arguments = new Object[args.length - 1];
240        System.arraycopy(args, 1, arguments, 0, arguments.length);
241        try {
242            return mh.invokeExact(obj, thiz, new Object[] { receiver, arguments });
243        } catch (final RuntimeException | Error e) {
244            throw e;
245        } catch (final Throwable e) {
246            throw new RuntimeException(e);
247        }
248    }
249
250    private static final MethodHandleFunctionality MH = MethodHandleFactory.getFunctionality();
251
252    // method handles of the current class
253    private static final MethodHandle IS_JSOBJECT_GUARD  = findOwnMH_S("isJSObject", boolean.class, Object.class);
254    private static final MethodHandle JSOBJECTLINKER_GET = findOwnMH_S("get", Object.class, MethodHandle.class, Object.class, Object.class);
255    private static final MethodHandle JSOBJECTLINKER_PUT = findOwnMH_S("put", Void.TYPE, Object.class, Object.class, Object.class);
256
257    // method handles of JSObject class
258    private static final MethodHandle JSOBJECT_GETMEMBER     = findJSObjectMH_V("getMember", Object.class, String.class);
259    private static final MethodHandle JSOBJECT_SETMEMBER     = findJSObjectMH_V("setMember", Void.TYPE, String.class, Object.class);
260    private static final MethodHandle JSOBJECT_CALL          = findJSObjectMH_V("call", Object.class, Object.class, Object[].class);
261    private static final MethodHandle JSOBJECT_CALL_TO_APPLY = findOwnMH_S("callToApply", Object.class, MethodHandle.class, JSObject.class, Object.class, Object[].class);
262    private static final MethodHandle JSOBJECT_NEW           = findJSObjectMH_V("newObject", Object.class, Object[].class);
263
264    private static final Map<Class<?>, MethodHandle> CONVERTERS = new HashMap<>();
265    static {
266        CONVERTERS.put(boolean.class, findOwnMH_S("toBoolean", boolean.class, JSObject.class));
267        CONVERTERS.put(int.class,     findOwnMH_S("toInt32", int.class, JSObject.class));
268        CONVERTERS.put(long.class,    findOwnMH_S("toLong", long.class, JSObject.class));
269        CONVERTERS.put(double.class,  findOwnMH_S("toNumber", double.class, JSObject.class));
270    }
271
272    private static MethodHandle findJSObjectMH_V(final String name, final Class<?> rtype, final Class<?>... types) {
273        return MH.findVirtual(MethodHandles.lookup(), JSObject.class, name, MH.type(rtype, types));
274    }
275
276    private static MethodHandle findOwnMH_S(final String name, final Class<?> rtype, final Class<?>... types) {
277        return MH.findStatic(MethodHandles.lookup(), JSObjectLinker.class, name, MH.type(rtype, types));
278    }
279}
280