SetMethodCreator.java revision 1649:50be58e74a21
1291011Sadrian/*
2291011Sadrian * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
3291011Sadrian * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4291011Sadrian *
5291011Sadrian * This code is free software; you can redistribute it and/or modify it
6291011Sadrian * under the terms of the GNU General Public License version 2 only, as
7291011Sadrian * published by the Free Software Foundation.  Oracle designates this
8291011Sadrian * particular file as subject to the "Classpath" exception as provided
9291011Sadrian * by Oracle in the LICENSE file that accompanied this code.
10291011Sadrian *
11291011Sadrian * This code is distributed in the hope that it will be useful, but WITHOUT
12291011Sadrian * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13291011Sadrian * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14291011Sadrian * version 2 for more details (a copy is included in the LICENSE file that
15291011Sadrian * accompanied this code).
16291011Sadrian *
17291011Sadrian * You should have received a copy of the GNU General Public License version
18291011Sadrian * 2 along with this work; if not, write to the Free Software Foundation,
19291011Sadrian * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20291011Sadrian *
21291011Sadrian * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22291011Sadrian * or visit www.oracle.com if you need additional information or have any
23291011Sadrian * questions.
24291011Sadrian */
25291011Sadrian
26291011Sadrianpackage jdk.nashorn.internal.runtime;
27291011Sadrian
28291011Sadrianimport static jdk.nashorn.internal.lookup.Lookup.MH;
29291011Sadrianimport static jdk.nashorn.internal.runtime.ECMAErrors.referenceError;
30291011Sadrianimport static jdk.nashorn.internal.runtime.JSType.getAccessorTypeIndex;
31291011Sadrian
32291011Sadrianimport java.lang.invoke.MethodHandle;
33291011Sadrianimport java.lang.invoke.SwitchPoint;
34291011Sadrianimport jdk.dynalink.CallSiteDescriptor;
35291011Sadrianimport jdk.dynalink.linker.GuardedInvocation;
36291011Sadrianimport jdk.dynalink.linker.LinkRequest;
37291011Sadrianimport jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
38291011Sadrianimport jdk.nashorn.internal.runtime.linker.NashornGuards;
39291011Sadrian
40291011Sadrian/**
41291011Sadrian * Instances of this class are quite ephemeral; they only exist for the duration of an invocation of
42291011Sadrian * {@link ScriptObject#findSetMethod(CallSiteDescriptor, jdk.dynalink.linker.LinkRequest)} and
43291011Sadrian * serve as the actual encapsulation of the algorithm for creating an appropriate property setter method.
44291011Sadrian */
45291011Sadrianfinal class SetMethodCreator {
46291011Sadrian    // See constructor parameters for description of fields
47291011Sadrian    private final ScriptObject       sobj;
48291011Sadrian    private final PropertyMap        map;
49291011Sadrian    private final FindProperty       find;
50291011Sadrian    private final CallSiteDescriptor desc;
51291011Sadrian    private final Class<?>           type;
52291011Sadrian    private final LinkRequest        request;
53291011Sadrian
54291011Sadrian    /**
55291011Sadrian     * Creates a new property setter method creator.
56291011Sadrian     * @param sobj the object for which we're creating the property setter
57291011Sadrian     * @param find a result of a {@link ScriptObject#findProperty(Object, boolean)} on the object for the property we
58291011Sadrian     * want to create a setter for. Can be null if the property does not yet exist on the object.
59291011Sadrian     * @param desc the descriptor of the call site that triggered the property setter lookup
60291011Sadrian     * @param request the link request
61291011Sadrian     */
62291011Sadrian    SetMethodCreator(final ScriptObject sobj, final FindProperty find, final CallSiteDescriptor desc, final LinkRequest request) {
63291011Sadrian        this.sobj    = sobj;
64291011Sadrian        this.map     = sobj.getMap();
65291011Sadrian        this.find    = find;
66291011Sadrian        this.desc    = desc;
67291011Sadrian        this.type    = desc.getMethodType().parameterType(1);
68291011Sadrian        this.request = request;
69291011Sadrian    }
70291011Sadrian
71291011Sadrian    private String getName() {
72291011Sadrian        return NashornCallSiteDescriptor.getOperand(desc);
73291011Sadrian    }
74291011Sadrian
75291011Sadrian    private PropertyMap getMap() {
76291011Sadrian        return map;
77291011Sadrian    }
78291011Sadrian
79291011Sadrian    /**
80291011Sadrian     * Creates the actual guarded invocation that represents the dynamic setter method for the property.
81291011Sadrian     * @return the actual guarded invocation that represents the dynamic setter method for the property.
82291011Sadrian     */
83291011Sadrian    GuardedInvocation createGuardedInvocation(final SwitchPoint builtinSwitchPoint) {
84291011Sadrian        return createSetMethod(builtinSwitchPoint).createGuardedInvocation();
85291011Sadrian    }
86291011Sadrian
87291011Sadrian    /**
88291011Sadrian     * This class encapsulates the results of looking up a setter method; it's basically a triple of a method handle,
89291011Sadrian     * a Property object, and flags for invocation.
90291011Sadrian     *
91291011Sadrian     */
92291011Sadrian    private class SetMethod {
93291011Sadrian        private final MethodHandle methodHandle;
94291011Sadrian        private final Property property;
95291011Sadrian
96291011Sadrian        /**
97291011Sadrian         * Creates a new lookup result.
98291011Sadrian         * @param methodHandle the actual method handle
99291011Sadrian         * @param property the property object. Can be null in case we're creating a new property in the global object.
100291011Sadrian         */
101291011Sadrian        SetMethod(final MethodHandle methodHandle, final Property property) {
102291011Sadrian            assert methodHandle != null;
103291438Sadrian            this.methodHandle = methodHandle;
104291011Sadrian            this.property     = property;
105291011Sadrian        }
106291011Sadrian
107291011Sadrian        /**
108291011Sadrian         * Composes from its components an actual guarded invocation that represents the dynamic setter method for the property.
109291011Sadrian         * @return the composed guarded invocation that represents the dynamic setter method for the property.
110291011Sadrian         */
111291011Sadrian        GuardedInvocation createGuardedInvocation() {
112291011Sadrian            // getGuard() and getException() either both return null, or neither does. The reason for that is that now
113291011Sadrian            // getGuard returns a map guard that casts its argument to ScriptObject, and if that fails, we need to
114291011Sadrian            // relink on ClassCastException.
115291011Sadrian            final boolean explicitInstanceOfCheck = NashornGuards.explicitInstanceOfCheck(desc, request);
116291011Sadrian            return new GuardedInvocation(methodHandle, NashornGuards.getGuard(sobj, property, desc, explicitInstanceOfCheck),
117291011Sadrian                    (SwitchPoint)null, explicitInstanceOfCheck ? null : ClassCastException.class);
118291011Sadrian        }
119291011Sadrian    }
120291011Sadrian
121291011Sadrian    private SetMethod createSetMethod(final SwitchPoint builtinSwitchPoint) {
122291011Sadrian        if (find != null) {
123291011Sadrian            return createExistingPropertySetter();
124291011Sadrian        }
125291011Sadrian
126291011Sadrian        checkStrictCreateNewVariable();
127291011Sadrian
128291011Sadrian        if (sobj.isScope()) {
129291011Sadrian            return createGlobalPropertySetter();
130291011Sadrian        }
131291011Sadrian
132291011Sadrian        return createNewPropertySetter(builtinSwitchPoint);
133291011Sadrian    }
134291011Sadrian
135291011Sadrian    private void checkStrictCreateNewVariable() {
136291011Sadrian        // In strict mode, assignment can not create a new variable.
137291011Sadrian        // See also ECMA Annex C item 4. ReferenceError is thrown.
138291011Sadrian        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) && property.needsDeclaration()) {
149            // This is a LET or CONST being declared. The property is already there but flagged as needing declaration.
150            // We create a new PropertyMap with the flag removed. The map is installed with a fast compare-and-set
151            // method if the pre-callsite map is stable (which should be the case for function scopes except for
152            // non-strict functions containing eval() with var). Otherwise we have to use a slow setter that creates
153            // a new PropertyMap on the fly.
154            final PropertyMap oldMap = getMap();
155            final Property newProperty = property.removeFlags(Property.NEEDS_DECLARATION);
156            final PropertyMap newMap = oldMap.replaceProperty(property, newProperty);
157            final MethodHandle fastSetter = find.replaceProperty(newProperty).getSetter(type, isStrict, request);
158            final MethodHandle slowSetter = MH.insertArguments(ScriptObject.DECLARE_AND_SET, 1, getName()).asType(fastSetter.type());
159
160            // cas map used as guard, if true that means we can do the set fast
161            MethodHandle casMap = MH.insertArguments(ScriptObject.CAS_MAP, 1, oldMap, newMap);
162            casMap = MH.dropArguments(casMap, 1, type);
163            casMap = MH.asType(casMap, casMap.type().changeParameterType(0, Object.class));
164            methodHandle = MH.guardWithTest(casMap, fastSetter, slowSetter);
165        } else {
166            methodHandle = find.getSetter(type, isStrict, request);
167        }
168
169        assert methodHandle != null;
170        assert property     != null;
171
172        final MethodHandle boundHandle;
173        if (!property.isAccessorProperty() && find.isInherited()) {
174            boundHandle = ScriptObject.addProtoFilter(methodHandle, find.getProtoChainLength());
175        } else {
176            boundHandle = methodHandle;
177        }
178        return new SetMethod(boundHandle, property);
179    }
180
181    private SetMethod createGlobalPropertySetter() {
182        final ScriptObject global = Context.getGlobal();
183        return new SetMethod(MH.filterArguments(global.addSpill(type, getName()), 0, ScriptObject.GLOBALFILTER), null);
184    }
185
186    private SetMethod createNewPropertySetter(final SwitchPoint builtinSwitchPoint) {
187        final SetMethod sm = map.getFreeFieldSlot() > -1 ? createNewFieldSetter(builtinSwitchPoint) : createNewSpillPropertySetter(builtinSwitchPoint);
188        map.propertyAdded(sm.property, true);
189        return sm;
190    }
191
192    private SetMethod createNewSetter(final Property property, final SwitchPoint builtinSwitchPoint) {
193        property.setBuiltinSwitchPoint(builtinSwitchPoint);
194
195        final PropertyMap oldMap   = getMap();
196        final PropertyMap newMap   = getNewMap(property);
197        final boolean     isStrict = NashornCallSiteDescriptor.isStrict(desc);
198        final String      name     = NashornCallSiteDescriptor.getOperand(desc);
199
200        //fast type specific setter
201        final MethodHandle fastSetter = property.getSetter(type, newMap); //0 sobj, 1 value, slot folded for spill property already
202
203        //slow setter, that calls ScriptObject.set with appropriate type and key name
204        MethodHandle slowSetter = ScriptObject.SET_SLOW[getAccessorTypeIndex(type)];
205        slowSetter = MH.insertArguments(slowSetter, 3, NashornCallSiteDescriptor.getFlags(desc));
206        slowSetter = MH.insertArguments(slowSetter, 1, name);
207        slowSetter = MH.asType(slowSetter, slowSetter.type().changeParameterType(0, Object.class));
208
209        assert slowSetter.type().equals(fastSetter.type()) : "slow=" + slowSetter + " != fast=" + fastSetter;
210
211        //cas map used as guard, if true that means we can do the set fast
212        MethodHandle casMap = MH.insertArguments(ScriptObject.CAS_MAP, 1, oldMap, newMap);
213        casMap = MH.dropArguments(casMap, 1, type);
214        casMap = MH.asType(casMap, casMap.type().changeParameterType(0, Object.class));
215        final MethodHandle casGuard = MH.guardWithTest(casMap, fastSetter, slowSetter);
216
217        //outermost level needs an extendable check. if object can be extended, guard is true and
218        //we can run the cas setter. The setter goes to "nop" VOID_RETURN if false or throws an
219        //exception if we are in strict mode and object is not extensible
220        MethodHandle extCheck = MH.insertArguments(ScriptObject.EXTENSION_CHECK, 1, isStrict, name);
221        extCheck = MH.asType(extCheck, extCheck.type().changeParameterType(0, Object.class));
222        extCheck = MH.dropArguments(extCheck, 1, type);
223
224        MethodHandle nop = JSType.VOID_RETURN.methodHandle();
225        nop = MH.dropArguments(nop, 0, Object.class, type);
226
227        return new SetMethod(MH.asType(MH.guardWithTest(extCheck, casGuard, nop), fastSetter.type()), property);
228    }
229
230    private SetMethod createNewFieldSetter(final SwitchPoint builtinSwitchPoint) {
231        return createNewSetter(new AccessorProperty(getName(), getFlags(sobj), sobj.getClass(), getMap().getFreeFieldSlot(), type), builtinSwitchPoint);
232    }
233
234    private SetMethod createNewSpillPropertySetter(final SwitchPoint builtinSwitchPoint) {
235        return createNewSetter(new SpillProperty(getName(), getFlags(sobj), getMap().getFreeSpillSlot(), type), builtinSwitchPoint);
236    }
237
238    private PropertyMap getNewMap(final Property property) {
239        return getMap().addProperty(property);
240    }
241
242    private static int getFlags(final ScriptObject scriptObject) {
243        return scriptObject.useDualFields() ? Property.DUAL_FIELDS : 0;
244    }
245}
246