aboutsummaryrefslogtreecommitdiff
path: root/src/jdk/nashorn/internal/runtime/arrays/ArrayData.java
blob: 897636ebe449daf0095f076067ffc06cb5c99b4e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
/*
 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package jdk.nashorn.internal.runtime.arrays;

import static jdk.nashorn.internal.codegen.CompilerConstants.staticCall;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.nio.ByteBuffer;
import jdk.internal.dynalink.CallSiteDescriptor;
import jdk.internal.dynalink.linker.GuardedInvocation;
import jdk.internal.dynalink.linker.LinkRequest;
import jdk.nashorn.internal.codegen.CompilerConstants;
import jdk.nashorn.internal.codegen.types.Type;
import jdk.nashorn.internal.objects.Global;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.PropertyDescriptor;
import jdk.nashorn.internal.runtime.UnwarrantedOptimismException;

/**
 * ArrayData - abstraction for wrapping array elements
 */
public abstract class ArrayData {
    /** Minimum chunk size for underlying arrays */
    protected static final int CHUNK_SIZE = 32;

    /** Mask for getting a chunk */
    protected static final int CHUNK_MASK = CHUNK_SIZE - 1;

    /**
     * Immutable empty array to get ScriptObjects started.
     */
    public static final ArrayData EMPTY_ARRAY = new NoTypeArrayData();

    /**
     * Length of the array data. Not necessarily length of the wrapped array.
     */
    private long length;

    /**
     * Method handle to throw an {@link UnwarrantedOptimismException} when getting an element
     * of the wrong type
     */
    protected static final CompilerConstants.Call THROW_UNWARRANTED = staticCall(MethodHandles.lookup(), ArrayData.class, "throwUnwarranted", void.class, ArrayData.class, int.class, int.class);

    /**
     * Constructor
     * @param length Virtual length of the array.
     */
    protected ArrayData(final long length) {
        this.length = length;
    }

    /**
     * Factory method for unspecified array - start as int
     * @return ArrayData
     */
    public static ArrayData initialArray() {
        return new IntArrayData();
    }

    /**
     * Unwarranted thrower
     *
     * @param data         array data
     * @param programPoint program point
     * @param index        array index
     */
    protected static void throwUnwarranted(final ArrayData data, final int programPoint, final int index) {
        throw new UnwarrantedOptimismException(data.getObject(index), programPoint);
    }

    private static int alignUp(final int size) {
        return size + CHUNK_SIZE - 1 & ~(CHUNK_SIZE - 1);
    }

    /**
     * Generic invalidation hook for script object to have call sites to this array indexing
     * relinked, e.g. when a native array is marked as non extensible
     */
    public void invalidateGetters() {
        //subclass responsibility
    }

    /**
     * Generic invalidation hook for script object to have call sites to this array indexing
     * relinked, e.g. when a native array is marked as non extensible
     */
    public void invalidateSetters() {
        //subclass responsibility
    }

    /**
     * Factory method for unspecified array with given length - start as int array data
     *
     * @param length the initial length
     * @return ArrayData
     */
    public static ArrayData allocate(final int length) {
        if (length == 0) {
            return new IntArrayData();
        } else if (length >= SparseArrayData.MAX_DENSE_LENGTH) {
            return new SparseArrayData(EMPTY_ARRAY, length);
        } else {
            return new DeletedRangeArrayFilter(new IntArrayData(length), 0, length - 1);
        }
    }

    /**
     * Factory method for unspecified given an array object
     *
     * @param  array the array
     * @return ArrayData wrapping this array
     */
    public static ArrayData allocate(final Object array) {
        final Class<?> clazz = array.getClass();

        if (clazz == int[].class) {
            return new IntArrayData((int[])array, ((int[])array).length);
        } else if (clazz == long[].class) {
            return new LongArrayData((long[])array, ((long[])array).length);
        } else if (clazz == double[].class) {
            return new NumberArrayData((double[])array, ((double[])array).length);
        } else {
            return new ObjectArrayData((Object[])array, ((Object[])array).length);
        }
    }

    /**
     * Allocate an ArrayData wrapping a given array
     *
     * @param array the array to use for initial elements
     * @return the ArrayData
     */
    public static ArrayData allocate(final int[] array) {
         return new IntArrayData(array, array.length);
    }

    /**
     * Allocate an ArrayData wrapping a given array
     *
     * @param array the array to use for initial elements
     * @return the ArrayData
     */
    public static ArrayData allocate(final long[] array) {
        return new LongArrayData(array, array.length);
    }

    /**
     * Allocate an ArrayData wrapping a given array
     *
     * @param array the array to use for initial elements
     * @return the ArrayData
     */
    public static ArrayData allocate(final double[] array) {
        return new NumberArrayData(array, array.length);
    }

    /**
     * Allocate an ArrayData wrapping a given array
     *
     * @param array the array to use for initial elements
     * @return the ArrayData
     */
    public static ArrayData allocate(final Object[] array) {
        return new ObjectArrayData(array, array.length);
    }

    /**
     * Allocate an ArrayData wrapping a given nio ByteBuffer
     *
     * @param buf the nio ByteBuffer to wrap
     * @return the ArrayData
     */
    public static ArrayData allocate(final ByteBuffer buf) {
        return new ByteBufferArrayData(buf);
    }

    /**
     * Apply a freeze filter to an ArrayData.
     *
     * @param underlying  the underlying ArrayData to wrap in the freeze filter
     * @return the frozen ArrayData
     */
    public static ArrayData freeze(final ArrayData underlying) {
        return new FrozenArrayFilter(underlying);
    }

    /**
     * Apply a seal filter to an ArrayData.
     *
     * @param underlying  the underlying ArrayData to wrap in the seal filter
     * @return the sealed ArrayData
     */
    public static ArrayData seal(final ArrayData underlying) {
        return new SealedArrayFilter(underlying);
    }

    /**
     * Return the length of the array data. This may differ from the actual
     * length of the array this wraps as length may be set or gotten as any
     * other JavaScript Property
     *
     * Even though a JavaScript array length may be a long, we only store
     * int parts for the optimized array access. For long lengths there
     * are special cases anyway.
     *
     * TODO: represent arrays with "long" lengths as a special ArrayData
     * that basically maps to the ScriptObject directly for better abstraction
     *
     * @return the length of the data
     */
    public final long length() {
        return length;
    }

    /**
     * Return a copy of the array that can be modified without affecting this instance.
     * It is safe to return themselves for immutable subclasses.
     *
     * @return a new array
     */
    public abstract ArrayData copy();

    /**
     * Return a copy of the array data as an Object array.
     *
     * @return an Object array
     */
    public abstract Object[] asObjectArray();

    /**
     * Return a copy of the array data as an array of the specified type.
     *
     * @param componentType  the type of elements in the array
     * @return and array of the given type
     */
    public Object asArrayOfType(final Class<?> componentType) {
        return JSType.convertArray(asObjectArray(), componentType);
    }

    /**
     * Set the length of the data array
     *
     * @param length the new length for the data array
     */
    public void setLength(final long length) {
        this.length = length;
    }

    /**
     * Shift the array data left
     *
     * TODO: explore start at an index and not at zero, to make these operations
     * even faster. Offset everything from the index. Costs memory but is probably
     * worth it
     *
     * @param by offset to shift
     */
    public abstract void shiftLeft(int by);

    /**
     * Shift the array right
     *
     * @param by offset to shift

     * @return New arraydata (or same)
     */
    public abstract ArrayData shiftRight(int by);

    /**
     * Ensure that the given index exists and won't fail subsequent
     *
     * @param safeIndex the index to ensure wont go out of bounds
     * @return new array data (or same)
     */
    public abstract ArrayData ensure(long safeIndex);

    /**
     * Shrink the array to a new length, may or may not retain the
     * inner array
     *
     * @param newLength new max length
     *
     * @return new array data (or same)
     */
    public abstract ArrayData shrink(long newLength);

    /**
     * Set an object value at a given index
     *
     * @param index the index
     * @param value the value
     * @param strict are we in strict mode
     * @return new array data (or same)
     */
    public abstract ArrayData set(int index, Object value, boolean strict);

    /**
     * Set an int value at a given index
     *
     * @param index the index
     * @param value the value
     * @param strict are we in strict mode
     * @return new array data (or same)
     */
    public abstract ArrayData set(int index, int value, boolean strict);

    /**
     * Set a long value at a given index
     *
     * @param index the index
     * @param value the value
     * @param strict are we in strict mode
     * @return new array data (or same)
     */
    public abstract ArrayData set(int index, long value, boolean strict);

    /**
     * Set an double value at a given index
     *
     * @param index the index
     * @param value the value
     * @param strict are we in strict mode
     * @return new array data (or same)
     */
    public abstract ArrayData set(int index, double value, boolean strict);

    /**
     * Set an empty value at a given index. Should only affect Object array.
     *
     * @param index the index
     * @return new array data (or same)
     */
    public ArrayData setEmpty(final int index) {
        // Do nothing.
        return this;
    }

    /**
     * Set an empty value for a given range. Should only affect Object array.
     *
     * @param lo range low end
     * @param hi range high end
     * @return new array data (or same)
     */
    public ArrayData setEmpty(final long lo, final long hi) {
        // Do nothing.
        return this;
    }

    /**
     * Get an int value from a given index
     *
     * @param index the index
     * @return the value
     */
    public abstract int getInt(int index);

    /**
     * Returns the optimistic type of this array data. Basically, when an array data object needs to throw an
     * {@link UnwarrantedOptimismException}, this type is used as the actual type of the return value.
     * @return the optimistic type of this array data.
     */
    public Type getOptimisticType() {
        return Type.OBJECT;
    }

    /**
     * Get optimistic int - default is that it's impossible. Overridden
     * by arrays that actually represents ints
     *
     * @param index        the index
     * @param programPoint program point
     * @return the value
     */
    public int getIntOptimistic(final int index, final int programPoint) {
        throw new UnwarrantedOptimismException(getObject(index), programPoint, getOptimisticType());
    }

    /**
     * Get a long value from a given index
     *
     * @param index the index
     * @return the value
     */
    public abstract long getLong(int index);

    /**
     * Get optimistic long - default is that it's impossible. Overridden
     * by arrays that actually represents longs or narrower
     *
     * @param index        the index
     * @param programPoint program point
     * @return the value
     */
    public long getLongOptimistic(final int index, final int programPoint) {
        throw new UnwarrantedOptimismException(getObject(index), programPoint, getOptimisticType());
    }

    /**
     * Get a double value from a given index
     *
     * @param index the index
     * @return the value
     */
    public abstract double getDouble(int index);

    /**
     * Get optimistic double - default is that it's impossible. Overridden
     * by arrays that actually represents doubles or narrower
     *
     * @param index        the index
     * @param programPoint program point
     * @return the value
     */
    public double getDoubleOptimistic(final int index, final int programPoint) {
        throw new UnwarrantedOptimismException(getObject(index), programPoint, getOptimisticType());
    }

    /**
     * Get an Object value from a given index
     *
     * @param index the index
     * @return the value
     */
    public abstract Object getObject(int index);

    /**
     * Tests to see if an entry exists (avoids boxing.)
     * @param index the index
     * @return true if entry exists
     */
    public abstract boolean has(int index);

    /**
     * Returns if element at specific index can be deleted or not.
     *
     * @param index the index of the element
     * @param strict are we in strict mode
     *
     * @return true if element can be deleted
     */
    public boolean canDelete(final int index, final boolean strict) {
        return true;
    }

    /**
     * Returns if element at specific index range can be deleted or not.
     *
     * @param fromIndex  the start index
     * @param toIndex    the end index
     * @param strict     are we in strict mode
     *
     * @return true if range can be deleted
     */
    public boolean canDelete(final long fromIndex, final long toIndex, final boolean strict) {
        return true;
    }

    /**
     * Returns property descriptor for element at a given index
     *
     * @param global the global object
     * @param index  the index
     *
     * @return property descriptor for element
     */
    public PropertyDescriptor getDescriptor(final Global global, final int index) {
        return global.newDataDescriptor(getObject(index), true, true, true);
    }

    /**
     * Delete an array value at the given index, substituting
     * for an undefined
     *
     * @param index the index
     * @return new array data (or same)
     */
    public abstract ArrayData delete(int index);

    /**
     * Delete a given range from this array;
     *
     * @param fromIndex  from index (inclusive)
     * @param toIndex    to index (inclusive)
     *
     * @return new ArrayData after deletion
     */
    public abstract ArrayData delete(long fromIndex, long toIndex);

    /**
     * Convert the ArrayData to one with a different element type
     * Currently Arrays are not collapsed to narrower types, just to
     * wider ones. Attempting to narrow an array will assert
     *
     * @param type new element type
     * @return new array data
     */
    protected abstract ArrayData convert(Class<?> type);

    /**
     * Push an array of items to the end of the array
     *
     * @param strict are we in strict mode
     * @param items  the items
     * @return new array data (or same)
     */
    public ArrayData push(final boolean strict, final Object... items) {
        if (items.length == 0) {
            return this;
        }

        final Class<?>  widest  = widestType(items);

        ArrayData newData = convert(widest);
        long      pos     = newData.length();
        for (final Object item : items) {
            newData = newData.ensure(pos); //avoid sparse array
            newData.set((int)pos++, item, strict);
        }
        return newData;
    }

    /**
     * Push an array of items to the end of the array
     *
     * @param strict are we in strict mode
     * @param item   the item
     * @return new array data (or same)
     */
    public ArrayData push(final boolean strict, final Object item) {
        return push(strict, new Object[] { item });
    }

    /**
     * Push an array of items to the end of the array
     *
     * @param strict are we in strict mode
     * @param item   the item
     * @return new array data (or same)
     */
    public ArrayData push(final boolean strict, final double item) {
        return push(strict, item);
    }

    /**
     * Push an array of items to the end of the array
     *
     * @param strict are we in strict mode
     * @param item   the item
     * @return new array data (or same)
     */
    public ArrayData push(final boolean strict, final long item) {
        return push(strict, item);
    }

    /**
     * Push an array of items to the end of the array
     *
     * @param strict are we in strict mode
     * @param item   the item
     * @return new array data (or same)
     */
    public ArrayData push(final boolean strict, final int item) {
        return push(strict, item);
    }

    /**
     * Pop an element from the end of the array
     *
     * @return the popped element
     */
    public abstract Object pop();

    /**
     * Slice out a section of the array and return that
     * subsection as a new array data: [from, to)
     *
     * @param from start index
     * @param to   end index + 1
     * @return new array data
     */
    public abstract ArrayData slice(long from, long to);

    /**
     * Fast splice operation. This just modifies the array according to the number of
     * elements added and deleted but does not insert the added elements. Throws
     * {@code UnsupportedOperationException} if fast splice operation is not supported
     * for this class or arguments.
     *
     * @param start start index of splice operation
     * @param removed number of removed elements
     * @param added number of added elements
     * @throws UnsupportedOperationException if fast splice is not supported for the class or arguments.
     * @return new arraydata, but this never happens because we always throw an exception
     */
    public ArrayData fastSplice(final int start, final int removed, final int added) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    static Class<?> widestType(final Object... items) {
        assert items.length > 0;

        Class<?> widest = Integer.class;

        for (final Object item : items) {
            if (item == null) {
                return Object.class;
            }
            final Class<?> itemClass = item.getClass();
            if (itemClass == Long.class) {
                if (widest == Integer.class) {
                    widest = Long.class;
                }
            } else if (itemClass == Double.class || itemClass == Float.class) {
                if (widest == Integer.class || widest == Long.class) {
                    widest = Double.class;
                }
            } else if (itemClass != Integer.class && itemClass != Short.class && itemClass != Byte.class) {
                return Object.class;
            }
        }

        return widest;
    }

    /**
     * Exponential growth function for array size when in
     * need of resizing.
     *
     * @param size current size
     * @return next size to allocate for internal array
     */
    protected static int nextSize(final int size) {
        return alignUp(size + 1) * 2;
    }

    /**
     * Return the next valid index from a given one. Subclassed for various
     * array representation
     *
     * @param index the current index
     *
     * @return the next index
     */
    public long nextIndex(final long index) {
        return index + 1;
    }

    static Object invoke(final MethodHandle mh, final Object arg) {
        try {
            return mh.invoke(arg);
        } catch (final RuntimeException | Error e) {
            throw e;
        } catch (final Throwable t) {
            throw new RuntimeException(t);
        }
    }

    /**
     * Find a fast property getter if one exists
     *
     * @param clazz    array data class
     * @param desc     callsite descriptor
     * @param request  link request
     * @param operator operator
     * @return fast property getter if one is found
     */
    public GuardedInvocation findFastGetMethod(final Class<? extends ArrayData> clazz, final CallSiteDescriptor desc, final LinkRequest request, final String operator) {
        return null;
    }

    /**
     * Find a fast element getter if one exists
     *
     * @param clazz   array data class
     * @param desc    callsite descriptor
     * @param request link request
     * @return fast index getter if one is found
     */
    public GuardedInvocation findFastGetIndexMethod(final Class<? extends ArrayData> clazz, final CallSiteDescriptor desc, final LinkRequest request) { // array, index, value
        return null;
    }

    /**
     * Find a fast element setter if one exists
     *
     * @param clazz   array data class
     * @param desc    callsite descriptor
     * @param request link request
     * @return fast index getter if one is found
     */
    public GuardedInvocation findFastSetIndexMethod(final Class<? extends ArrayData> clazz, final CallSiteDescriptor desc, final LinkRequest request) { // array, index, value
        return null;
    }

}