aboutsummaryrefslogtreecommitdiff
path: root/src/jdk/nashorn/internal/runtime/JSType.java
blob: 4d1d825c852dbd092c115238e13a5d4bd93c2f4a (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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
/*
 * 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;

import static jdk.nashorn.internal.codegen.CompilerConstants.staticCall;
import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;

import java.util.Locale;
import jdk.internal.dynalink.beans.BeansLinker;
import jdk.internal.dynalink.beans.StaticClass;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import jdk.nashorn.internal.codegen.CompilerConstants.Call;
import jdk.nashorn.internal.parser.Lexer;

/**
 * Representation for ECMAScript types - this maps directly to the ECMA script standard
 */
public enum JSType {
    /** The undefined type */
    UNDEFINED,

    /** The null type */
    NULL,

    /** The boolean type */
    BOOLEAN,

    /** The number type */
    NUMBER,

    /** The string type */
    STRING,

    /** The object type */
    OBJECT,

    /** The function type */
    FUNCTION;

    /** Max value for an uint32 in JavaScript */
    public static final long MAX_UINT = 0xFFFF_FFFFL;

    /** JavaScript compliant conversion function from Object to boolean */
    public static final Call TO_BOOLEAN = staticCall(JSType.class, "toBoolean", boolean.class, Object.class);

    /** JavaScript compliant conversion function from number to boolean */
    public static final Call TO_BOOLEAN_D = staticCall(JSType.class, "toBoolean", boolean.class, double.class);

    /** JavaScript compliant conversion function from Object to integer */
    public static final Call TO_INTEGER = staticCall(JSType.class, "toInteger", int.class, Object.class);

    /** JavaScript compliant conversion function from Object to long */
    public static final Call TO_LONG = staticCall(JSType.class, "toLong", long.class, Object.class);

    /** JavaScript compliant conversion function from Object to number */
    public static final Call TO_NUMBER = staticCall(JSType.class, "toNumber", double.class, Object.class);

    /** JavaScript compliant conversion function from Object to int32 */
    public static final Call TO_INT32 = staticCall(JSType.class, "toInt32", int.class, Object.class);

    /** JavaScript compliant conversion function from double to int32 */
    public static final Call TO_INT32_D = staticCall(JSType.class, "toInt32", int.class, double.class);

    /** JavaScript compliant conversion function from Object to uint32 */
    public static final Call TO_UINT32 = staticCall(JSType.class, "toUint32", long.class, Object.class);

    /** JavaScript compliant conversion function from number to uint32 */
    public static final Call TO_UINT32_D = staticCall(JSType.class, "toUint32", long.class, double.class);

    /** JavaScript compliant conversion function from Object to int64 */
    public static final Call TO_INT64 = staticCall(JSType.class, "toInt64", long.class, Object.class);

    /** JavaScript compliant conversion function from number to int64 */
    public static final Call TO_INT64_D = staticCall(JSType.class, "toInt64", long.class, double.class);

    /** JavaScript compliant conversion function from Object to String */
    public static final Call TO_STRING = staticCall(JSType.class, "toString", String.class, Object.class);

    /** JavaScript compliant conversion function from number to String */
    public static final Call TO_STRING_D = staticCall(JSType.class, "toString", String.class, double.class);

    /** JavaScript compliant conversion function from Object to primitive */
    public static final Call TO_PRIMITIVE = staticCall(JSType.class, "toPrimitive", Object.class,  Object.class);

    private static final double INT32_LIMIT = 4294967296.0;

    /**
     * The external type name as returned by ECMAScript "typeof" operator
     *
     * @return type name for this type
     */
    public final String typeName() {
        // For NULL, "object" has to be returned!
        return ((this == NULL) ? OBJECT : this).name().toLowerCase(Locale.ENGLISH);
    }

    /**
     * Return the JSType for a given object
     *
     * @param obj an object
     *
     * @return the JSType for the object
     */
    public static JSType of(final Object obj) {
        if (obj == ScriptRuntime.UNDEFINED) {
            return JSType.UNDEFINED;
        }

        if (obj == null) {
            return JSType.NULL;
        }

        if (obj instanceof Boolean) {
            return JSType.BOOLEAN;
        }

        if (obj instanceof Number) {
            return JSType.NUMBER;
        }

        if (obj instanceof String || obj instanceof ConsString) {
            return JSType.STRING;
        }

        if (obj instanceof ScriptObject) {
            return (obj instanceof ScriptFunction) ? JSType.FUNCTION : JSType.OBJECT;
        }

        if (obj instanceof StaticClass) {
            return JSType.FUNCTION;
        }

        if (BeansLinker.isDynamicMethod(obj)) {
            return JSType.FUNCTION;
        }

        if (obj instanceof ScriptObjectMirror) {
            return ((ScriptObjectMirror)obj).isFunction()? JSType.FUNCTION : JSType.OBJECT;
        }

        return JSType.OBJECT;
    }

    /**
     * Returns true if double number can be represented as an int
     *
     * @param number a long to inspect
     *
     * @return true for int representable longs
     */
    public static boolean isRepresentableAsInt(final long number) {
        return (int)number == number;
    }

    /**
     * Returns true if double number can be represented as an int
     *
     * @param number a double to inspect
     *
     * @return true for int representable doubles
     */
    public static boolean isRepresentableAsInt(final double number) {
        return (int)number == number;
    }

    /**
     * Returns true if double number can be represented as a long
     *
     * @param number a double to inspect
     * @return true for long representable doubles
     */
    public static boolean isRepresentableAsLong(final double number) {
        return (long)number == number;
    }

    /**
     * Get the smallest integer representation of a number. Returns an Integer
     * for something that is int representable, and Long for something that
     * is long representable. If the number needs to be a double, this is an
     * identity function
     *
     * @param number number to check
     *
     * @return Number instanceof the narrowest possible integer representation for number
     */
    public static Number narrowestIntegerRepresentation(final double number) {
        if (isRepresentableAsInt(number)) {
            return (int)number;
        } else if (isRepresentableAsLong(number)) {
            return (long)number;
        } else {
            return number;
        }
    }

    /**
     * Check whether an object is primitive
     *
     * @param obj an object
     *
     * @return true if object is primitive (includes null and undefined)
     */
   public static boolean isPrimitive(final Object obj) {
        return obj == null ||
               obj == ScriptRuntime.UNDEFINED ||
               obj instanceof Boolean ||
               obj instanceof Number ||
               obj instanceof String ||
               obj instanceof ConsString;
    }

   /**
    * Primitive converter for an object
    *
    * @param obj an object
    *
    * @return primitive form of the object
    */
    public static Object toPrimitive(final Object obj) {
        return toPrimitive(obj, null);
    }

    /**
     * Primitive converter for an object including type hint
     * See ECMA 9.1 ToPrimitive
     *
     * @param obj  an object
     * @param hint a type hint
     *
     * @return the primitive form of the object
     */
    public static Object toPrimitive(final Object obj, final Class<?> hint) {
        if (!(obj instanceof ScriptObject)) {
            return obj;
        }

        final ScriptObject sobj   = (ScriptObject)obj;
        final Object       result = sobj.getDefaultValue(hint);

        if (!isPrimitive(result)) {
            throw typeError("bad.default.value", result.toString());
        }

        return result;
    }

    /**
     * JavaScript compliant conversion of number to boolean
     *
     * @param num a number
     *
     * @return a boolean
     */
    public static boolean toBoolean(final double num) {
        return num != 0 && !Double.isNaN(num);
    }

    /**
     * JavaScript compliant conversion of Object to boolean
     * See ECMA 9.2 ToBoolean
     *
     * @param obj an object
     *
     * @return a boolean
     */
    public static boolean toBoolean(final Object obj) {
        if (obj instanceof Boolean) {
            return (Boolean)obj;
        }

        if (nullOrUndefined(obj)) {
            return false;
        }

        if (obj instanceof Number) {
            final double num = ((Number)obj).doubleValue();
            return num != 0 && !Double.isNaN(num);
        }

        if (obj instanceof String || obj instanceof ConsString) {
            return ((CharSequence)obj).length() > 0;
        }

        return true;
    }


    /**
     * JavaScript compliant converter of Object to String
     * See ECMA 9.8 ToString
     *
     * @param obj an object
     *
     * @return a string
     */
    public static String toString(final Object obj) {
        return toStringImpl(obj, false);
    }

    /**
     * If obj is an instance of {@link ConsString} cast to CharSequence, else return
     * result of {@link #toString(Object)}.
     *
     * @param obj an object
     * @return an instance of String or ConsString
     */
    public static CharSequence toCharSequence(final Object obj) {
        if (obj instanceof ConsString) {
            return (CharSequence) obj;
        }
        return toString(obj);
    }

    /**
     * Check whether a string is representable as a JavaScript number
     *
     * @param str  a string
     *
     * @return     true if string can be represented as a number
     */
    public static boolean isNumber(final String str) {
        try {
            Double.parseDouble(str);
            return true;
        } catch (final NumberFormatException e) {
            return false;
        }
    }

    /**
     * JavaScript compliant conversion of integer to String
     *
     * @param num an integer
     *
     * @return a string
     */
    public static String toString(final int num) {
        return Integer.toString(num);
    }

    /**
     * JavaScript compliant conversion of number to String
     * See ECMA 9.8.1
     *
     * @param num a number
     *
     * @return a string
     */
    public static String toString(final double num) {
        if (isRepresentableAsInt(num)) {
            return Integer.toString((int)num);
        }

        if (num == Double.POSITIVE_INFINITY) {
            return "Infinity";
        }

        if (num == Double.NEGATIVE_INFINITY) {
            return "-Infinity";
        }

        if (Double.isNaN(num)) {
            return "NaN";
        }

        return NumberToString.stringFor(num);
    }

    /**
     * JavaScript compliant conversion of number to String
     *
     * @param num   a number
     * @param radix a radix for the conversion
     *
     * @return a string
     */
    public static String toString(final double num, final int radix) {
        assert radix >= 2 && radix <= 36 : "invalid radix";

        if (isRepresentableAsInt(num)) {
            return Integer.toString((int)num, radix);
        }

        if (num == Double.POSITIVE_INFINITY) {
            return "Infinity";
        }

        if (num == Double.NEGATIVE_INFINITY) {
            return "-Infinity";
        }

        if (Double.isNaN(num)) {
            return "NaN";
        }

        if (num == 0.0) {
            return "0";
        }

        final String chars     = "0123456789abcdefghijklmnopqrstuvwxyz";
        final StringBuilder sb = new StringBuilder();

        final boolean negative  = num < 0.0;
        final double  signedNum = negative ? -num : num;

        double intPart = Math.floor(signedNum);
        double decPart = signedNum - intPart;

        // encode integer part from least significant digit, then reverse
        do {
            sb.append(chars.charAt((int) (intPart % radix)));
            intPart /= radix;
        } while (intPart >= 1.0);

        if (negative) {
            sb.append('-');
        }
        sb.reverse();

        // encode decimal part
        if (decPart > 0.0) {
            final int dot = sb.length();
            sb.append('.');
            do {
                decPart *= radix;
                final double d = Math.floor(decPart);
                sb.append(chars.charAt((int)d));
                decPart -= d;
            } while (decPart > 0.0 && sb.length() - dot < 1100);
            // somewhat arbitrarily use same limit as V8
        }

        return sb.toString();
    }

    /**
     * JavaScript compliant conversion of Object to number
     * See ECMA 9.3 ToNumber
     *
     * @param obj  an object
     *
     * @return a number
     */
    public static double toNumber(final Object obj) {
        if (obj instanceof Number) {
            return ((Number)obj).doubleValue();
        }
        return toNumberGeneric(obj);
    }

    /**
     * Digit representation for a character
     *
     * @param ch     a character
     * @param radix  radix
     *
     * @return the digit for this character
     */
    public static int digit(final char ch, final int radix) {
        return digit(ch, radix, false);
    }

    /**
     * Digit representation for a character
     *
     * @param ch             a character
     * @param radix          radix
     * @param onlyIsoLatin1  iso latin conversion only
     *
     * @return the digit for this character
     */
    public static int digit(final char ch, final int radix, final boolean onlyIsoLatin1) {
        final char maxInRadix = (char)('a' + (radix - 1) - 10);
        final char c          = Character.toLowerCase(ch);

        if (c >= 'a' && c <= maxInRadix) {
            return Character.digit(ch, radix);
        }

        if (Character.isDigit(ch)) {
            if (!onlyIsoLatin1 || ch >= '0' && ch <= '9') {
                return Character.digit(ch, radix);
            }
        }

        return -1;
    }

    /**
     * JavaScript compliant String to number conversion
     *
     * @param str  a string
     *
     * @return a number
     */
    public static double toNumber(final String str) {
        int end = str.length();
        if (end == 0) {
            return 0.0; // Empty string
        }

        int  start = 0;
        char f     = str.charAt(0);

        while (Lexer.isJSWhitespace(f)) {
            if (++start == end) {
                return 0.0d; // All whitespace string
            }
            f = str.charAt(start);
        }

        // Guaranteed to terminate even without start >= end check, as the previous loop found at least one
        // non-whitespace character.
        while (Lexer.isJSWhitespace(str.charAt(end - 1))) {
            end--;
        }

        final boolean negative;
        if (f == '-') {
            if(++start == end) {
                return Double.NaN; // Single-char "-" string
            }
            f = str.charAt(start);
            negative = true;
        } else {
            if (f == '+') {
                if (++start == end) {
                    return Double.NaN; // Single-char "+" string
                }
                f = str.charAt(start);
            }
            negative = false;
        }

        final double value;
        if (start + 1 < end && f == '0' && Character.toLowerCase(str.charAt(start + 1)) == 'x') {
            //decode hex string
            value = parseRadix(str.toCharArray(), start + 2, end, 16);
        } else {
            // Fast (no NumberFormatException) path to NaN for non-numeric strings. We allow those starting with "I" or
            // "N" to allow for parsing "NaN" and "Infinity" correctly.
            if ((f < '0' || f > '9') && f != '.' && f != 'I' && f != 'N') {
                return Double.NaN;
            }
            try {
                value = Double.parseDouble(str.substring(start, end));
            } catch (final NumberFormatException e) {
                return Double.NaN;
            }
        }

        return negative ? -value : value;
    }

    /**
     * JavaScript compliant Object to integer conversion. See ECMA 9.4 ToInteger
     *
     * <p>Note that this returns {@link java.lang.Integer#MAX_VALUE} or {@link java.lang.Integer#MIN_VALUE}
     * for double values that exceed the int range, including positive and negative Infinity. It is the
     * caller's responsibility to handle such values correctly.</p>
     *
     * @param obj  an object
     * @return an integer
     */
    public static int toInteger(final Object obj) {
        return (int)toNumber(obj);
    }

    /**
     * JavaScript compliant Object to long conversion. See ECMA 9.4 ToInteger
     *
     * <p>Note that this returns {@link java.lang.Long#MAX_VALUE} or {@link java.lang.Long#MIN_VALUE}
     * for double values that exceed the long range, including positive and negative Infinity. It is the
     * caller's responsibility to handle such values correctly.</p>
     *
     * @param obj  an object
     * @return a long
     */
    public static long toLong(final Object obj) {
        return (long)toNumber(obj);
    }

    /**
     * JavaScript compliant Object to int32 conversion
     * See ECMA 9.5 ToInt32
     *
     * @param obj an object
     * @return an int32
     */
    public static int toInt32(final Object obj) {
        return toInt32(toNumber(obj));
    }

    /**
     * JavaScript compliant long to int32 conversion
     *
     * @param num a long
     * @return an int32
     */
    public static int toInt32(final long num) {
        return (int)num;
    }

    /**
     * JavaScript compliant number to int32 conversion
     *
     * @param num a number
     * @return an int32
     */
    public static int toInt32(final double num) {
        return (int)doubleToInt32(num);
    }

    /**
     * JavaScript compliant Object to int64 conversion
     *
     * @param obj an object
     * @return an int64
     */
    public static long toInt64(final Object obj) {
        return toInt64(toNumber(obj));
    }

    /**
     * JavaScript compliant number to int64 conversion
     *
     * @param num a number
     * @return an int64
     */
    public static long toInt64(final double num) {
        if (Double.isInfinite(num)) {
            return 0L;
        }
        return (long)num;
    }

    /**
     * JavaScript compliant Object to uint32 conversion
     *
     * @param obj an object
     * @return a uint32
     */
    public static long toUint32(final Object obj) {
        return toUint32(toNumber(obj));
    }

    /**
     * JavaScript compliant number to uint32 conversion
     *
     * @param num a number
     * @return a uint32
     */
    public static long toUint32(final double num) {
        return doubleToInt32(num) & MAX_UINT;
    }

    /**
     * JavaScript compliant Object to uint16 conversion
     * ECMA 9.7 ToUint16: (Unsigned 16 Bit Integer)
     *
     * @param obj an object
     * @return a uint16
     */
    public static int toUint16(final Object obj) {
        return toUint16(toNumber(obj));
    }

    /**
     * JavaScript compliant number to uint16 conversion
     *
     * @param num a number
     * @return a uint16
     */
    public static int toUint16(final int num) {
        return num & 0xffff;
    }

    /**
     * JavaScript compliant number to uint16 conversion
     *
     * @param num a number
     * @return a uint16
     */
    public static int toUint16(final long num) {
        return ((int)num) & 0xffff;
    }

    /**
     * JavaScript compliant number to uint16 conversion
     *
     * @param num a number
     * @return a uint16
     */
    public static int toUint16(final double num) {
        return ((int)doubleToInt32(num)) & 0xffff;
    }

    private static long doubleToInt32(final double num) {
        final int exponent = Math.getExponent(num);
        if (exponent < 31) {
            return (long) num;  // Fits into 32 bits
        }
        if (exponent >= 84) {
            // Either infinite or NaN or so large that shift / modulo will produce 0
            // (52 bit mantissa + 32 bit target width).
            return 0;
        }
        // This is rather slow and could probably be sped up using bit-fiddling.
        final double d = (num >= 0) ? Math.floor(num) : Math.ceil(num);
        return (long)(d % INT32_LIMIT);
    }

    /**
     * Check whether a number is finite
     *
     * @param num a number
     * @return true if finite
     */
    public static boolean isFinite(final double num) {
        return !Double.isInfinite(num) && !Double.isNaN(num);
    }

    /**
     * Convert a primitive to a double
     *
     * @param num a double
     * @return a boxed double
     */
    public static Double toDouble(final double num) {
        return num;
    }

    /**
     * Convert a primitive to a double
     *
     * @param num a long
     * @return a boxed double
     */
    public static Double toDouble(final long num) {
        return (double)num;
    }

    /**
     * Convert a primitive to a double
     *
     * @param num an int
     * @return a boxed double
     */
    public static Double toDouble(final int num) {
        return (double)num;
    }

    /**
     * Convert a boolean to an Object
     *
     * @param bool a boolean
     * @return a boxed boolean, its Object representation
     */
    public static Object toObject(final boolean bool) {
        return bool;
    }

    /**
     * Convert a number to an Object
     *
     * @param num an integer
     * @return the boxed number
     */
    public static Object toObject(final int num) {
        return num;
    }

    /**
     * Convert a number to an Object
     *
     * @param num a long
     * @return the boxed number
     */
    public static Object toObject(final long num) {
        return num;
    }

    /**
     * Convert a number to an Object
     *
     * @param num a double
     * @return the boxed number
     */
    public static Object toObject(final double num) {
        return num;
    }

    /**
     * Identity converter for objects.
     *
     * @param obj an object
     * @return the boxed number
     */
    public static Object toObject(final Object obj) {
        return obj;
    }

    /**
     * Object conversion. This is used to convert objects and numbers to their corresponding
     * NativeObject type
     * See ECMA 9.9 ToObject
     *
     * @param obj     the object to convert
     *
     * @return the wrapped object
     */
    public static Object toScriptObject(final Object obj) {
        return toScriptObject(Context.getGlobalTrusted(), obj);
    }

    /**
     * Object conversion. This is used to convert objects and numbers to their corresponding
     * NativeObject type
     * See ECMA 9.9 ToObject
     *
     * @param global  the global object
     * @param obj     the object to convert
     *
     * @return the wrapped object
     */
    public static Object toScriptObject(final ScriptObject global, final Object obj) {
        if (nullOrUndefined(obj)) {
            throw typeError(global, "not.an.object", ScriptRuntime.safeToString(obj));
        }

        if (obj instanceof ScriptObject) {
            return obj;
        }

        return ((GlobalObject)global).wrapAsObject(obj);
    }

    /**
     * Check if an object is null or undefined
     *
     * @param obj object to check
     *
     * @return true if null or undefined
     */
    public static boolean nullOrUndefined(final Object obj) {
        return obj == null || obj == ScriptRuntime.UNDEFINED;
    }

    static String toStringImpl(final Object obj, final boolean safe) {
        if (obj instanceof String) {
            return (String)obj;
        }

        if (obj instanceof Number) {
            return toString(((Number)obj).doubleValue());
        }

        if (obj == ScriptRuntime.UNDEFINED) {
            return "undefined";
        }

        if (obj == null) {
            return "null";
        }

        if (obj instanceof ScriptObject) {
            if (safe) {
                final ScriptObject sobj = (ScriptObject)obj;
                final GlobalObject gobj = (GlobalObject)Context.getGlobalTrusted();
                return gobj.isError(sobj) ?
                    ECMAException.safeToString(sobj) :
                    sobj.safeToString();
            }

            return toString(toPrimitive(obj, String.class));
        }

        if (obj instanceof StaticClass) {
            return "[JavaClass " + ((StaticClass)obj).getRepresentedClass().getName() + "]";
        }

        return obj.toString();
    }

    // trim from left for JS whitespaces.
    static String trimLeft(final String str) {
        int start = 0;

        while (start < str.length() && Lexer.isJSWhitespace(str.charAt(start))) {
            start++;
        }

        return str.substring(start);
    }

    private static double parseRadix(final char chars[], final int start, final int length, final int radix) {
        int pos = 0;

        for (int i = start; i < length ; i++) {
            if (digit(chars[i], radix) == -1) {
                return Double.NaN;
            }
            pos++;
        }

        if (pos == 0) {
            return Double.NaN;
        }

        double value = 0.0;
        for (int i = start; i < start + pos; i++) {
            value *= radix;
            value += digit(chars[i], radix);
        }

        return value;
    }

    private static double toNumberGeneric(final Object obj) {
        if (obj == null) {
            return +0.0;
        }

        if (obj instanceof String) {
            return toNumber((String)obj);
        }

        if (obj instanceof ConsString) {
            return toNumber(obj.toString());
        }

        if (obj instanceof Boolean) {
            return (Boolean)obj ? 1 : +0.0;
        }

        if (obj instanceof ScriptObject) {
            return toNumber(toPrimitive(obj, Number.class));
        }

        return Double.NaN;
    }

}