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