-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathjsnum.cpp
2270 lines (1946 loc) · 62.2 KB
/
jsnum.cpp
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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* JS number type and wrapper class.
*/
#include "jsnum.h"
#include "mozilla/Casting.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/Maybe.h"
#include "mozilla/RangedPtr.h"
#include "mozilla/TextUtils.h"
#include "mozilla/Utf8.h"
#include <algorithm>
#include <charconv>
#include <iterator>
#include <limits>
#ifdef HAVE_LOCALECONV
# include <locale.h>
#endif
#include <math.h>
#include <string.h> // memmove
#include <string_view>
#include "jstypes.h"
#include "builtin/String.h"
#include "double-conversion/double-conversion.h"
#include "frontend/ParserAtom.h" // frontend::{ParserAtomsTable, TaggedParserAtomIndex}
#include "jit/InlinableNatives.h"
#include "js/CharacterEncoding.h"
#include "js/Conversions.h"
#include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
#include "js/GCAPI.h"
#if !JS_HAS_INTL_API
# include "js/LocaleSensitive.h"
#endif
#include "js/PropertyAndElement.h" // JS_DefineFunctions
#include "js/PropertySpec.h"
#include "util/DoubleToString.h"
#include "util/Memory.h"
#include "util/StringBuilder.h"
#include "vm/BigIntType.h"
#include "vm/GlobalObject.h"
#include "vm/JSAtomUtils.h" // Atomize, AtomizeString
#include "vm/JSContext.h"
#include "vm/JSObject.h"
#include "vm/StaticStrings.h"
#include "vm/Compartment-inl.h" // For js::UnwrapAndTypeCheckThis
#include "vm/GeckoProfiler-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/NumberObject-inl.h"
#include "vm/StringType-inl.h"
using namespace js;
using mozilla::Abs;
using mozilla::AsciiAlphanumericToNumber;
using mozilla::IsAsciiAlphanumeric;
using mozilla::IsAsciiDigit;
using mozilla::MaxNumberValue;
using mozilla::Maybe;
using mozilla::MinNumberValue;
using mozilla::NegativeInfinity;
using mozilla::NumberEqualsInt32;
using mozilla::PositiveInfinity;
using mozilla::RangedPtr;
using mozilla::Utf8AsUnsignedChars;
using mozilla::Utf8Unit;
using JS::AutoCheckCannotGC;
using JS::GenericNaN;
using JS::ToInt16;
using JS::ToInt32;
using JS::ToInt64;
using JS::ToInt8;
using JS::ToUint16;
using JS::ToUint32;
using JS::ToUint64;
using JS::ToUint8;
static bool EnsureDtoaState(JSContext* cx) {
if (!cx->dtoaState) {
cx->dtoaState = NewDtoaState();
if (!cx->dtoaState) {
return false;
}
}
return true;
}
template <typename CharT>
static inline void AssertWellPlacedNumericSeparator(const CharT* s,
const CharT* start,
const CharT* end) {
MOZ_ASSERT(start < end, "string is non-empty");
MOZ_ASSERT(s > start, "number can't start with a separator");
MOZ_ASSERT(s + 1 < end,
"final character in a numeric literal can't be a separator");
MOZ_ASSERT(*(s + 1) != '_',
"separator can't be followed by another separator");
MOZ_ASSERT(*(s - 1) != '_',
"separator can't be preceded by another separator");
}
namespace {
template <typename CharT>
class BinaryDigitReader {
const int base; /* Base of number; must be a power of 2 */
int digit; /* Current digit value in radix given by base */
int digitMask; /* Mask to extract the next bit from digit */
const CharT* cur; /* Pointer to the remaining digits */
const CharT* start; /* Pointer to the start of the string */
const CharT* end; /* Pointer to first non-digit */
public:
BinaryDigitReader(int base, const CharT* start, const CharT* end)
: base(base),
digit(0),
digitMask(0),
cur(start),
start(start),
end(end) {}
/* Return the next binary digit from the number, or -1 if done. */
int nextDigit() {
if (digitMask == 0) {
if (cur == end) {
return -1;
}
int c = *cur++;
if (c == '_') {
AssertWellPlacedNumericSeparator(cur - 1, start, end);
c = *cur++;
}
MOZ_ASSERT(IsAsciiAlphanumeric(c));
digit = AsciiAlphanumericToNumber(c);
digitMask = base >> 1;
}
int bit = (digit & digitMask) != 0;
digitMask >>= 1;
return bit;
}
};
} /* anonymous namespace */
/*
* The fast result might also have been inaccurate for power-of-two bases. This
* happens if the addition in value * 2 + digit causes a round-down to an even
* least significant mantissa bit when the first dropped bit is a one. If any
* of the following digits in the number (which haven't been added in yet) are
* nonzero, then the correct action would have been to round up instead of
* down. An example occurs when reading the number 0x1000000000000081, which
* rounds to 0x1000000000000000 instead of 0x1000000000000100.
*/
template <typename CharT>
static double ComputeAccurateBinaryBaseInteger(const CharT* start,
const CharT* end, int base) {
BinaryDigitReader<CharT> bdr(base, start, end);
/* Skip leading zeroes. */
int bit;
do {
bit = bdr.nextDigit();
} while (bit == 0);
MOZ_ASSERT(bit == 1); // guaranteed by Get{Prefix,Decimal}Integer
/* Gather the 53 significant bits (including the leading 1). */
double value = 1.0;
for (int j = 52; j > 0; j--) {
bit = bdr.nextDigit();
if (bit < 0) {
return value;
}
value = value * 2 + bit;
}
/* bit2 is the 54th bit (the first dropped from the mantissa). */
int bit2 = bdr.nextDigit();
if (bit2 >= 0) {
double factor = 2.0;
int sticky = 0; /* sticky is 1 if any bit beyond the 54th is 1 */
int bit3;
while ((bit3 = bdr.nextDigit()) >= 0) {
sticky |= bit3;
factor *= 2;
}
value += bit2 & (bit | sticky);
value *= factor;
}
return value;
}
template <typename CharT>
double js::ParseDecimalNumber(const mozilla::Range<const CharT> chars) {
MOZ_ASSERT(chars.length() > 0);
uint64_t dec = 0;
RangedPtr<const CharT> s = chars.begin(), end = chars.end();
do {
CharT c = *s;
MOZ_ASSERT('0' <= c && c <= '9');
uint8_t digit = c - '0';
uint64_t next = dec * 10 + digit;
MOZ_ASSERT(next < DOUBLE_INTEGRAL_PRECISION_LIMIT,
"next value won't be an integrally-precise double");
dec = next;
} while (++s < end);
return static_cast<double>(dec);
}
template double js::ParseDecimalNumber(
const mozilla::Range<const Latin1Char> chars);
template double js::ParseDecimalNumber(
const mozilla::Range<const char16_t> chars);
template <typename CharT>
static bool GetPrefixIntegerImpl(const CharT* start, const CharT* end, int base,
IntegerSeparatorHandling separatorHandling,
const CharT** endp, double* dp) {
MOZ_ASSERT(start <= end);
MOZ_ASSERT(2 <= base && base <= 36);
const CharT* s = start;
double d = 0.0;
for (; s < end; s++) {
CharT c = *s;
if (!IsAsciiAlphanumeric(c)) {
if (c == '_' &&
separatorHandling == IntegerSeparatorHandling::SkipUnderscore) {
AssertWellPlacedNumericSeparator(s, start, end);
continue;
}
break;
}
uint8_t digit = AsciiAlphanumericToNumber(c);
if (digit >= base) {
break;
}
d = d * base + digit;
}
*endp = s;
*dp = d;
/* If we haven't reached the limit of integer precision, we're done. */
if (d < DOUBLE_INTEGRAL_PRECISION_LIMIT) {
return true;
}
/*
* Otherwise compute the correct integer from the prefix of valid digits
* if we're computing for base ten or a power of two. Don't worry about
* other bases; see ES2018, 18.2.5 `parseInt(string, radix)`, step 13.
*/
if (base == 10) {
return false;
}
if ((base & (base - 1)) == 0) {
*dp = ComputeAccurateBinaryBaseInteger(start, s, base);
}
return true;
}
template <typename CharT>
bool js::GetPrefixInteger(const CharT* start, const CharT* end, int base,
IntegerSeparatorHandling separatorHandling,
const CharT** endp, double* dp) {
if (GetPrefixIntegerImpl(start, end, base, separatorHandling, endp, dp)) {
return true;
}
// Can only fail for base 10.
MOZ_ASSERT(base == 10);
// If we're accumulating a decimal number and the number is >= 2^53, then the
// fast result from the loop in GetPrefixIntegerImpl may be inaccurate. Call
// GetDecimal to get the correct answer.
return GetDecimal(start, *endp, dp);
}
namespace js {
template bool GetPrefixInteger(const char16_t* start, const char16_t* end,
int base,
IntegerSeparatorHandling separatorHandling,
const char16_t** endp, double* dp);
template bool GetPrefixInteger(const Latin1Char* start, const Latin1Char* end,
int base,
IntegerSeparatorHandling separatorHandling,
const Latin1Char** endp, double* dp);
} // namespace js
template <typename CharT>
bool js::GetDecimalInteger(const CharT* start, const CharT* end, double* dp) {
MOZ_ASSERT(start <= end);
double d = 0.0;
for (const CharT* s = start; s < end; s++) {
CharT c = *s;
if (c == '_') {
AssertWellPlacedNumericSeparator(s, start, end);
continue;
}
MOZ_ASSERT(IsAsciiDigit(c));
int digit = c - '0';
d = d * 10 + digit;
}
// If we haven't reached the limit of integer precision, we're done.
if (d < DOUBLE_INTEGRAL_PRECISION_LIMIT) {
*dp = d;
return true;
}
// Otherwise compute the correct integer using GetDecimal.
return GetDecimal(start, end, dp);
}
namespace js {
template bool GetDecimalInteger(const char16_t* start, const char16_t* end,
double* dp);
template bool GetDecimalInteger(const Latin1Char* start, const Latin1Char* end,
double* dp);
template <>
bool GetDecimalInteger<Utf8Unit>(const Utf8Unit* start, const Utf8Unit* end,
double* dp) {
return GetDecimalInteger(Utf8AsUnsignedChars(start), Utf8AsUnsignedChars(end),
dp);
}
} // namespace js
template <typename CharT>
bool js::GetDecimal(const CharT* start, const CharT* end, double* dp) {
MOZ_ASSERT(start <= end);
size_t length = end - start;
auto convert = [](auto* chars, size_t length) -> double {
using SToDConverter = double_conversion::StringToDoubleConverter;
SToDConverter converter(/* flags = */ 0, /* empty_string_value = */ 0.0,
/* junk_string_value = */ 0.0,
/* infinity_symbol = */ nullptr,
/* nan_symbol = */ nullptr);
int lengthInt = mozilla::AssertedCast<int>(length);
int processed = 0;
double d = converter.StringToDouble(chars, lengthInt, &processed);
MOZ_ASSERT(processed >= 0);
MOZ_ASSERT(size_t(processed) == length);
return d;
};
// If there are no underscores, we don't need to copy the chars.
bool hasUnderscore = std::any_of(start, end, [](auto c) { return c == '_'; });
if (!hasUnderscore) {
if constexpr (std::is_same_v<CharT, char16_t>) {
*dp = convert(reinterpret_cast<const uc16*>(start), length);
} else {
static_assert(std::is_same_v<CharT, Latin1Char>);
*dp = convert(reinterpret_cast<const char*>(start), length);
}
return true;
}
Vector<char, 32, SystemAllocPolicy> chars;
if (!chars.growByUninitialized(length)) {
return false;
}
const CharT* s = start;
size_t i = 0;
for (; s < end; s++) {
CharT c = *s;
if (c == '_') {
AssertWellPlacedNumericSeparator(s, start, end);
continue;
}
MOZ_ASSERT(IsAsciiDigit(c) || c == '.' || c == 'e' || c == 'E' ||
c == '+' || c == '-');
chars[i++] = char(c);
}
*dp = convert(chars.begin(), i);
return true;
}
namespace js {
template bool GetDecimal(const char16_t* start, const char16_t* end,
double* dp);
template bool GetDecimal(const Latin1Char* start, const Latin1Char* end,
double* dp);
template <>
bool GetDecimal<Utf8Unit>(const Utf8Unit* start, const Utf8Unit* end,
double* dp) {
return GetDecimal(Utf8AsUnsignedChars(start), Utf8AsUnsignedChars(end), dp);
}
} // namespace js
static bool num_parseFloat(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() == 0) {
args.rval().setNaN();
return true;
}
if (args[0].isNumber()) {
// ToString(-0) is "0", handle it accordingly.
if (args[0].isDouble() && args[0].toDouble() == 0.0) {
args.rval().setInt32(0);
} else {
args.rval().set(args[0]);
}
return true;
}
JSString* str = ToString<CanGC>(cx, args[0]);
if (!str) {
return false;
}
if (str->hasIndexValue()) {
args.rval().setNumber(str->getIndexValue());
return true;
}
JSLinearString* linear = str->ensureLinear(cx);
if (!linear) {
return false;
}
double d;
AutoCheckCannotGC nogc;
if (linear->hasLatin1Chars()) {
const Latin1Char* begin = linear->latin1Chars(nogc);
const Latin1Char* end;
d = js_strtod(begin, begin + linear->length(), &end);
if (end == begin) {
d = GenericNaN();
}
} else {
const char16_t* begin = linear->twoByteChars(nogc);
const char16_t* end;
d = js_strtod(begin, begin + linear->length(), &end);
if (end == begin) {
d = GenericNaN();
}
}
args.rval().setDouble(d);
return true;
}
// ES2023 draft rev 053d34c87b14d9234d6f7f45bd61074b72ca9d69
// 19.2.5 parseInt ( string, radix )
template <typename CharT>
static bool ParseIntImpl(JSContext* cx, const CharT* chars, size_t length,
bool stripPrefix, int32_t radix, double* res) {
// Step 2.
const CharT* end = chars + length;
const CharT* s = SkipSpace(chars, end);
MOZ_ASSERT(chars <= s);
MOZ_ASSERT(s <= end);
// Steps 3-4.
bool negative = (s != end && s[0] == '-');
// Step 5. */
if (s != end && (s[0] == '-' || s[0] == '+')) {
s++;
}
// Step 10.
if (stripPrefix) {
if (end - s >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
s += 2;
radix = 16;
}
}
// Steps 11-15.
const CharT* actualEnd;
double d;
if (!js::GetPrefixInteger(s, end, radix, IntegerSeparatorHandling::None,
&actualEnd, &d)) {
ReportOutOfMemory(cx);
return false;
}
if (s == actualEnd) {
*res = GenericNaN();
} else {
*res = negative ? -d : d;
}
return true;
}
// ES2023 draft rev 053d34c87b14d9234d6f7f45bd61074b72ca9d69
// 19.2.5 parseInt ( string, radix )
bool js::NumberParseInt(JSContext* cx, HandleString str, int32_t radix,
MutableHandleValue result) {
// Step 7.
bool stripPrefix = true;
// Steps 8-9.
if (radix != 0) {
if (radix < 2 || radix > 36) {
result.setNaN();
return true;
}
if (radix != 16) {
stripPrefix = false;
}
} else {
radix = 10;
}
MOZ_ASSERT(2 <= radix && radix <= 36);
JSLinearString* linear = str->ensureLinear(cx);
if (!linear) {
return false;
}
// Steps 2-5, 10-16.
AutoCheckCannotGC nogc;
size_t length = linear->length();
double number;
if (linear->hasLatin1Chars()) {
if (!ParseIntImpl(cx, linear->latin1Chars(nogc), length, stripPrefix, radix,
&number)) {
return false;
}
} else {
if (!ParseIntImpl(cx, linear->twoByteChars(nogc), length, stripPrefix,
radix, &number)) {
return false;
}
}
result.setNumber(number);
return true;
}
// ES2023 draft rev 053d34c87b14d9234d6f7f45bd61074b72ca9d69
// 19.2.5 parseInt ( string, radix )
static bool num_parseInt(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
/* Fast paths and exceptional cases. */
if (args.length() == 0) {
args.rval().setNaN();
return true;
}
if (args.length() == 1 || (args[1].isInt32() && (args[1].toInt32() == 0 ||
args[1].toInt32() == 10))) {
if (args[0].isInt32()) {
args.rval().set(args[0]);
return true;
}
/*
* Step 1 is |inputString = ToString(string)|. When string >=
* 1e21, ToString(string) is in the form "NeM". 'e' marks the end of
* the word, which would mean the result of parseInt(string) should be |N|.
*
* To preserve this behaviour, we can't use the fast-path when string >=
* 1e21, or else the result would be |NeM|.
*
* The same goes for values smaller than 1.0e-6, because the string would be
* in the form of "Ne-M".
*/
if (args[0].isDouble()) {
double d = args[0].toDouble();
if (DOUBLE_DECIMAL_IN_SHORTEST_LOW <= d &&
d < DOUBLE_DECIMAL_IN_SHORTEST_HIGH) {
args.rval().setNumber(floor(d));
return true;
}
if (-DOUBLE_DECIMAL_IN_SHORTEST_HIGH < d &&
d <= -DOUBLE_DECIMAL_IN_SHORTEST_LOW) {
args.rval().setNumber(-floor(-d));
return true;
}
if (d == 0.0) {
args.rval().setInt32(0);
return true;
}
}
if (args[0].isString()) {
JSString* str = args[0].toString();
if (str->hasIndexValue()) {
args.rval().setNumber(str->getIndexValue());
return true;
}
}
}
// Step 1.
RootedString inputString(cx, ToString<CanGC>(cx, args[0]));
if (!inputString) {
return false;
}
// Step 6.
int32_t radix = 0;
if (args.hasDefined(1)) {
if (!ToInt32(cx, args[1], &radix)) {
return false;
}
}
// Steps 2-5, 7-16.
return NumberParseInt(cx, inputString, radix, args.rval());
}
static constexpr JSFunctionSpec number_functions[] = {
JS_SELF_HOSTED_FN("isNaN", "Global_isNaN", 1, JSPROP_RESOLVING),
JS_SELF_HOSTED_FN("isFinite", "Global_isFinite", 1, JSPROP_RESOLVING),
JS_FS_END,
};
const JSClass NumberObject::class_ = {
"Number",
JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_HAS_CACHED_PROTO(JSProto_Number),
JS_NULL_CLASS_OPS,
&NumberObject::classSpec_,
};
static bool Number(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() > 0) {
// BigInt proposal section 6.2, steps 2a-c.
if (!ToNumeric(cx, args[0])) {
return false;
}
if (args[0].isBigInt()) {
args[0].setNumber(BigInt::numberValue(args[0].toBigInt()));
}
MOZ_ASSERT(args[0].isNumber());
}
if (!args.isConstructing()) {
if (args.length() > 0) {
args.rval().set(args[0]);
} else {
args.rval().setInt32(0);
}
return true;
}
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_Number, &proto)) {
return false;
}
double d = args.length() > 0 ? args[0].toNumber() : 0;
JSObject* obj = NumberObject::create(cx, d, proto);
if (!obj) {
return false;
}
args.rval().setObject(*obj);
return true;
}
// ES2020 draft rev e08b018785606bc6465a0456a79604b149007932
// 20.1.3 Properties of the Number Prototype Object, thisNumberValue.
MOZ_ALWAYS_INLINE
static bool ThisNumberValue(JSContext* cx, const CallArgs& args,
const char* methodName, double* number) {
HandleValue thisv = args.thisv();
// Step 1.
if (thisv.isNumber()) {
*number = thisv.toNumber();
return true;
}
// Steps 2-3.
auto* obj = UnwrapAndTypeCheckThis<NumberObject>(cx, args, methodName);
if (!obj) {
return false;
}
*number = obj->unbox();
return true;
}
// On-off helper function for the self-hosted Number_toLocaleString method.
// This only exists to produce an error message with the right method name.
bool js::ThisNumberValueForToLocaleString(JSContext* cx, unsigned argc,
Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
double d;
if (!ThisNumberValue(cx, args, "toLocaleString", &d)) {
return false;
}
args.rval().setNumber(d);
return true;
}
static bool num_toSource(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
double d;
if (!ThisNumberValue(cx, args, "toSource", &d)) {
return false;
}
JSStringBuilder sb(cx);
if (!sb.append("(new Number(") ||
!NumberValueToStringBuilder(NumberValue(d), sb) || !sb.append("))")) {
return false;
}
JSString* str = sb.finishString();
if (!str) {
return false;
}
args.rval().setString(str);
return true;
}
// Subtract one from DTOSTR_STANDARD_BUFFER_SIZE to exclude the null-character.
static_assert(
double_conversion::DoubleToStringConverter::kMaxCharsEcmaScriptShortest ==
DTOSTR_STANDARD_BUFFER_SIZE - 1,
"double_conversion and dtoa both agree how large the longest string "
"can be");
static_assert(DTOSTR_STANDARD_BUFFER_SIZE <= JS::MaximumNumberToStringLength,
"MaximumNumberToStringLength is large enough to hold the longest "
"string produced by a conversion");
MOZ_ALWAYS_INLINE
static JSLinearString* LookupInt32ToString(JSContext* cx, int32_t si) {
if (StaticStrings::hasInt(si)) {
return cx->staticStrings().getInt(si);
}
return cx->realm()->dtoaCache.lookup(10, si);
}
template <AllowGC allowGC>
JSLinearString* js::Int32ToString(JSContext* cx, int32_t si) {
return js::Int32ToStringWithHeap<allowGC>(cx, si, gc::Heap::Default);
}
template JSLinearString* js::Int32ToString<CanGC>(JSContext* cx, int32_t si);
template JSLinearString* js::Int32ToString<NoGC>(JSContext* cx, int32_t si);
template <AllowGC allowGC>
JSLinearString* js::Int32ToStringWithHeap(JSContext* cx, int32_t si,
gc::Heap heap) {
if (JSLinearString* str = LookupInt32ToString(cx, si)) {
return str;
}
char buffer[JSFatInlineString::MAX_LENGTH_LATIN1];
auto result = std::to_chars(buffer, std::end(buffer), si, 10);
MOZ_ASSERT(result.ec == std::errc());
size_t length = result.ptr - buffer;
const auto& latin1Chars =
reinterpret_cast<const JS::Latin1Char(&)[std::size(buffer)]>(buffer);
JSInlineString* str = NewInlineString<allowGC>(cx, latin1Chars, length, heap);
if (!str) {
return nullptr;
}
if (si >= 0) {
str->maybeInitializeIndexValue(si);
}
cx->realm()->dtoaCache.cache(10, si, str);
return str;
}
template JSLinearString* js::Int32ToStringWithHeap<CanGC>(JSContext* cx,
int32_t si,
gc::Heap heap);
template JSLinearString* js::Int32ToStringWithHeap<NoGC>(JSContext* cx,
int32_t si,
gc::Heap heap);
JSLinearString* js::Int32ToStringPure(JSContext* cx, int32_t si) {
AutoUnsafeCallWithABI unsafe;
return Int32ToString<NoGC>(cx, si);
}
JSAtom* js::Int32ToAtom(JSContext* cx, int32_t si) {
if (JSLinearString* str = LookupInt32ToString(cx, si)) {
return js::AtomizeString(cx, str);
}
Int32ToCStringBuf cbuf;
auto result = std::to_chars(cbuf.sbuf, std::end(cbuf.sbuf), si, 10);
MOZ_ASSERT(result.ec == std::errc());
Maybe<uint32_t> indexValue;
if (si >= 0) {
indexValue.emplace(si);
}
size_t length = result.ptr - cbuf.sbuf;
JSAtom* atom = Atomize(cx, cbuf.sbuf, length, indexValue);
if (!atom) {
return nullptr;
}
cx->realm()->dtoaCache.cache(10, si, atom);
return atom;
}
frontend::TaggedParserAtomIndex js::Int32ToParserAtom(
FrontendContext* fc, frontend::ParserAtomsTable& parserAtoms, int32_t si) {
Int32ToCStringBuf cbuf;
auto result = std::to_chars(cbuf.sbuf, std::end(cbuf.sbuf), si, 10);
MOZ_ASSERT(result.ec == std::errc());
size_t length = result.ptr - cbuf.sbuf;
return parserAtoms.internAscii(fc, cbuf.sbuf, length);
}
/* Returns the number of digits written. */
template <typename T, size_t Base, size_t Length>
static size_t Int32ToCString(char (&out)[Length], T i) {
// The buffer needs to be large enough to hold the largest number, including
// the sign and the terminating null-character.
if constexpr (Base == 10) {
static_assert(std::numeric_limits<T>::digits10 + 1 + std::is_signed_v<T> <
Length);
} else {
// Compute digits16 analog to std::numeric_limits::digits10, which is
// defined as |std::numeric_limits::digits * std::log10(2)| for integer
// types.
// Note: log16(2) is 1/4.
static_assert(Base == 16);
static_assert(((std::numeric_limits<T>::digits + std::is_signed_v<T>) / 4 +
std::is_signed_v<T>) < Length);
}
// -1 to leave space for the terminating null-character.
auto result = std::to_chars(out, std::end(out) - 1, i, Base);
MOZ_ASSERT(result.ec == std::errc());
// Null-terminate the result.
*result.ptr = '\0';
return result.ptr - out;
}
/* Returns the number of digits written. */
template <typename T, size_t Base = 10>
static size_t Int32ToCString(ToCStringBuf* cbuf, T i) {
return Int32ToCString<T, Base>(cbuf->sbuf, i);
}
/* Returns the number of digits written. */
template <typename T, size_t Base = 10>
static size_t Int32ToCString(Int32ToCStringBuf* cbuf, T i) {
return Int32ToCString<T, Base>(cbuf->sbuf, i);
}
template <AllowGC allowGC>
static JSString* NumberToStringWithBase(JSContext* cx, double d, int32_t base);
static bool num_toString(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
double d;
if (!ThisNumberValue(cx, args, "toString", &d)) {
return false;
}
int32_t base = 10;
if (args.hasDefined(0)) {
double d2;
if (!ToInteger(cx, args[0], &d2)) {
return false;
}
if (d2 < 2 || d2 > 36) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_RADIX);
return false;
}
base = int32_t(d2);
}
JSString* str = NumberToStringWithBase<CanGC>(cx, d, base);
if (!str) {
return false;
}
args.rval().setString(str);
return true;
}
#if !JS_HAS_INTL_API
static bool num_toLocaleString(JSContext* cx, unsigned argc, Value* vp) {
AutoJSMethodProfilerEntry pseudoFrame(cx, "Number.prototype",
"toLocaleString");
CallArgs args = CallArgsFromVp(argc, vp);
double d;
if (!ThisNumberValue(cx, args, "toLocaleString", &d)) {
return false;
}
RootedString str(cx, NumberToStringWithBase<CanGC>(cx, d, 10));
if (!str) {
return false;
}
/*
* Create the string, move back to bytes to make string twiddling
* a bit easier and so we can insert platform charset seperators.
*/
UniqueChars numBytes = EncodeAscii(cx, str);
if (!numBytes) {
return false;
}
const char* num = numBytes.get();
if (!num) {
return false;
}
/*
* Find the first non-integer value, whether it be a letter as in
* 'Infinity', a decimal point, or an 'e' from exponential notation.
*/
const char* nint = num;
if (*nint == '-') {
nint++;
}
while (*nint >= '0' && *nint <= '9') {
nint++;
}
int digits = nint - num;
const char* end = num + digits;
if (!digits) {
args.rval().setString(str);
return true;
}
JSRuntime* rt = cx->runtime();
size_t thousandsLength = strlen(rt->thousandsSeparator);
size_t decimalLength = strlen(rt->decimalSeparator);
/* Figure out how long resulting string will be. */
int buflen = strlen(num);
if (*nint == '.') {
buflen += decimalLength - 1; /* -1 to account for existing '.' */
}
const char* numGrouping;
const char* tmpGroup;
numGrouping = tmpGroup = rt->numGrouping;
int remainder = digits;
if (*num == '-') {
remainder--;
}
while (*tmpGroup != CHAR_MAX && *tmpGroup != '\0') {
if (*tmpGroup >= remainder) {
break;
}
buflen += thousandsLength;
remainder -= *tmpGroup;