NativeArguments.java revision 1508:a661018d34b8
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.objects;
27
28import static jdk.nashorn.internal.lookup.Lookup.MH;
29import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
30import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
31
32import java.lang.invoke.MethodHandle;
33import java.lang.invoke.MethodHandles;
34import java.util.ArrayList;
35import java.util.Arrays;
36import java.util.BitSet;
37import jdk.nashorn.internal.runtime.AccessorProperty;
38import jdk.nashorn.internal.runtime.JSType;
39import jdk.nashorn.internal.runtime.Property;
40import jdk.nashorn.internal.runtime.PropertyDescriptor;
41import jdk.nashorn.internal.runtime.PropertyMap;
42import jdk.nashorn.internal.runtime.ScriptFunction;
43import jdk.nashorn.internal.runtime.ScriptObject;
44import jdk.nashorn.internal.runtime.ScriptRuntime;
45import jdk.nashorn.internal.runtime.arrays.ArrayData;
46import jdk.nashorn.internal.runtime.arrays.ArrayIndex;
47
48/**
49 * ECMA 10.6 Arguments Object.
50 *
51 * Arguments object used for non-strict mode functions. For strict mode, we use
52 * a different implementation (@see NativeStrictArguments). In non-strict mode,
53 * named argument access and index argument access (arguments[i]) are linked.
54 * Modifications reflect on each other access -- till arguments indexed element
55 * is deleted. After delete, there is no link between named access and indexed
56 * access for that deleted index alone.
57 */
58public final class NativeArguments extends ScriptObject {
59
60    private static final MethodHandle G$LENGTH = findOwnMH("G$length", Object.class, Object.class);
61    private static final MethodHandle S$LENGTH = findOwnMH("S$length", void.class, Object.class, Object.class);
62    private static final MethodHandle G$CALLEE = findOwnMH("G$callee", Object.class, Object.class);
63    private static final MethodHandle S$CALLEE = findOwnMH("S$callee", void.class, Object.class, Object.class);
64
65    private static final PropertyMap map$;
66
67    static {
68        final ArrayList<Property> properties = new ArrayList<>(2);
69        properties.add(AccessorProperty.create("length", Property.NOT_ENUMERABLE, G$LENGTH, S$LENGTH));
70        properties.add(AccessorProperty.create("callee", Property.NOT_ENUMERABLE, G$CALLEE, S$CALLEE));
71        map$ = PropertyMap.newMap(properties);
72    }
73
74    static PropertyMap getInitialMap() {
75        return map$;
76    }
77
78    private Object length;
79    private Object callee;
80    private final int numMapped;
81    private final int numParams;
82
83    // These are lazily initialized when delete is invoked on a mapped arg or an unmapped argument is set.
84    private ArrayData unmappedArgs;
85    private BitSet deleted;
86
87    NativeArguments(final Object[] arguments, final Object callee, final int numParams, final ScriptObject proto, final PropertyMap map) {
88        super(proto, map);
89        setIsArguments();
90        setArray(ArrayData.allocate(arguments));
91        this.length = arguments.length;
92        this.callee = callee;
93        this.numMapped = Math.min(numParams, arguments.length);
94        this.numParams = numParams;
95    }
96
97    @Override
98    public String getClassName() {
99        return "Arguments";
100    }
101
102    /**
103     * getArgument is used for named argument access.
104     */
105    @Override
106    public Object getArgument(final int key) {
107        assert key >= 0 && key < numParams : "invalid argument index";
108        return isMapped(key) ? getArray().getObject(key) : getUnmappedArg(key);
109    }
110
111    /**
112     * setArgument is used for named argument set.
113     */
114    @Override
115    public void setArgument(final int key, final Object value) {
116        assert key >= 0 && key < numParams : "invalid argument index";
117        if (isMapped(key)) {
118            setArray(getArray().set(key, value, false));
119        } else {
120            setUnmappedArg(key, value);
121        }
122    }
123
124    @Override
125    public boolean delete(final int key, final boolean strict) {
126        final int index = ArrayIndex.getArrayIndex(key);
127        return isMapped(index) ? deleteMapped(index, strict) : super.delete(key, strict);
128    }
129
130    @Override
131    public boolean delete(final long key, final boolean strict) {
132        final int index = ArrayIndex.getArrayIndex(key);
133        return isMapped(index) ? deleteMapped(index, strict) : super.delete(key, strict);
134    }
135
136    @Override
137    public boolean delete(final double key, final boolean strict) {
138        final int index = ArrayIndex.getArrayIndex(key);
139        return isMapped(index) ? deleteMapped(index, strict) : super.delete(key, strict);
140    }
141
142    @Override
143    public boolean delete(final Object key, final boolean strict) {
144        final Object primitiveKey = JSType.toPrimitive(key, String.class);
145        final int index = ArrayIndex.getArrayIndex(primitiveKey);
146        return isMapped(index) ? deleteMapped(index, strict) : super.delete(primitiveKey, strict);
147    }
148
149    /**
150     * ECMA 15.4.5.1 [[DefineOwnProperty]] ( P, Desc, Throw ) as specialized in
151     * ECMA 10.6 for Arguments object.
152     */
153    @Override
154    public boolean defineOwnProperty(final Object key, final Object propertyDesc, final boolean reject) {
155        final int index = ArrayIndex.getArrayIndex(key);
156        if (index >= 0) {
157            final boolean isMapped = isMapped(index);
158            final Object oldValue = isMapped ? getArray().getObject(index) : null;
159
160            if (!super.defineOwnProperty(key, propertyDesc, false)) {
161                if (reject) {
162                    throw typeError("cant.redefine.property",  key.toString(), ScriptRuntime.safeToString(this));
163                }
164                return false;
165            }
166
167            if (isMapped) {
168                // When mapped argument is redefined, if new descriptor is accessor property
169                // or data-non-writable property, we have to "unmap" (unlink).
170                final PropertyDescriptor desc = toPropertyDescriptor(Global.instance(), propertyDesc);
171                if (desc.type() == PropertyDescriptor.ACCESSOR) {
172                    setDeleted(index, oldValue);
173                } else if (desc.has(PropertyDescriptor.WRITABLE) && !desc.isWritable()) {
174                    // delete and set value from new descriptor if it has one, otherwise use old value
175                    setDeleted(index, desc.has(PropertyDescriptor.VALUE) ? desc.getValue() : oldValue);
176                } else if (desc.has(PropertyDescriptor.VALUE)) {
177                    setArray(getArray().set(index, desc.getValue(), false));
178                }
179            }
180
181            return true;
182        }
183
184        return super.defineOwnProperty(key, propertyDesc, reject);
185    }
186
187    // Internals below this point
188
189    // We track deletions using a bit set (delete arguments[index])
190    private boolean isDeleted(final int index) {
191        return deleted != null && deleted.get(index);
192    }
193
194    private void setDeleted(final int index, final Object unmappedValue) {
195        if (deleted == null) {
196            deleted = new BitSet(numMapped);
197        }
198        deleted.set(index, true);
199        setUnmappedArg(index, unmappedValue);
200    }
201
202    private boolean deleteMapped(final int index, final boolean strict) {
203        final Object value = getArray().getObject(index);
204        final boolean success = super.delete(index, strict);
205        if (success) {
206            setDeleted(index, value);
207        }
208        return success;
209    }
210
211    private Object getUnmappedArg(final int key) {
212        assert key >= 0 && key < numParams;
213        return unmappedArgs == null ? UNDEFINED : unmappedArgs.getObject(key);
214    }
215
216    private void setUnmappedArg(final int key, final Object value) {
217        assert key >= 0 && key < numParams;
218        if (unmappedArgs == null) {
219            /*
220             * Declared number of parameters may be more or less than the actual passed
221             * runtime arguments count. We need to truncate or extend with undefined values.
222             *
223             * Example:
224             *
225             * // less declared params
226             * (function (x) { print(arguments); })(20, 44);
227             *
228             * // more declared params
229             * (function (x, y) { print(arguments); })(3);
230             */
231            final Object[] newValues = new Object[numParams];
232            System.arraycopy(getArray().asObjectArray(), 0, newValues, 0, numMapped);
233            if (numMapped < numParams) {
234                Arrays.fill(newValues, numMapped, numParams, UNDEFINED);
235            }
236            this.unmappedArgs = ArrayData.allocate(newValues);
237        }
238        // Set value of argument
239        unmappedArgs = unmappedArgs.set(key, value, false);
240    }
241
242    /**
243     * Are arguments[index] and corresponding named parameter linked?
244     *
245     * In non-strict mode, arguments[index] and corresponding named param are "linked" or "mapped"
246     * if the argument is provided by the caller. Modifications are tacked b/w each other - until
247     * (delete arguments[index]) is used. Once deleted, the corresponding arg is no longer 'mapped'.
248     * Please note that delete can happen only through the arguments array - named param can not
249     * be deleted. (delete is one-way).
250     */
251    private boolean isMapped(final int index) {
252        // in mapped named args and not marked as "deleted"
253        return index >= 0 && index < numMapped && !isDeleted(index);
254    }
255
256    /**
257     * Factory to create correct Arguments object based on strict mode.
258     *
259     * @param arguments the actual arguments array passed
260     * @param callee the callee function that uses arguments object
261     * @param numParams the number of declared (named) function parameters
262     * @return Arguments Object
263     */
264    public static ScriptObject allocate(final Object[] arguments, final ScriptFunction callee, final int numParams) {
265        // Strict functions won't always have a callee for arguments, and will pass null instead.
266        final boolean isStrict = callee == null || callee.isStrict();
267        final Global global = Global.instance();
268        final ScriptObject proto = global.getObjectPrototype();
269        if (isStrict) {
270            return new NativeStrictArguments(arguments, numParams, proto, NativeStrictArguments.getInitialMap());
271        }
272        return new NativeArguments(arguments, callee, numParams, proto, NativeArguments.getInitialMap());
273    }
274
275    /**
276     * Length getter
277     * @param self self reference
278     * @return length property value
279     */
280    public static Object G$length(final Object self) {
281        if (self instanceof NativeArguments) {
282            return ((NativeArguments)self).getArgumentsLength();
283        }
284
285        return 0;
286    }
287
288    /**
289     * Length setter
290     * @param self self reference
291     * @param value value for length property
292     */
293    public static void S$length(final Object self, final Object value) {
294        if (self instanceof NativeArguments) {
295            ((NativeArguments)self).setArgumentsLength(value);
296        }
297    }
298
299    /**
300     * Callee getter
301     * @param self self reference
302     * @return value for callee property
303     */
304    public static Object G$callee(final Object self) {
305        if (self instanceof NativeArguments) {
306            return ((NativeArguments)self).getCallee();
307        }
308        return UNDEFINED;
309    }
310
311    /**
312     * Callee setter
313     * @param self self reference
314     * @param value value for callee property
315     */
316    public static void S$callee(final Object self, final Object value) {
317        if (self instanceof NativeArguments) {
318            ((NativeArguments)self).setCallee(value);
319        }
320    }
321
322    @Override
323    public Object getLength() {
324        return length;
325    }
326
327    private Object getArgumentsLength() {
328        return length;
329    }
330
331    private void setArgumentsLength(final Object length) {
332        this.length = length;
333    }
334
335    private Object getCallee() {
336        return callee;
337    }
338
339    private void setCallee(final Object callee) {
340        this.callee = callee;
341    }
342
343    private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
344        return MH.findStatic(MethodHandles.lookup(), NativeArguments.class, name, MH.type(rtype, types));
345    }
346}
347