WithObject.java revision 1429:b4eb53200105
1129199Scognet/*
2129199Scognet * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
3129199Scognet * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4129199Scognet *
5129199Scognet * This code is free software; you can redistribute it and/or modify it
6129199Scognet * under the terms of the GNU General Public License version 2 only, as
7129199Scognet * published by the Free Software Foundation.  Oracle designates this
8129199Scognet * particular file as subject to the "Classpath" exception as provided
9129199Scognet * by Oracle in the LICENSE file that accompanied this code.
10129199Scognet *
11129199Scognet * This code is distributed in the hope that it will be useful, but WITHOUT
12129199Scognet * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13129199Scognet * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14129199Scognet * version 2 for more details (a copy is included in the LICENSE file that
15129199Scognet * accompanied this code).
16129199Scognet *
17129199Scognet * You should have received a copy of the GNU General Public License version
18129199Scognet * 2 along with this work; if not, write to the Free Software Foundation,
19129199Scognet * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20129199Scognet *
21129199Scognet * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22129199Scognet * or visit www.oracle.com if you need additional information or have any
23129199Scognet * questions.
24129199Scognet */
25129199Scognet
26129199Scognetpackage jdk.nashorn.internal.runtime;
27129199Scognet
28129199Scognetimport static jdk.nashorn.internal.lookup.Lookup.MH;
29129199Scognetimport static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
30129199Scognet
31129199Scognetimport java.lang.invoke.MethodHandle;
32129199Scognetimport java.lang.invoke.MethodHandles;
33129199Scognetimport java.lang.invoke.MethodType;
34129199Scognetimport java.lang.invoke.SwitchPoint;
35129199Scognetimport jdk.internal.dynalink.CallSiteDescriptor;
36129199Scognetimport jdk.internal.dynalink.linker.GuardedInvocation;
37129199Scognetimport jdk.internal.dynalink.linker.LinkRequest;
38129199Scognetimport jdk.internal.dynalink.support.CallSiteDescriptorFactory;
39129199Scognetimport jdk.nashorn.api.scripting.AbstractJSObject;
40129199Scognetimport jdk.nashorn.api.scripting.ScriptObjectMirror;
41129199Scognetimport jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
42129199Scognetimport jdk.nashorn.internal.runtime.linker.NashornGuards;
43129199Scognet
44129199Scognet/**
45129199Scognet * This class supports the handling of scope in a with body.
46129199Scognet *
47129199Scognet */
48129199Scognetpublic final class WithObject extends Scope {
49129199Scognet    private static final MethodHandle WITHEXPRESSIONGUARD    = findOwnMH("withExpressionGuard",  boolean.class, Object.class, PropertyMap.class, SwitchPoint[].class);
50129199Scognet    private static final MethodHandle WITHEXPRESSIONFILTER   = findOwnMH("withFilterExpression", Object.class, Object.class);
51129199Scognet    private static final MethodHandle WITHSCOPEFILTER        = findOwnMH("withFilterScope",      Object.class, Object.class);
52    private static final MethodHandle BIND_TO_EXPRESSION_OBJ = findOwnMH("bindToExpression",     Object.class, Object.class, Object.class);
53    private static final MethodHandle BIND_TO_EXPRESSION_FN  = findOwnMH("bindToExpression",     Object.class, ScriptFunction.class, Object.class);
54
55    /** With expression object. */
56    private final ScriptObject expression;
57
58    /**
59     * Constructor
60     *
61     * @param scope scope object
62     * @param expression with expression
63     */
64    WithObject(final ScriptObject scope, final ScriptObject expression) {
65        super(scope, null);
66        this.expression = expression;
67    }
68
69    /**
70     * Delete a property based on a key.
71     * @param key Any valid JavaScript value.
72     * @param strict strict mode execution.
73     * @return True if deleted.
74     */
75    @Override
76    public boolean delete(final Object key, final boolean strict) {
77        final ScriptObject self = expression;
78        final String propName = JSType.toString(key);
79
80        final FindProperty find = self.findProperty(propName, true);
81
82        if (find != null) {
83            return self.delete(propName, strict);
84        }
85
86        return false;
87    }
88
89
90    @Override
91    public GuardedInvocation lookup(final CallSiteDescriptor desc, final LinkRequest request) {
92        if (request.isCallSiteUnstable()) {
93            // Fall back to megamorphic invocation which performs a complete lookup each time without further relinking.
94            return super.lookup(desc, request);
95        }
96
97        // With scopes can never be observed outside of Nashorn code, so all call sites that can address it will of
98        // necessity have a Nashorn descriptor - it is safe to cast.
99        final NashornCallSiteDescriptor ndesc = (NashornCallSiteDescriptor)desc;
100        FindProperty find = null;
101        GuardedInvocation link = null;
102        ScriptObject self;
103
104        final boolean isNamedOperation;
105        final String name;
106        if (desc.getNameTokenCount() > 2) {
107            isNamedOperation = true;
108            name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
109        } else {
110            isNamedOperation = false;
111            name = null;
112        }
113
114        self = expression;
115        if (isNamedOperation) {
116             find = self.findProperty(name, true);
117        }
118
119        if (find != null) {
120            link = self.lookup(desc, request);
121            if (link != null) {
122                return fixExpressionCallSite(ndesc, link);
123            }
124        }
125
126        final ScriptObject scope = getProto();
127        if (isNamedOperation) {
128            find = scope.findProperty(name, true);
129        }
130
131        if (find != null) {
132            return fixScopeCallSite(scope.lookup(desc, request), name, find.getOwner());
133        }
134
135        // the property is not found - now check for
136        // __noSuchProperty__ and __noSuchMethod__ in expression
137        if (self != null) {
138            final String fallBack;
139
140            final String operator = CallSiteDescriptorFactory.tokenizeOperators(desc).get(0);
141
142            switch (operator) {
143            case "callMethod":
144                throw new AssertionError(); // Nashorn never emits callMethod
145            case "getMethod":
146                fallBack = NO_SUCH_METHOD_NAME;
147                break;
148            case "getProp":
149            case "getElem":
150                fallBack = NO_SUCH_PROPERTY_NAME;
151                break;
152            default:
153                fallBack = null;
154                break;
155            }
156
157            if (fallBack != null) {
158                find = self.findProperty(fallBack, true);
159                if (find != null) {
160                    switch (operator) {
161                    case "getMethod":
162                        link = self.noSuchMethod(desc, request);
163                        break;
164                    case "getProp":
165                    case "getElem":
166                        link = self.noSuchProperty(desc, request);
167                        break;
168                    default:
169                        break;
170                    }
171                }
172            }
173
174            if (link != null) {
175                return fixExpressionCallSite(ndesc, link);
176            }
177        }
178
179        // still not found, may be scope can handle with it's own
180        // __noSuchProperty__, __noSuchMethod__ etc.
181        link = scope.lookup(desc, request);
182
183        if (link != null) {
184            return fixScopeCallSite(link, name, null);
185        }
186
187        return null;
188    }
189
190    /**
191     * Overridden to try to find the property first in the expression object (and its prototypes), and only then in this
192     * object (and its prototypes).
193     *
194     * @param key  Property key.
195     * @param deep Whether the search should look up proto chain.
196     * @param start the object on which the lookup was originally initiated
197     *
198     * @return FindPropertyData or null if not found.
199     */
200    @Override
201    protected FindProperty findProperty(final String key, final boolean deep, final ScriptObject start) {
202        // We call findProperty on 'expression' with 'expression' itself as start parameter.
203        // This way in ScriptObject.setObject we can tell the property is from a 'with' expression
204        // (as opposed from another non-scope object in the proto chain such as Object.prototype).
205        final FindProperty exprProperty = expression.findProperty(key, true, expression);
206        if (exprProperty != null) {
207             return exprProperty;
208        }
209        return super.findProperty(key, deep, start);
210    }
211
212    @Override
213    protected Object invokeNoSuchProperty(final String name, final boolean isScope, final int programPoint) {
214        FindProperty find = expression.findProperty(NO_SUCH_PROPERTY_NAME, true);
215        if (find != null) {
216            final Object func = find.getObjectValue();
217            if (func instanceof ScriptFunction) {
218                final ScriptFunction sfunc = (ScriptFunction)func;
219                final Object self = isScope && sfunc.isStrict()? UNDEFINED : expression;
220                return ScriptRuntime.apply(sfunc, self, name);
221            }
222        }
223
224        return getProto().invokeNoSuchProperty(name, isScope, programPoint);
225    }
226
227    @Override
228    public void setSplitState(final int state) {
229        ((Scope) getNonWithParent()).setSplitState(state);
230    }
231
232    @Override
233    public int getSplitState() {
234        return ((Scope) getNonWithParent()).getSplitState();
235    }
236
237    @Override
238    public void addBoundProperties(final ScriptObject source, final Property[] properties) {
239        // Declared variables in nested eval go to first normal (non-with) parent scope.
240        getNonWithParent().addBoundProperties(source, properties);
241    }
242
243    /**
244     * Get first parent scope that is not an instance of WithObject.
245     */
246    private ScriptObject getNonWithParent() {
247        ScriptObject proto = getProto();
248
249        while (proto != null && proto instanceof WithObject) {
250            proto = proto.getProto();
251        }
252
253        return proto;
254    }
255
256    private static GuardedInvocation fixReceiverType(final GuardedInvocation link, final MethodHandle filter) {
257        // The receiver may be an Object or a ScriptObject.
258        final MethodType invType = link.getInvocation().type();
259        final MethodType newInvType = invType.changeParameterType(0, filter.type().returnType());
260        return link.asType(newInvType);
261    }
262
263    private static GuardedInvocation fixExpressionCallSite(final NashornCallSiteDescriptor desc, final GuardedInvocation link) {
264        // If it's not a getMethod, just add an expression filter that converts WithObject in "this" position to its
265        // expression.
266        if (!"getMethod".equals(desc.getFirstOperator())) {
267            return fixReceiverType(link, WITHEXPRESSIONFILTER).filterArguments(0, WITHEXPRESSIONFILTER);
268        }
269
270        final MethodHandle linkInvocation      = link.getInvocation();
271        final MethodType   linkType            = linkInvocation.type();
272        final boolean      linkReturnsFunction = ScriptFunction.class.isAssignableFrom(linkType.returnType());
273
274        return link.replaceMethods(
275                // Make sure getMethod will bind the script functions it receives to WithObject.expression
276                MH.foldArguments(
277                        linkReturnsFunction ?
278                                BIND_TO_EXPRESSION_FN :
279                                BIND_TO_EXPRESSION_OBJ,
280                        filterReceiver(
281                                linkInvocation.asType(
282                                        linkType.changeReturnType(
283                                                linkReturnsFunction ?
284                                                        ScriptFunction.class :
285                                                        Object.class).
286                                                            changeParameterType(
287                                                                    0,
288                                                                    Object.class)),
289                                        WITHEXPRESSIONFILTER)),
290                         filterGuardReceiver(link, WITHEXPRESSIONFILTER));
291     // No clever things for the guard -- it is still identically filtered.
292
293    }
294
295    private GuardedInvocation fixScopeCallSite(final GuardedInvocation link, final String name, final ScriptObject owner) {
296        final GuardedInvocation newLink             = fixReceiverType(link, WITHSCOPEFILTER);
297        final MethodHandle      expressionGuard     = expressionGuard(name, owner);
298        final MethodHandle      filterGuardReceiver = filterGuardReceiver(newLink, WITHSCOPEFILTER);
299        return link.replaceMethods(
300                filterReceiver(
301                        newLink.getInvocation(),
302                        WITHSCOPEFILTER),
303                NashornGuards.combineGuards(
304                        expressionGuard,
305                        filterGuardReceiver));
306    }
307
308    private static MethodHandle filterGuardReceiver(final GuardedInvocation link, final MethodHandle receiverFilter) {
309        final MethodHandle test = link.getGuard();
310        if (test == null) {
311            return null;
312        }
313
314        final Class<?> receiverType = test.type().parameterType(0);
315        final MethodHandle filter = MH.asType(receiverFilter,
316                receiverFilter.type().changeParameterType(0, receiverType).
317                changeReturnType(receiverType));
318
319        return filterReceiver(test, filter);
320    }
321
322    private static MethodHandle filterReceiver(final MethodHandle mh, final MethodHandle receiverFilter) {
323        //With expression filter == receiverFilter, i.e. receiver is cast to withobject and its expression returned
324        return MH.filterArguments(mh, 0, receiverFilter.asType(receiverFilter.type().changeReturnType(mh.type().parameterType(0))));
325    }
326
327    /**
328     * Drops the WithObject wrapper from the expression.
329     * @param receiver WithObject wrapper.
330     * @return The with expression.
331     */
332    public static Object withFilterExpression(final Object receiver) {
333        return ((WithObject)receiver).expression;
334    }
335
336    @SuppressWarnings("unused")
337    private static Object bindToExpression(final Object fn, final Object receiver) {
338        if (fn instanceof ScriptFunction) {
339            return bindToExpression((ScriptFunction) fn, receiver);
340        } else if (fn instanceof ScriptObjectMirror) {
341            final ScriptObjectMirror mirror = (ScriptObjectMirror)fn;
342            if (mirror.isFunction()) {
343                // We need to make sure correct 'this' is used for calls with Ident call
344                // expressions. We do so here using an AbstractJSObject instance.
345                return new AbstractJSObject() {
346                    @Override
347                    public Object call(final Object thiz, final Object... args) {
348                        return mirror.call(withFilterExpression(receiver), args);
349                    }
350                };
351            }
352        }
353
354        return fn;
355    }
356
357    private static Object bindToExpression(final ScriptFunction fn, final Object receiver) {
358        return fn.createBound(withFilterExpression(receiver), ScriptRuntime.EMPTY_ARRAY);
359    }
360
361    private MethodHandle expressionGuard(final String name, final ScriptObject owner) {
362        final PropertyMap map = expression.getMap();
363        final SwitchPoint[] sp = expression.getProtoSwitchPoints(name, owner);
364        return MH.insertArguments(WITHEXPRESSIONGUARD, 1, map, sp);
365    }
366
367    @SuppressWarnings("unused")
368    private static boolean withExpressionGuard(final Object receiver, final PropertyMap map, final SwitchPoint[] sp) {
369        return ((WithObject)receiver).expression.getMap() == map && !hasBeenInvalidated(sp);
370    }
371
372    private static boolean hasBeenInvalidated(final SwitchPoint[] switchPoints) {
373        if (switchPoints != null) {
374            for (final SwitchPoint switchPoint : switchPoints) {
375                if (switchPoint.hasBeenInvalidated()) {
376                    return true;
377                }
378            }
379        }
380        return false;
381    }
382
383    /**
384     * Drops the WithObject wrapper from the scope.
385     * @param receiver WithObject wrapper.
386     * @return The with scope.
387     */
388    public static Object withFilterScope(final Object receiver) {
389        return ((WithObject)receiver).getProto();
390    }
391
392    /**
393     * Get the with expression for this {@code WithObject}
394     * @return the with expression
395     */
396    public ScriptObject getExpression() {
397        return expression;
398    }
399
400    private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
401        return MH.findStatic(MethodHandles.lookup(), WithObject.class, name, MH.type(rtype, types));
402    }
403}
404