SetMethodCreator.java revision 971:c93b6091b11e
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;
31
32import java.lang.invoke.MethodHandle;
33import java.lang.invoke.SwitchPoint;
34import jdk.internal.dynalink.CallSiteDescriptor;
35import jdk.internal.dynalink.linker.GuardedInvocation;
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 boolean            explicitInstanceOfCheck;
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     */
60    SetMethodCreator(final ScriptObject sobj, final FindProperty find, final CallSiteDescriptor desc, final boolean explicitInstanceOfCheck) {
61        this.sobj = sobj;
62        this.map  = sobj.getMap();
63        this.find = find;
64        this.desc = desc;
65        this.type = desc.getMethodType().parameterType(1);
66        this.explicitInstanceOfCheck = explicitInstanceOfCheck;
67
68    }
69
70    private String getName() {
71        return desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
72    }
73
74    private PropertyMap getMap() {
75        return map;
76    }
77
78    /**
79     * Creates the actual guarded invocation that represents the dynamic setter method for the property.
80     * @return the actual guarded invocation that represents the dynamic setter method for the property.
81     */
82    GuardedInvocation createGuardedInvocation() {
83        return createSetMethod().createGuardedInvocation();
84    }
85
86    /**
87     * This class encapsulates the results of looking up a setter method; it's basically a triple of a method handle,
88     * a Property object, and flags for invocation.
89     *
90     */
91    private class SetMethod {
92        private final MethodHandle methodHandle;
93        private final Property property;
94
95        /**
96         * Creates a new lookup result.
97         * @param methodHandle the actual method handle
98         * @param property the property object. Can be null in case we're creating a new property in the global object.
99         */
100        SetMethod(final MethodHandle methodHandle, final Property property) {
101            assert methodHandle != null;
102            this.methodHandle = methodHandle;
103            this.property     = property;
104        }
105
106        /**
107         * Composes from its components an actual guarded invocation that represents the dynamic setter method for the property.
108         * @return the composed guarded invocation that represents the dynamic setter method for the property.
109         */
110        GuardedInvocation createGuardedInvocation() {
111            // getGuard() and getException() either both return null, or neither does. The reason for that is that now
112            // getGuard returns a map guard that casts its argument to ScriptObject, and if that fails, we need to
113            // relink on ClassCastException.
114            return new GuardedInvocation(methodHandle, NashornGuards.getGuard(sobj, property, desc, explicitInstanceOfCheck),
115                    (SwitchPoint)null, explicitInstanceOfCheck ? null : ClassCastException.class);
116        }
117    }
118
119    private SetMethod createSetMethod() {
120        if (find != null) {
121            return createExistingPropertySetter();
122        }
123
124        checkStrictCreateNewVariable();
125
126        if (sobj.isScope()) {
127            return createGlobalPropertySetter();
128        }
129
130        return createNewPropertySetter();
131    }
132
133    private void checkStrictCreateNewVariable() {
134        // In strict mode, assignment can not create a new variable.
135        // See also ECMA Annex C item 4. ReferenceError is thrown.
136        if (NashornCallSiteDescriptor.isScope(desc) && NashornCallSiteDescriptor.isStrict(desc)) {
137            throw referenceError("not.defined", getName());
138        }
139    }
140
141    private SetMethod createExistingPropertySetter() {
142        final Property property = find.getProperty();
143        final MethodHandle methodHandle = find.getSetter(type, NashornCallSiteDescriptor.isStrict(desc));
144
145        assert methodHandle != null;
146        assert property     != null;
147
148        final MethodHandle boundHandle;
149        if (!property.hasSetterFunction(find.getOwner()) && find.isInherited()) {
150            boundHandle = ScriptObject.addProtoFilter(methodHandle, find.getProtoChainLength());
151        } else {
152            boundHandle = methodHandle;
153        }
154        return new SetMethod(boundHandle, property);
155    }
156
157    private SetMethod createGlobalPropertySetter() {
158        final ScriptObject global = Context.getGlobal();
159        return new SetMethod(MH.filterArguments(global.addSpill(type, getName()), 0, ScriptObject.GLOBALFILTER), null);
160    }
161
162    private SetMethod createNewPropertySetter() {
163        final SetMethod sm = map.getFreeFieldSlot() > -1 ? createNewFieldSetter() : createNewSpillPropertySetter();
164        final PropertyListeners listeners = map.getListeners();
165        if (listeners != null) {
166            listeners.propertyAdded(sm.property);
167        }
168        return sm;
169    }
170
171    private SetMethod createNewSetter(final Property property) {
172        final PropertyMap oldMap   = getMap();
173        final PropertyMap newMap   = getNewMap(property);
174        final boolean     isStrict = NashornCallSiteDescriptor.isStrict(desc);
175        final String      name     = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
176
177        //fast type specific setter
178        final MethodHandle fastSetter = property.getSetter(type, newMap); //0 sobj, 1 value, slot folded for spill property already
179
180        //slow setter, that calls ScriptObject.set with appropraite type and key name
181        MethodHandle slowSetter = ScriptObject.SET_SLOW[getAccessorTypeIndex(type)];
182        slowSetter = MH.insertArguments(slowSetter, 3, NashornCallSiteDescriptor.isStrict(desc));
183        slowSetter = MH.insertArguments(slowSetter, 1, name);
184        slowSetter = MH.asType(slowSetter, slowSetter.type().changeParameterType(0, Object.class));
185
186        assert slowSetter.type().equals(fastSetter.type()) : "slow=" + slowSetter + " != fast=" + fastSetter;
187
188        //cas map used as guard, if true that means we can do the set fast
189        MethodHandle casMap = MH.insertArguments(ScriptObject.CAS_MAP, 1, oldMap, newMap);
190        casMap = MH.dropArguments(casMap, 1, type);
191        casMap = MH.asType(casMap, casMap.type().changeParameterType(0, Object.class));
192        final MethodHandle casGuard = MH.guardWithTest(casMap, fastSetter, slowSetter);
193
194        //outermost level needs an extendable check. if object can be extended, guard is true and
195        //we can run the cas setter. The setter goes to "nop" VOID_RETURN if false or throws an
196        //exception if we are in strict mode and object is not extensible
197        MethodHandle extCheck = MH.insertArguments(ScriptObject.EXTENSION_CHECK, 1, isStrict, name);
198        extCheck = MH.asType(extCheck, extCheck.type().changeParameterType(0, Object.class));
199        extCheck = MH.dropArguments(extCheck, 1, type);
200
201        MethodHandle nop = JSType.VOID_RETURN.methodHandle();
202        nop = MH.dropArguments(nop, 0, Object.class, type);
203
204        return new SetMethod(MH.asType(MH.guardWithTest(extCheck, casGuard, nop), fastSetter.type()), property);
205    }
206
207    private SetMethod createNewFieldSetter() {
208        return createNewSetter(new AccessorProperty(getName(), 0, sobj.getClass(), getMap().getFreeFieldSlot(), type));
209    }
210
211    private SetMethod createNewSpillPropertySetter() {
212        return createNewSetter(new SpillProperty(getName(), 0, getMap().getFreeSpillSlot(), type));
213    }
214
215    private PropertyMap getNewMap(final Property property) {
216        return getMap().addProperty(property);
217    }
218}
219