1/*
2 * Copyright (c) 2016, 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 java.lang.invoke.MethodHandle;
29
30import jdk.nashorn.internal.objects.annotations.Attribute;
31import jdk.nashorn.internal.objects.annotations.Constructor;
32import jdk.nashorn.internal.objects.annotations.Function;
33import jdk.nashorn.internal.objects.annotations.Getter;
34import jdk.nashorn.internal.objects.annotations.ScriptClass;
35import jdk.nashorn.internal.objects.annotations.Where;
36import jdk.nashorn.internal.runtime.ConsString;
37import jdk.nashorn.internal.runtime.JSType;
38import jdk.nashorn.internal.runtime.PropertyMap;
39import jdk.nashorn.internal.runtime.ScriptObject;
40import jdk.nashorn.internal.runtime.ScriptRuntime;
41import jdk.nashorn.internal.runtime.Undefined;
42import jdk.nashorn.internal.runtime.linker.Bootstrap;
43
44import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
45
46/**
47 * This implements the ECMA6 Map object.
48 */
49@ScriptClass("Map")
50public class NativeMap extends ScriptObject {
51
52    // our underlying map
53    private final LinkedMap map = new LinkedMap();
54
55    // key for the forEach invoker callback
56    private final static Object FOREACH_INVOKER_KEY = new Object();
57
58    // initialized by nasgen
59    private static PropertyMap $nasgenmap$;
60
61    private NativeMap(final ScriptObject proto, final PropertyMap map) {
62        super(proto, map);
63    }
64
65    /**
66     * ECMA6 23.1.1 The Map Constructor
67     *
68     * @param isNew is this called with the new operator?
69     * @param self self reference
70     * @param arg optional iterable argument
71     * @return  a new Map instance
72     */
73    @Constructor(arity = 0)
74    public static Object construct(final boolean isNew, final Object self, final Object arg) {
75        if (!isNew) {
76            throw typeError("constructor.requires.new", "Map");
77        }
78        final Global global = Global.instance();
79        final NativeMap map = new NativeMap(global.getMapPrototype(), $nasgenmap$);
80        populateMap(map.getJavaMap(), arg, global);
81        return map;
82    }
83
84    /**
85     * ECMA6 23.1.3.1 Map.prototype.clear ( )
86     *
87     * @param self the self reference
88     */
89    @Function(attributes = Attribute.NOT_ENUMERABLE)
90    public static void clear(final Object self) {
91        getNativeMap(self).map.clear();
92    }
93
94    /**
95     * ECMA6 23.1.3.3 Map.prototype.delete ( key )
96     *
97     * @param self the self reference
98     * @param key the key to delete
99     * @return true if the key was deleted
100     */
101    @Function(attributes = Attribute.NOT_ENUMERABLE)
102    public static boolean delete(final Object self, final Object key) {
103        return getNativeMap(self).map.delete(convertKey(key));
104    }
105
106    /**
107     * ECMA6 23.1.3.7 Map.prototype.has ( key )
108     *
109     * @param self the self reference
110     * @param key the key
111     * @return true if key is contained
112     */
113    @Function(attributes = Attribute.NOT_ENUMERABLE)
114    public static boolean has(final Object self, final Object key) {
115        return getNativeMap(self).map.has(convertKey(key));
116    }
117
118    /**
119     * ECMA6 23.1.3.9 Map.prototype.set ( key , value )
120     *
121     * @param self the self reference
122     * @param key the key
123     * @param value the value
124     * @return this Map object
125     */
126    @Function(attributes = Attribute.NOT_ENUMERABLE)
127    public static Object set(final Object self, final Object key, final Object value) {
128        getNativeMap(self).map.set(convertKey(key), value);
129        return self;
130    }
131
132    /**
133     * ECMA6 23.1.3.6 Map.prototype.get ( key )
134     *
135     * @param self the self reference
136     * @param key the key
137     * @return the associated value or undefined
138     */
139    @Function(attributes = Attribute.NOT_ENUMERABLE)
140    public static Object get(final Object self, final Object key) {
141        return getNativeMap(self).map.get(convertKey(key));
142    }
143
144    /**
145     * ECMA6 23.1.3.10 get Map.prototype.size
146     *
147     * @param self the self reference
148     * @return the size of the map
149     */
150    @Getter(attributes = Attribute.NOT_ENUMERABLE | Attribute.IS_ACCESSOR, where = Where.PROTOTYPE)
151    public static int size(final Object self) {
152        return getNativeMap(self).map.size();
153    }
154
155    /**
156     * ECMA6 23.1.3.4 Map.prototype.entries ( )
157     *
158     * @param self the self reference
159     * @return an iterator over the Map's entries
160     */
161    @Function(attributes = Attribute.NOT_ENUMERABLE)
162    public static Object entries(final Object self) {
163        return new MapIterator(getNativeMap(self), AbstractIterator.IterationKind.KEY_VALUE, Global.instance());
164    }
165
166    /**
167     * ECMA6 23.1.3.8 Map.prototype.keys ( )
168     *
169     * @param self the self reference
170     * @return an iterator over the Map's keys
171     */
172    @Function(attributes = Attribute.NOT_ENUMERABLE)
173    public static Object keys(final Object self) {
174        return new MapIterator(getNativeMap(self), AbstractIterator.IterationKind.KEY, Global.instance());
175    }
176
177    /**
178     * ECMA6 23.1.3.11 Map.prototype.values ( )
179     *
180     * @param self the self reference
181     * @return an iterator over the Map's values
182     */
183    @Function(attributes = Attribute.NOT_ENUMERABLE)
184    public static Object values(final Object self) {
185        return new MapIterator(getNativeMap(self), AbstractIterator.IterationKind.VALUE, Global.instance());
186    }
187
188    /**
189     * ECMA6 23.1.3.12 Map.prototype [ @@iterator ]( )
190     *
191     * @param self the self reference
192     * @return An iterator over the Map's entries
193     */
194    @Function(attributes = Attribute.NOT_ENUMERABLE, name = "@@iterator")
195    public static Object getIterator(final Object self) {
196        return new MapIterator(getNativeMap(self), AbstractIterator.IterationKind.KEY_VALUE, Global.instance());
197    }
198
199    /**
200     *
201     * @param self the self reference
202     * @param callbackFn the callback function
203     * @param thisArg optional this-object
204     */
205    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
206    public static void forEach(final Object self, final Object callbackFn, final Object thisArg) {
207        final NativeMap map = getNativeMap(self);
208        if (!Bootstrap.isCallable(callbackFn)) {
209            throw typeError("not.a.function", ScriptRuntime.safeToString(callbackFn));
210        }
211        final MethodHandle invoker = Global.instance().getDynamicInvoker(FOREACH_INVOKER_KEY,
212                () -> Bootstrap.createDynamicCallInvoker(Object.class, Object.class, Object.class, Object.class, Object.class, Object.class));
213
214        final LinkedMap.LinkedMapIterator iterator = map.getJavaMap().getIterator();
215        for (;;) {
216            final LinkedMap.Node node = iterator.next();
217            if (node == null) {
218                break;
219            }
220
221            try {
222                final Object result = invoker.invokeExact(callbackFn, thisArg, node.getValue(), node.getKey(), self);
223            } catch (final RuntimeException | Error e) {
224                throw e;
225            } catch (final Throwable t) {
226                throw new RuntimeException(t);
227            }
228        }
229    }
230
231    @Override
232    public String getClassName() {
233        return "Map";
234    }
235
236    static void populateMap(final LinkedMap map, final Object arg, final Global global) {
237        if (arg != null && arg != Undefined.getUndefined()) {
238            AbstractIterator.iterate(arg, global, value -> {
239                if (JSType.isPrimitive(value)) {
240                    throw typeError(global, "not.an.object", ScriptRuntime.safeToString(value));
241                }
242                if (value instanceof ScriptObject) {
243                    final ScriptObject sobj = (ScriptObject) value;
244                    map.set(convertKey(sobj.get(0)), sobj.get(1));
245                }
246            });
247        }
248    }
249
250    /**
251     * Returns a canonicalized key object by converting numbers to their narrowest representation and
252     * ConsStrings to strings. Conversion of Double to Integer also takes care of converting -0 to 0
253     * as required by step 6 of ECMA6 23.1.3.9.
254     *
255     * @param key a key
256     * @return the canonical key
257     */
258    static Object convertKey(final Object key) {
259        if (key instanceof ConsString) {
260            return key.toString();
261        }
262        if (key instanceof Double) {
263            final Double d = (Double) key;
264            if (JSType.isRepresentableAsInt(d.doubleValue())) {
265                return d.intValue();
266            }
267        }
268        return key;
269    }
270
271    /**
272     * Get the underlying Java map.
273     * @return the Java map
274     */
275    LinkedMap getJavaMap() {
276        return map;
277    }
278
279    private static NativeMap getNativeMap(final Object self) {
280        if (self instanceof NativeMap) {
281            return (NativeMap)self;
282        } else {
283            throw typeError("not.a.map", ScriptRuntime.safeToString(self));
284        }
285    }
286
287}
288