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.UnwarrantedOptimismException.isValid;
30
31import java.lang.invoke.MethodHandle;
32import jdk.dynalink.linker.LinkRequest;
33import jdk.nashorn.internal.codegen.ObjectClassGenerator;
34import jdk.nashorn.internal.objects.Global;
35
36/**
37 * This class represents the result from a find property search.
38 */
39public final class FindProperty {
40    /** Object where search began. */
41    private final ScriptObject self;
42
43    /** Object where search finish. */
44    private final ScriptObject prototype;
45
46    /** Found property. */
47    private final Property     property;
48
49    /**
50     * Constructor
51     *
52     * @param self      script object where search began
53     * @param prototype prototype where property was found, may be {@code self} if not inherited
54     * @param property  property that was search result
55     */
56    public FindProperty(final ScriptObject self, final ScriptObject prototype, final Property property) {
57        this.self      = self;
58        this.prototype = prototype;
59        this.property  = property;
60    }
61
62    /**
63     * Return a copy of this FindProperty with a different property.
64     *
65     * @param newProperty the new property
66     * @return the new FindProperty instance
67     */
68    public FindProperty replaceProperty(final Property newProperty) {
69        assert this.property.getKey().equals(newProperty.getKey());
70        assert this.property.getSlot() == newProperty.getSlot();
71        return new FindProperty(self, prototype, newProperty);
72    }
73
74    /**
75     * Ask for a getter that returns the given type. The type has nothing to do with the
76     * internal representation of the property. It may be an Object (boxing primitives) or
77     * a primitive (primitive fields with -Dnashorn.fields.dual=true)
78     * @see ObjectClassGenerator
79     *
80     * @param type type of getter, e.g. int.class if we want a function with {@code get()I} signature
81     * @param programPoint program point, or INVALID_PROGRAM_POINT if pessimistic
82     * @param request link request
83     *
84     * @return method handle for the getter
85     */
86    public MethodHandle getGetter(final Class<?> type, final int programPoint, final LinkRequest request) {
87        MethodHandle getter;
88        if (isValid(programPoint)) {
89            getter = property.getOptimisticGetter(type, programPoint);
90        } else {
91            getter = property.getGetter(type);
92        }
93        if (property instanceof UserAccessorProperty) {
94            getter = MH.insertArguments(getter, 1, UserAccessorProperty.getINVOKE_UA_GETTER(type, programPoint));
95            if (isValid(programPoint) && type.isPrimitive()) {
96                getter = MH.insertArguments(getter, 1, programPoint);
97            }
98            property.setType(type);
99            return insertAccessorsGetter((UserAccessorProperty) property, request, getter);
100        }
101        return getter;
102    }
103
104    /**
105     * Ask for a setter that sets the given type. The type has nothing to do with the
106     * internal representation of the property. It may be an Object (boxing primitives) or
107     * a primitive (primitive fields with -Dnashorn.fields.dual=true)
108     * @see ObjectClassGenerator
109     *
110     * @param type type of setter, e.g. int.class if we want a function with {@code set(I)V} signature
111     * @param strict are we in strict mode
112     * @param request link request
113     *
114     * @return method handle for the getter
115     */
116    public MethodHandle getSetter(final Class<?> type, final boolean strict, final LinkRequest request) {
117        MethodHandle setter = property.getSetter(type, getOwner().getMap());
118        if (property instanceof UserAccessorProperty) {
119            setter =  MH.insertArguments(setter, 1, UserAccessorProperty.getINVOKE_UA_SETTER(type), strict ? property.getKey() : null);
120            property.setType(type);
121            return insertAccessorsGetter((UserAccessorProperty) property, request, setter);
122        }
123
124        return setter;
125    }
126
127    // Fold an accessor getter into the method handle of a user accessor property.
128    private MethodHandle insertAccessorsGetter(final UserAccessorProperty uap, final LinkRequest request, final MethodHandle mh) {
129        MethodHandle superGetter = uap.getAccessorsGetter();
130        if (!isSelf()) {
131            superGetter = ScriptObject.addProtoFilter(superGetter, getProtoChainLength());
132        }
133        if (request != null && !(request.getReceiver() instanceof ScriptObject)) {
134            final MethodHandle wrapFilter = Global.getPrimitiveWrapFilter(request.getReceiver());
135            superGetter = MH.filterArguments(superGetter, 0, wrapFilter.asType(wrapFilter.type().changeReturnType(superGetter.type().parameterType(0))));
136        }
137        superGetter = MH.asType(superGetter, superGetter.type().changeParameterType(0, Object.class));
138
139        return MH.foldArguments(mh, superGetter);
140    }
141
142    /**
143     * Return the {@code ScriptObject} owning of the property:  this means the prototype.
144     * @return owner of property
145     */
146    public ScriptObject getOwner() {
147        return prototype;
148    }
149
150    /**
151     * Return the {@code ScriptObject} where the search started. This is usually the ScriptObject the
152     * operation was started on, except for properties found inside a 'with' statement, where it is the
153     * top-level 'with' expression object.
154     *
155     * @return the start object.
156     */
157    public ScriptObject getSelf() {
158        return self;
159    }
160
161    /**
162     * Return the appropriate receiver for a getter.
163     * @return appropriate receiver
164     */
165    public ScriptObject getGetterReceiver() {
166        return property != null && property.isAccessorProperty() ? self : prototype;
167    }
168
169    /**
170     * Return the appropriate receiver for a setter.
171     * @return appropriate receiver
172     */
173    public ScriptObject getSetterReceiver() {
174        return property != null && property.hasSetterFunction(prototype) ? self : prototype;
175    }
176
177    /**
178     * Return the property that was found
179     * @return property
180     */
181    public Property getProperty() {
182        return property;
183    }
184
185    /**
186     * Check if the property found was inherited from a prototype and it is an ordinary
187     * property (one that has no accessor function).
188     * @return true if the found property is an inherited ordinary property
189     */
190    public boolean isInheritedOrdinaryProperty() {
191        return !isSelf() && !getProperty().isAccessorProperty();
192    }
193
194    /**
195     * Check if the property found was NOT inherited, i.e. defined in the script
196     * object, rather than in the prototype
197     * @return true if not inherited
198     */
199    public boolean isSelf() {
200        return self == prototype;
201    }
202
203    /**
204     * Check if the property is in the scope
205     * @return true if on scope
206     */
207    public boolean isScope() {
208        return prototype.isScope();
209    }
210
211    /**
212     * Get the property value from self as object.
213     * @return the property value
214     */
215    public int getIntValue() {
216        return property.getIntValue(getGetterReceiver(), getOwner());
217    }
218    /**
219     * Get the property value from self as object.
220     * @return the property value
221     */
222    public double getDoubleValue() {
223        return property.getDoubleValue(getGetterReceiver(), getOwner());
224    }
225    /**
226     * Get the property value from self as object.
227     * @return the property value
228     */
229    public Object getObjectValue() {
230        return property.getObjectValue(getGetterReceiver(), getOwner());
231    }
232
233    /**
234     * Set the property value in self.
235     *
236     * @param value the new value
237     * @param strict strict flag
238     */
239    public void setValue(final int value, final boolean strict) {
240        property.setValue(getSetterReceiver(), getOwner(), value, strict);
241    }
242
243    /**
244     * Set the property value in self.
245     *
246     * @param value the new value
247     * @param strict strict flag
248     */
249    public void setValue(final double value, final boolean strict) {
250        property.setValue(getSetterReceiver(), getOwner(), value, strict);
251    }
252
253    /**
254     * Set the property value in self.
255     *
256     * @param value the new value
257     * @param strict strict flag
258     */
259    public void setValue(final Object value, final boolean strict) {
260        property.setValue(getSetterReceiver(), getOwner(), value, strict);
261    }
262
263    /**
264     * Get the number of objects in the prototype chain between the {@code self} and the
265     * {@code owner} objects.
266     * @return the prototype chain length
267     */
268    int getProtoChainLength() {
269        assert self != null;
270        int length = 0;
271        for (ScriptObject obj = self; obj != prototype; obj = obj.getProto()) {
272            assert !(obj instanceof WithObject);
273            ++length;
274        }
275        return length;
276    }
277
278    @Override
279    public String toString() {
280        return "[FindProperty: " + property.getKey() + ']';
281    }
282
283}
284