SetMethodCreator.java revision 1245:c55ce3738888
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;
27
28import static jdk.nashorn.internal.lookup.Lookup.MH;
29import static jdk.nashorn.internal.runtime.ECMAErrors.referenceError;
30import static jdk.nashorn.internal.runtime.JSType.getAccessorTypeIndex;
31import java.lang.invoke.MethodHandle;
32import java.lang.invoke.SwitchPoint;
33import jdk.internal.dynalink.CallSiteDescriptor;
34import jdk.internal.dynalink.linker.GuardedInvocation;
35import jdk.internal.dynalink.linker.LinkRequest;
36import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
37import jdk.nashorn.internal.runtime.linker.NashornGuards;
38
39/**
40 * Instances of this class are quite ephemeral; they only exist for the duration of an invocation of
41 * {@link ScriptObject#findSetMethod(CallSiteDescriptor, jdk.internal.dynalink.linker.LinkRequest)} and
42 * serve as the actual encapsulation of the algorithm for creating an appropriate property setter method.
43 */
44final class SetMethodCreator {
45    // See constructor parameters for description of fields
46    private final ScriptObject       sobj;
47    private final PropertyMap        map;
48    private final FindProperty       find;
49    private final CallSiteDescriptor desc;
50    private final Class<?>           type;
51    private final LinkRequest        request;
52
53    /**
54     * Creates a new property setter method creator.
55     * @param sobj the object for which we're creating the property setter
56     * @param find a result of a {@link ScriptObject#findProperty(String, boolean)} on the object for the property we
57     * want to create a setter for. Can be null if the property does not yet exist on the object.
58     * @param desc the descriptor of the call site that triggered the property setter lookup
59     * @param request the link request
60     */
61    SetMethodCreator(final ScriptObject sobj, final FindProperty find, final CallSiteDescriptor desc, final LinkRequest request) {
62        this.sobj    = sobj;
63        this.map     = sobj.getMap();
64        this.find    = find;
65        this.desc    = desc;
66        this.type    = desc.getMethodType().parameterType(1);
67        this.request = request;
68
69    }
70
71    private String getName() {
72        return desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
73    }
74
75    private PropertyMap getMap() {
76        return map;
77    }
78
79    /**
80     * Creates the actual guarded invocation that represents the dynamic setter method for the property.
81     * @return the actual guarded invocation that represents the dynamic setter method for the property.
82     */
83    GuardedInvocation createGuardedInvocation(final SwitchPoint builtinSwitchPoint) {
84        return createSetMethod(builtinSwitchPoint).createGuardedInvocation();
85    }
86
87    /**
88     * This class encapsulates the results of looking up a setter method; it's basically a triple of a method handle,
89     * a Property object, and flags for invocation.
90     *
91     */
92    private class SetMethod {
93        private final MethodHandle methodHandle;
94        private final Property property;
95
96        /**
97         * Creates a new lookup result.
98         * @param methodHandle the actual method handle
99         * @param property the property object. Can be null in case we're creating a new property in the global object.
100         */
101        SetMethod(final MethodHandle methodHandle, final Property property) {
102            assert methodHandle != null;
103            this.methodHandle = methodHandle;
104            this.property     = property;
105        }
106
107        /**
108         * Composes from its components an actual guarded invocation that represents the dynamic setter method for the property.
109         * @return the composed guarded invocation that represents the dynamic setter method for the property.
110         */
111        GuardedInvocation createGuardedInvocation() {
112            // getGuard() and getException() either both return null, or neither does. The reason for that is that now
113            // getGuard returns a map guard that casts its argument to ScriptObject, and if that fails, we need to
114            // relink on ClassCastException.
115            final boolean explicitInstanceOfCheck = NashornGuards.explicitInstanceOfCheck(desc, request);
116            return new GuardedInvocation(methodHandle, NashornGuards.getGuard(sobj, property, desc, explicitInstanceOfCheck),
117                    (SwitchPoint)null, explicitInstanceOfCheck ? null : ClassCastException.class);
118        }
119    }
120
121    private SetMethod createSetMethod(final SwitchPoint builtinSwitchPoint) {
122        if (find != null) {
123            return createExistingPropertySetter();
124        }
125
126        checkStrictCreateNewVariable();
127
128        if (sobj.isScope()) {
129            return createGlobalPropertySetter();
130        }
131
132        return createNewPropertySetter(builtinSwitchPoint);
133    }
134
135    private void checkStrictCreateNewVariable() {
136        // In strict mode, assignment can not create a new variable.
137        // See also ECMA Annex C item 4. ReferenceError is thrown.
138        if (NashornCallSiteDescriptor.isScope(desc) && NashornCallSiteDescriptor.isStrict(desc)) {
139            throw referenceError("not.defined", getName());
140        }
141    }
142
143    private SetMethod createExistingPropertySetter() {
144        final Property property = find.getProperty();
145        final boolean isStrict  = NashornCallSiteDescriptor.isStrict(desc);
146        final MethodHandle methodHandle;
147
148        if (NashornCallSiteDescriptor.isDeclaration(desc)) {
149            assert property.needsDeclaration();
150            // This is a LET or CONST being declared. The property is already there but flagged as needing declaration.
151            // We create a new PropertyMap with the flag removed. The map is installed with a fast compare-and-set
152            // method if the pre-callsite map is stable (which should be the case for function scopes except for
153            // non-strict functions containing eval() with var). Otherwise we have to use a slow setter that creates
154            // a new PropertyMap on the fly.
155            final PropertyMap oldMap = getMap();
156            final Property newProperty = property.removeFlags(Property.NEEDS_DECLARATION);
157            final PropertyMap newMap = oldMap.replaceProperty(property, newProperty);
158            final MethodHandle fastSetter = find.replaceProperty(newProperty).getSetter(type, isStrict, request);
159            final MethodHandle slowSetter = MH.insertArguments(ScriptObject.DECLARE_AND_SET, 1, getName()).asType(fastSetter.type());
160
161            // cas map used as guard, if true that means we can do the set fast
162            MethodHandle casMap = MH.insertArguments(ScriptObject.CAS_MAP, 1, oldMap, newMap);
163            casMap = MH.dropArguments(casMap, 1, type);
164            casMap = MH.asType(casMap, casMap.type().changeParameterType(0, Object.class));
165            methodHandle = MH.guardWithTest(casMap, fastSetter, slowSetter);
166        } else {
167            methodHandle = find.getSetter(type, isStrict, request);
168        }
169
170        assert methodHandle != null;
171        assert property     != null;
172
173        final MethodHandle boundHandle;
174        if (!(property instanceof UserAccessorProperty) && find.isInherited()) {
175            boundHandle = ScriptObject.addProtoFilter(methodHandle, find.getProtoChainLength());
176        } else {
177            boundHandle = methodHandle;
178        }
179        return new SetMethod(boundHandle, property);
180    }
181
182    private SetMethod createGlobalPropertySetter() {
183        final ScriptObject global = Context.getGlobal();
184        return new SetMethod(MH.filterArguments(global.addSpill(type, getName()), 0, ScriptObject.GLOBALFILTER), null);
185    }
186
187    private SetMethod createNewPropertySetter(final SwitchPoint builtinSwitchPoint) {
188        final SetMethod sm = map.getFreeFieldSlot() > -1 ? createNewFieldSetter(builtinSwitchPoint) : createNewSpillPropertySetter(builtinSwitchPoint);
189        final PropertyListeners listeners = map.getListeners();
190        if (listeners != null) {
191            listeners.propertyAdded(sm.property);
192        }
193        return sm;
194    }
195
196    private SetMethod createNewSetter(final Property property, final SwitchPoint builtinSwitchPoint) {
197        property.setBuiltinSwitchPoint(builtinSwitchPoint);
198
199        final PropertyMap oldMap   = getMap();
200        final PropertyMap newMap   = getNewMap(property);
201        final boolean     isStrict = NashornCallSiteDescriptor.isStrict(desc);
202        final String      name     = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
203
204        //fast type specific setter
205        final MethodHandle fastSetter = property.getSetter(type, newMap); //0 sobj, 1 value, slot folded for spill property already
206
207        //slow setter, that calls ScriptObject.set with appropraite type and key name
208        MethodHandle slowSetter = ScriptObject.SET_SLOW[getAccessorTypeIndex(type)];
209        slowSetter = MH.insertArguments(slowSetter, 3, NashornCallSiteDescriptor.getFlags(desc));
210        slowSetter = MH.insertArguments(slowSetter, 1, name);
211        slowSetter = MH.asType(slowSetter, slowSetter.type().changeParameterType(0, Object.class));
212
213        assert slowSetter.type().equals(fastSetter.type()) : "slow=" + slowSetter + " != fast=" + fastSetter;
214
215        //cas map used as guard, if true that means we can do the set fast
216        MethodHandle casMap = MH.insertArguments(ScriptObject.CAS_MAP, 1, oldMap, newMap);
217        casMap = MH.dropArguments(casMap, 1, type);
218        casMap = MH.asType(casMap, casMap.type().changeParameterType(0, Object.class));
219        final MethodHandle casGuard = MH.guardWithTest(casMap, fastSetter, slowSetter);
220
221        //outermost level needs an extendable check. if object can be extended, guard is true and
222        //we can run the cas setter. The setter goes to "nop" VOID_RETURN if false or throws an
223        //exception if we are in strict mode and object is not extensible
224        MethodHandle extCheck = MH.insertArguments(ScriptObject.EXTENSION_CHECK, 1, isStrict, name);
225        extCheck = MH.asType(extCheck, extCheck.type().changeParameterType(0, Object.class));
226        extCheck = MH.dropArguments(extCheck, 1, type);
227
228        MethodHandle nop = JSType.VOID_RETURN.methodHandle();
229        nop = MH.dropArguments(nop, 0, Object.class, type);
230
231        return new SetMethod(MH.asType(MH.guardWithTest(extCheck, casGuard, nop), fastSetter.type()), property);
232    }
233
234    private SetMethod createNewFieldSetter(final SwitchPoint builtinSwitchPoint) {
235        return createNewSetter(new AccessorProperty(getName(), getFlags(sobj), sobj.getClass(), getMap().getFreeFieldSlot(), type), builtinSwitchPoint);
236    }
237
238    private SetMethod createNewSpillPropertySetter(final SwitchPoint builtinSwitchPoint) {
239        return createNewSetter(new SpillProperty(getName(), getFlags(sobj), getMap().getFreeSpillSlot(), type), builtinSwitchPoint);
240    }
241
242    private PropertyMap getNewMap(final Property property) {
243        return getMap().addProperty(property);
244    }
245
246    private static int getFlags(final ScriptObject scriptObject) {
247        return scriptObject.useDualFields() ? Property.DUAL_FIELDS : 0;
248    }
249}
250