1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2
* vim: set ts=8 sts=4 et sw=4 tw=99:
3
* This Source Code Form is subject to the terms of the Mozilla Public
4
* License, v. 2.0. If a copy of the MPL was not distributed with this
5
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8
* JS number type and wrapper class.
13
#include "mozilla/FloatingPoint.h"
14
#include "mozilla/PodOperations.h"
15
#include "mozilla/RangedPtr.h"
17
#include "double-conversion.h"
21
#define _MCW_EM MCW_EM
22
#define _MCW_PC MCW_PC
35
#include "vm/GlobalObject.h"
36
#include "vm/NumericConversions.h"
37
#include "vm/StringBuffer.h"
39
#include "jsatominlines.h"
40
#include "jsstrinlines.h"
41
#include "vm/NumberObject-inl.h"
42
#include "vm/String-inl.h"
45
using namespace js::types;
47
using mozilla::PodCopy;
48
using mozilla::RangedPtr;
51
* If we're accumulating a decimal number and the number is >= 2^53, then the
52
* fast result from the loop in GetPrefixInteger may be inaccurate. Call
53
* js_strtod_harder to get the correct answer.
56
ComputeAccurateDecimalInteger(JSContext *cx, const jschar *start, const jschar *end, double *dp)
58
size_t length = end - start;
59
char *cstr = cx->pod_malloc<char>(length + 1);
63
for (size_t i = 0; i < length; i++) {
64
char c = char(start[i]);
65
JS_ASSERT(('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'));
72
*dp = js_strtod_harder(cx->runtime()->dtoaState, cstr, &estr, &err);
73
if (err == JS_DTOA_ENOMEM) {
74
JS_ReportOutOfMemory(cx);
78
if (err == JS_DTOA_ERANGE && *dp == HUGE_VAL)
79
*dp = js_PositiveInfinity;
84
class BinaryDigitReader
86
const int base; /* Base of number; must be a power of 2 */
87
int digit; /* Current digit value in radix given by base */
88
int digitMask; /* Mask to extract the next bit from digit */
89
const jschar *start; /* Pointer to the remaining digits */
90
const jschar *end; /* Pointer to first non-digit */
93
BinaryDigitReader(int base, const jschar *start, const jschar *end)
94
: base(base), digit(0), digitMask(0), start(start), end(end)
98
/* Return the next binary digit from the number, or -1 if done. */
100
if (digitMask == 0) {
105
JS_ASSERT(('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'));
106
if ('0' <= c && c <= '9')
108
else if ('a' <= c && c <= 'z')
109
digit = c - 'a' + 10;
111
digit = c - 'A' + 10;
112
digitMask = base >> 1;
115
int bit = (digit & digitMask) != 0;
122
* The fast result might also have been inaccurate for power-of-two bases. This
123
* happens if the addition in value * 2 + digit causes a round-down to an even
124
* least significant mantissa bit when the first dropped bit is a one. If any
125
* of the following digits in the number (which haven't been added in yet) are
126
* nonzero, then the correct action would have been to round up instead of
127
* down. An example occurs when reading the number 0x1000000000000081, which
128
* rounds to 0x1000000000000000 instead of 0x1000000000000100.
131
ComputeAccurateBinaryBaseInteger(const jschar *start, const jschar *end, int base)
133
BinaryDigitReader bdr(base, start, end);
135
/* Skip leading zeroes. */
138
bit = bdr.nextDigit();
141
JS_ASSERT(bit == 1); // guaranteed by GetPrefixInteger
143
/* Gather the 53 significant bits (including the leading 1). */
145
for (int j = 52; j > 0; j--) {
146
bit = bdr.nextDigit();
149
value = value * 2 + bit;
152
/* bit2 is the 54th bit (the first dropped from the mantissa). */
153
int bit2 = bdr.nextDigit();
156
int sticky = 0; /* sticky is 1 if any bit beyond the 54th is 1 */
159
while ((bit3 = bdr.nextDigit()) >= 0) {
163
value += bit2 & (bit | sticky);
171
js::ParseDecimalNumber(const JS::TwoByteChars chars)
173
MOZ_ASSERT(chars.length() > 0);
175
RangedPtr<jschar> s = chars.start(), end = chars.end();
178
MOZ_ASSERT('0' <= c && c <= '9');
179
uint8_t digit = c - '0';
180
uint64_t next = dec * 10 + digit;
181
MOZ_ASSERT(next < DOUBLE_INTEGRAL_PRECISION_LIMIT,
182
"next value won't be an integrally-precise double");
185
return static_cast<double>(dec);
189
js::GetPrefixInteger(JSContext *cx, const jschar *start, const jschar *end, int base,
190
const jschar **endp, double *dp)
192
JS_ASSERT(start <= end);
193
JS_ASSERT(2 <= base && base <= 36);
195
const jschar *s = start;
197
for (; s < end; s++) {
200
if ('0' <= c && c <= '9')
202
else if ('a' <= c && c <= 'z')
203
digit = c - 'a' + 10;
204
else if ('A' <= c && c <= 'Z')
205
digit = c - 'A' + 10;
210
d = d * base + digit;
216
/* If we haven't reached the limit of integer precision, we're done. */
217
if (d < DOUBLE_INTEGRAL_PRECISION_LIMIT)
221
* Otherwise compute the correct integer from the prefix of valid digits
222
* if we're computing for base ten or a power of two. Don't worry about
223
* other bases; see 15.1.2.2 step 13.
226
return ComputeAccurateDecimalInteger(cx, start, s, dp);
227
if ((base & (base - 1)) == 0)
228
*dp = ComputeAccurateBinaryBaseInteger(start, s, base);
234
num_isNaN(JSContext *cx, unsigned argc, Value *vp)
237
vp->setBoolean(true);
241
if (!ToNumber(cx, vp[2], &x))
243
vp->setBoolean(mozilla::IsNaN(x));
248
num_isFinite(JSContext *cx, unsigned argc, Value *vp)
251
vp->setBoolean(false);
255
if (!ToNumber(cx, vp[2], &x))
257
vp->setBoolean(mozilla::IsFinite(x));
262
num_parseFloat(JSContext *cx, unsigned argc, Value *vp)
264
CallArgs args = CallArgsFromVp(argc, vp);
266
if (args.length() == 0) {
267
args.rval().setDouble(js_NaN);
270
JSString *str = ToString<CanGC>(cx, args.handleAt(0));
273
const jschar *bp = str->getChars(cx);
276
const jschar *end = bp + str->length();
279
if (!js_strtod(cx, bp, end, &ep, &d))
282
args.rval().setDouble(js_NaN);
285
args.rval().setDouble(d);
291
js::num_parseInt(JSContext *cx, unsigned argc, Value *vp)
293
CallArgs args = CallArgsFromVp(argc, vp);
295
/* Fast paths and exceptional cases. */
296
if (args.length() == 0) {
297
args.rval().setDouble(js_NaN);
301
if (args.length() == 1 ||
302
(args[1].isInt32() && (args[1].toInt32() == 0 || args[1].toInt32() == 10))) {
303
if (args[0].isInt32()) {
304
args.rval().set(args[0]);
309
* Step 1 is |inputString = ToString(string)|. When string >=
310
* 1e21, ToString(string) is in the form "NeM". 'e' marks the end of
311
* the word, which would mean the result of parseInt(string) should be |N|.
313
* To preserve this behaviour, we can't use the fast-path when string >
314
* 1e21, or else the result would be |NeM|.
316
* The same goes for values smaller than 1.0e-6, because the string would be in
317
* the form of "Ne-M".
319
if (args[0].isDouble()) {
320
double d = args[0].toDouble();
321
if (1.0e-6 < d && d < 1.0e21) {
322
args.rval().setNumber(floor(d));
325
if (-1.0e21 < d && d < -1.0e-6) {
326
args.rval().setNumber(-floor(-d));
330
args.rval().setInt32(0);
337
RootedString inputString(cx, ToString<CanGC>(cx, args.handleAt(0)));
340
args[0].setString(inputString);
343
bool stripPrefix = true;
345
if (!args.hasDefined(1)) {
348
if (!ToInt32(cx, args[1], &radix))
353
if (radix < 2 || radix > 36) {
354
args.rval().setDouble(js_NaN);
366
const jschar *ws = inputString->getChars(cx);
369
end = ws + inputString->length();
370
s = SkipSpace(ws, end);
373
MOZ_ASSERT(s <= end);
377
bool negative = (s != end && s[0] == '-');
380
if (s != end && (s[0] == '-' || s[0] == '+'))
385
if (end - s >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
392
const jschar *actualEnd;
394
if (!GetPrefixInteger(cx, s, end, radix, &actualEnd, &number))
397
args.rval().setNumber(js_NaN);
399
args.rval().setNumber(negative ? -number : number);
403
static const JSFunctionSpec number_functions[] = {
404
JS_FN(js_isNaN_str, num_isNaN, 1,0),
405
JS_FN(js_isFinite_str, num_isFinite, 1,0),
406
JS_FN(js_parseFloat_str, num_parseFloat, 1,0),
407
JS_FN(js_parseInt_str, num_parseInt, 2,0),
411
Class NumberObject::class_ = {
413
JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_HAS_CACHED_PROTO(JSProto_Number),
414
JS_PropertyStub, /* addProperty */
415
JS_DeletePropertyStub, /* delProperty */
416
JS_PropertyStub, /* getProperty */
417
JS_StrictPropertyStub, /* setProperty */
424
Number(JSContext *cx, unsigned argc, Value *vp)
426
/* Sample JS_CALLEE before clobbering. */
427
bool isConstructing = IsConstructing(vp);
430
if (!ToNumber(cx, &vp[2]))
440
JSObject *obj = NumberObject::create(cx, vp[0].toNumber());
447
JS_ALWAYS_INLINE bool
448
IsNumber(const Value &v)
450
return v.isNumber() || (v.isObject() && v.toObject().is<NumberObject>());
454
Extract(const Value &v)
458
return v.toObject().as<NumberObject>().unbox();
462
JS_ALWAYS_INLINE bool
463
num_toSource_impl(JSContext *cx, CallArgs args)
465
double d = Extract(args.thisv());
468
if (!sb.append("(new Number(") ||
469
!NumberValueToStringBuffer(cx, NumberValue(d), sb) ||
475
JSString *str = sb.finishString();
478
args.rval().setString(str);
483
num_toSource(JSContext *cx, unsigned argc, Value *vp)
485
CallArgs args = CallArgsFromVp(argc, vp);
486
return CallNonGenericMethod<IsNumber, num_toSource_impl>(cx, args);
490
ToCStringBuf::ToCStringBuf() :dbuf(NULL)
492
JS_STATIC_ASSERT(sbufSize >= DTOSTR_STANDARD_BUFFER_SIZE);
495
ToCStringBuf::~ToCStringBuf()
501
template <AllowGC allowGC>
503
js::Int32ToString(JSContext *cx, int32_t si)
507
if (StaticStrings::hasInt(si))
508
return cx->runtime()->staticStrings.getInt(si);
512
JS_ASSERT_IF(si == INT32_MIN, ui == uint32_t(INT32_MAX) + 1);
515
JSCompartment *c = cx->compartment();
516
if (JSFlatString *str = c->dtoaCache.lookup(10, si))
519
JSShortString *str = js_NewGCShortString<allowGC>(cx);
523
jschar buffer[JSShortString::MAX_SHORT_LENGTH + 1];
524
RangedPtr<jschar> end(buffer + JSShortString::MAX_SHORT_LENGTH,
525
buffer, JSShortString::MAX_SHORT_LENGTH + 1);
527
RangedPtr<jschar> start = BackfillIndexInCharBuffer(ui, end);
531
jschar *dst = str->init(end - start);
532
PodCopy(dst, start.get(), end - start + 1);
534
c->dtoaCache.cache(10, si, str);
538
template JSFlatString *
539
js::Int32ToString<CanGC>(JSContext *cx, int32_t si);
541
template JSFlatString *
542
js::Int32ToString<NoGC>(JSContext *cx, int32_t si);
544
/* Returns a non-NULL pointer to inside cbuf. */
546
IntToCString(ToCStringBuf *cbuf, int i, int base = 10)
548
unsigned u = (i < 0) ? -i : i;
550
RangedPtr<char> cp(cbuf->sbuf + cbuf->sbufSize - 1, cbuf->sbuf, cbuf->sbufSize);
553
/* Build the string from behind. */
556
cp = BackfillIndexInCharBuffer(u, cp);
560
unsigned newu = u / 16;
561
*--cp = "0123456789abcdef"[u - newu * 16];
566
JS_ASSERT(base >= 2 && base <= 36);
568
unsigned newu = u / base;
569
*--cp = "0123456789abcdefghijklmnopqrstuvwxyz"[u - newu * base];
580
template <AllowGC allowGC>
581
static JSString * JS_FASTCALL
582
js_NumberToStringWithBase(JSContext *cx, double d, int base);
584
JS_ALWAYS_INLINE bool
585
num_toString_impl(JSContext *cx, CallArgs args)
587
JS_ASSERT(IsNumber(args.thisv()));
589
double d = Extract(args.thisv());
592
if (args.hasDefined(0)) {
594
if (!ToInteger(cx, args[0], &d2))
597
if (d2 < 2 || d2 > 36) {
598
JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_RADIX);
604
JSString *str = js_NumberToStringWithBase<CanGC>(cx, d, base);
606
JS_ReportOutOfMemory(cx);
609
args.rval().setString(str);
614
num_toString(JSContext *cx, unsigned argc, Value *vp)
616
CallArgs args = CallArgsFromVp(argc, vp);
617
return CallNonGenericMethod<IsNumber, num_toString_impl>(cx, args);
621
JS_ALWAYS_INLINE bool
622
num_toLocaleString_impl(JSContext *cx, CallArgs args)
624
JS_ASSERT(IsNumber(args.thisv()));
626
double d = Extract(args.thisv());
628
Rooted<JSString*> str(cx, js_NumberToStringWithBase<CanGC>(cx, d, 10));
630
JS_ReportOutOfMemory(cx);
635
* Create the string, move back to bytes to make string twiddling
636
* a bit easier and so we can insert platform charset seperators.
638
JSAutoByteString numBytes(cx, str);
641
const char *num = numBytes.ptr();
646
* Find the first non-integer value, whether it be a letter as in
647
* 'Infinity', a decimal point, or an 'e' from exponential notation.
649
const char *nint = num;
652
while (*nint >= '0' && *nint <= '9')
654
int digits = nint - num;
655
const char *end = num + digits;
657
args.rval().setString(str);
661
JSRuntime *rt = cx->runtime();
662
size_t thousandsLength = strlen(rt->thousandsSeparator);
663
size_t decimalLength = strlen(rt->decimalSeparator);
665
/* Figure out how long resulting string will be. */
666
int buflen = strlen(num);
668
buflen += decimalLength - 1; /* -1 to account for existing '.' */
670
const char *numGrouping;
671
const char *tmpGroup;
672
numGrouping = tmpGroup = rt->numGrouping;
673
int remainder = digits;
677
while (*tmpGroup != CHAR_MAX && *tmpGroup != '\0') {
678
if (*tmpGroup >= remainder)
680
buflen += thousandsLength;
681
remainder -= *tmpGroup;
686
if (*tmpGroup == '\0' && *numGrouping != '\0') {
687
nrepeat = (remainder - 1) / tmpGroup[-1];
688
buflen += thousandsLength * nrepeat;
689
remainder -= nrepeat * tmpGroup[-1];
695
char *buf = cx->pod_malloc<char>(buflen + 1);
700
const char *tmpSrc = num;
702
while (*tmpSrc == '-' || remainder--) {
703
JS_ASSERT(tmpDest - buf < buflen);
704
*tmpDest++ = *tmpSrc++;
706
while (tmpSrc < end) {
707
JS_ASSERT(tmpDest - buf + ptrdiff_t(thousandsLength) <= buflen);
708
strcpy(tmpDest, rt->thousandsSeparator);
709
tmpDest += thousandsLength;
710
JS_ASSERT(tmpDest - buf + *tmpGroup <= buflen);
711
js_memcpy(tmpDest, tmpSrc, *tmpGroup);
712
tmpDest += *tmpGroup;
719
JS_ASSERT(tmpDest - buf + ptrdiff_t(decimalLength) <= buflen);
720
strcpy(tmpDest, rt->decimalSeparator);
721
tmpDest += decimalLength;
722
JS_ASSERT(tmpDest - buf + ptrdiff_t(strlen(nint + 1)) <= buflen);
723
strcpy(tmpDest, nint + 1);
725
JS_ASSERT(tmpDest - buf + ptrdiff_t(strlen(nint)) <= buflen);
726
strcpy(tmpDest, nint);
729
if (cx->runtime()->localeCallbacks && cx->runtime()->localeCallbacks->localeToUnicode) {
730
Rooted<Value> v(cx, StringValue(str));
731
bool ok = !!cx->runtime()->localeCallbacks->localeToUnicode(cx, buf, &v);
738
str = js_NewStringCopyN<CanGC>(cx, buf, buflen);
743
args.rval().setString(str);
748
num_toLocaleString(JSContext *cx, unsigned argc, Value *vp)
750
CallArgs args = CallArgsFromVp(argc, vp);
751
return CallNonGenericMethod<IsNumber, num_toLocaleString_impl>(cx, args);
755
JS_ALWAYS_INLINE bool
756
num_valueOf_impl(JSContext *cx, CallArgs args)
758
JS_ASSERT(IsNumber(args.thisv()));
759
args.rval().setNumber(Extract(args.thisv()));
764
js_num_valueOf(JSContext *cx, unsigned argc, Value *vp)
766
CallArgs args = CallArgsFromVp(argc, vp);
767
return CallNonGenericMethod<IsNumber, num_valueOf_impl>(cx, args);
770
const unsigned MAX_PRECISION = 100;
773
ComputePrecisionInRange(JSContext *cx, int minPrecision, int maxPrecision, const Value &v,
777
if (!ToInteger(cx, v, &prec))
779
if (minPrecision <= prec && prec <= maxPrecision) {
780
*precision = int(prec);
785
if (char *numStr = NumberToCString(cx, &cbuf, prec, 10))
786
JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_PRECISION_RANGE, numStr);
791
DToStrResult(JSContext *cx, double d, JSDToStrMode mode, int precision, CallArgs args)
793
char buf[DTOSTR_VARIABLE_BUFFER_SIZE(MAX_PRECISION + 1)];
794
char *numStr = js_dtostr(cx->runtime()->dtoaState, buf, sizeof buf, mode, precision, d);
796
JS_ReportOutOfMemory(cx);
799
JSString *str = js_NewStringCopyZ<CanGC>(cx, numStr);
802
args.rval().setString(str);
807
* In the following three implementations, we allow a larger range of precision
808
* than ECMA requires; this is permitted by ECMA-262.
810
JS_ALWAYS_INLINE bool
811
num_toFixed_impl(JSContext *cx, CallArgs args)
813
JS_ASSERT(IsNumber(args.thisv()));
816
if (args.length() == 0) {
819
if (!ComputePrecisionInRange(cx, -20, MAX_PRECISION, args[0], &precision))
823
return DToStrResult(cx, Extract(args.thisv()), DTOSTR_FIXED, precision, args);
827
num_toFixed(JSContext *cx, unsigned argc, Value *vp)
829
CallArgs args = CallArgsFromVp(argc, vp);
830
return CallNonGenericMethod<IsNumber, num_toFixed_impl>(cx, args);
833
JS_ALWAYS_INLINE bool
834
num_toExponential_impl(JSContext *cx, CallArgs args)
836
JS_ASSERT(IsNumber(args.thisv()));
840
if (args.length() == 0) {
841
mode = DTOSTR_STANDARD_EXPONENTIAL;
844
mode = DTOSTR_EXPONENTIAL;
845
if (!ComputePrecisionInRange(cx, 0, MAX_PRECISION, args[0], &precision))
849
return DToStrResult(cx, Extract(args.thisv()), mode, precision + 1, args);
853
num_toExponential(JSContext *cx, unsigned argc, Value *vp)
855
CallArgs args = CallArgsFromVp(argc, vp);
856
return CallNonGenericMethod<IsNumber, num_toExponential_impl>(cx, args);
859
JS_ALWAYS_INLINE bool
860
num_toPrecision_impl(JSContext *cx, CallArgs args)
862
JS_ASSERT(IsNumber(args.thisv()));
864
double d = Extract(args.thisv());
866
if (!args.hasDefined(0)) {
867
JSString *str = js_NumberToStringWithBase<CanGC>(cx, d, 10);
869
JS_ReportOutOfMemory(cx);
872
args.rval().setString(str);
878
if (args.length() == 0) {
879
mode = DTOSTR_STANDARD;
882
mode = DTOSTR_PRECISION;
883
if (!ComputePrecisionInRange(cx, 1, MAX_PRECISION, args[0], &precision))
887
return DToStrResult(cx, d, mode, precision, args);
891
num_toPrecision(JSContext *cx, unsigned argc, Value *vp)
893
CallArgs args = CallArgsFromVp(argc, vp);
894
return CallNonGenericMethod<IsNumber, num_toPrecision_impl>(cx, args);
897
static const JSFunctionSpec number_methods[] = {
899
JS_FN(js_toSource_str, num_toSource, 0, 0),
901
JS_FN(js_toString_str, num_toString, 1, 0),
903
{js_toLocaleString_str, {NULL, NULL}, 0,0, "Number_toLocaleString"},
905
JS_FN(js_toLocaleString_str, num_toLocaleString, 0,0),
907
JS_FN(js_valueOf_str, js_num_valueOf, 0, 0),
908
JS_FN("toFixed", num_toFixed, 1, 0),
909
JS_FN("toExponential", num_toExponential, 1, 0),
910
JS_FN("toPrecision", num_toPrecision, 1, 0),
915
// ES6 draft ES6 15.7.3.10
917
Number_isNaN(JSContext *cx, unsigned argc, Value *vp)
919
CallArgs args = CallArgsFromVp(argc, vp);
920
if (args.length() < 1 || !args[0].isDouble()) {
921
args.rval().setBoolean(false);
924
args.rval().setBoolean(mozilla::IsNaN(args[0].toDouble()));
928
// ES6 draft ES6 15.7.3.11
930
Number_isFinite(JSContext *cx, unsigned argc, Value *vp)
932
CallArgs args = CallArgsFromVp(argc, vp);
933
if (args.length() < 1 || !args[0].isNumber()) {
934
args.rval().setBoolean(false);
937
args.rval().setBoolean(args[0].isInt32() ||
938
mozilla::IsFinite(args[0].toDouble()));
942
// ES6 draft ES6 15.7.3.12
944
Number_isInteger(JSContext *cx, unsigned argc, Value *vp)
946
CallArgs args = CallArgsFromVp(argc, vp);
947
if (args.length() < 1 || !args[0].isNumber()) {
948
args.rval().setBoolean(false);
952
args.rval().setBoolean(val.isInt32() ||
953
(mozilla::IsFinite(val.toDouble()) &&
954
ToInteger(val.toDouble()) == val.toDouble()));
958
// ES6 drafult ES6 15.7.3.13
960
Number_toInteger(JSContext *cx, unsigned argc, Value *vp)
962
CallArgs args = CallArgsFromVp(argc, vp);
963
if (args.length() < 1) {
964
args.rval().setInt32(0);
968
if (!ToInteger(cx, args[0], &asint))
970
args.rval().setNumber(asint);
975
static const JSFunctionSpec number_static_methods[] = {
976
JS_FN("isFinite", Number_isFinite, 1, 0),
977
JS_FN("isInteger", Number_isInteger, 1, 0),
978
JS_FN("isNaN", Number_isNaN, 1, 0),
979
JS_FN("toInteger", Number_toInteger, 1, 0),
984
/* NB: Keep this in synch with number_constants[]. */
987
NC_POSITIVE_INFINITY,
988
NC_NEGATIVE_INFINITY,
995
* Some to most C compilers forbid spelling these at compile time, or barf
996
* if you try, so all but MAX_VALUE are set up by InitRuntimeNumberState
997
* using union jsdpun.
999
static JSConstDoubleSpec number_constants[] = {
1000
{0, "NaN", 0,{0,0,0}},
1001
{0, "POSITIVE_INFINITY", 0,{0,0,0}},
1002
{0, "NEGATIVE_INFINITY", 0,{0,0,0}},
1003
{1.7976931348623157E+308, "MAX_VALUE", 0,{0,0,0}},
1004
{0, "MIN_VALUE", 0,{0,0,0}},
1009
double js_PositiveInfinity;
1010
double js_NegativeInfinity;
1012
#if (defined __GNUC__ && defined __i386__) || \
1013
(defined __SUNPRO_CC && defined __i386)
1016
* Set the exception mask to mask all exceptions and set the FPU precision
1017
* to 53 bit mantissa (64 bit doubles).
1019
inline void FIX_FPU() {
1021
asm("fstcw %0" : "=m" (control) : );
1022
control &= ~0x300; // Lower bits 8 and 9 (precision control).
1023
control |= 0x2f3; // Raise bits 0-5 (exception masks) and 9 (64-bit precision).
1024
asm("fldcw %0" : : "m" (control) );
1029
#define FIX_FPU() ((void)0)
1034
js::InitRuntimeNumberState(JSRuntime *rt)
1041
* Our NaN must be one particular canonical value, because we rely on NaN
1042
* encoding for our value representation. See Value.h.
1044
d = mozilla::SpecificNaN(0, 0x8000000000000ULL);
1045
number_constants[NC_NaN].dval = js_NaN = d;
1046
rt->NaNValue.setDouble(d);
1048
d = mozilla::PositiveInfinity();
1049
number_constants[NC_POSITIVE_INFINITY].dval = js_PositiveInfinity = d;
1050
rt->positiveInfinityValue.setDouble(d);
1052
d = mozilla::NegativeInfinity();
1053
number_constants[NC_NEGATIVE_INFINITY].dval = js_NegativeInfinity = d;
1054
rt->negativeInfinityValue.setDouble(d);
1056
number_constants[NC_MIN_VALUE].dval = mozilla::MinDoubleValue();
1058
// XXX If ENABLE_INTL_API becomes true all the time at some point,
1059
// js::InitRuntimeNumberState is no longer fallible, and we should
1060
// change its return type.
1061
#if !ENABLE_INTL_API
1062
/* Copy locale-specific separators into the runtime strings. */
1063
const char *thousandsSeparator, *decimalPoint, *grouping;
1064
#ifdef HAVE_LOCALECONV
1065
struct lconv *locale = localeconv();
1066
thousandsSeparator = locale->thousands_sep;
1067
decimalPoint = locale->decimal_point;
1068
grouping = locale->grouping;
1070
thousandsSeparator = getenv("LOCALE_THOUSANDS_SEP");
1071
decimalPoint = getenv("LOCALE_DECIMAL_POINT");
1072
grouping = getenv("LOCALE_GROUPING");
1074
if (!thousandsSeparator)
1075
thousandsSeparator = "'";
1082
* We use single malloc to get the memory for all separator and grouping
1085
size_t thousandsSeparatorSize = strlen(thousandsSeparator) + 1;
1086
size_t decimalPointSize = strlen(decimalPoint) + 1;
1087
size_t groupingSize = strlen(grouping) + 1;
1089
char *storage = js_pod_malloc<char>(thousandsSeparatorSize +
1095
js_memcpy(storage, thousandsSeparator, thousandsSeparatorSize);
1096
rt->thousandsSeparator = storage;
1097
storage += thousandsSeparatorSize;
1099
js_memcpy(storage, decimalPoint, decimalPointSize);
1100
rt->decimalSeparator = storage;
1101
storage += decimalPointSize;
1103
js_memcpy(storage, grouping, groupingSize);
1104
rt->numGrouping = grouping;
1109
#if !ENABLE_INTL_API
1111
js::FinishRuntimeNumberState(JSRuntime *rt)
1114
* The free also releases the memory for decimalSeparator and numGrouping
1117
char *storage = const_cast<char *>(rt->thousandsSeparator);
1123
js_InitNumberClass(JSContext *cx, HandleObject obj)
1125
JS_ASSERT(obj->isNative());
1127
/* XXX must do at least once per new thread, so do it per JSContext... */
1130
Rooted<GlobalObject*> global(cx, &obj->as<GlobalObject>());
1132
RootedObject numberProto(cx, global->createBlankPrototype(cx, &NumberObject::class_));
1135
numberProto->as<NumberObject>().setPrimitiveValue(0);
1137
RootedFunction ctor(cx);
1138
ctor = global->createConstructor(cx, Number, cx->names().Number, 1);
1142
if (!LinkConstructorAndPrototype(cx, ctor, numberProto))
1145
/* Add numeric constants (MAX_VALUE, NaN, &c.) to the Number constructor. */
1146
if (!JS_DefineConstDoubles(cx, ctor, number_constants))
1149
if (!DefinePropertiesAndBrand(cx, ctor, NULL, number_static_methods))
1152
if (!DefinePropertiesAndBrand(cx, numberProto, NULL, number_methods))
1155
if (!JS_DefineFunctions(cx, global, number_functions))
1158
RootedValue valueNaN(cx, cx->runtime()->NaNValue);
1159
RootedValue valueInfinity(cx, cx->runtime()->positiveInfinityValue);
1161
/* ES5 15.1.1.1, 15.1.1.2 */
1162
if (!DefineNativeProperty(cx, global, cx->names().NaN, valueNaN,
1163
JS_PropertyStub, JS_StrictPropertyStub,
1164
JSPROP_PERMANENT | JSPROP_READONLY, 0, 0) ||
1165
!DefineNativeProperty(cx, global, cx->names().Infinity, valueInfinity,
1166
JS_PropertyStub, JS_StrictPropertyStub,
1167
JSPROP_PERMANENT | JSPROP_READONLY, 0, 0))
1172
if (!DefineConstructorAndPrototype(cx, global, JSProto_Number, ctor, numberProto))
1179
FracNumberToCString(JSContext *cx, ToCStringBuf *cbuf, double d, int base = 10)
1184
JS_ASSERT(!mozilla::DoubleIsInt32(d, &_));
1191
* This is V8's implementation of the algorithm described in the
1194
* Printing floating-point numbers quickly and accurately with integers.
1195
* Florian Loitsch, PLDI 2010.
1197
const double_conversion::DoubleToStringConverter &converter
1198
= double_conversion::DoubleToStringConverter::EcmaScriptConverter();
1199
double_conversion::StringBuilder builder(cbuf->sbuf, cbuf->sbufSize);
1200
converter.ToShortest(d, &builder);
1201
numStr = builder.Finalize();
1203
numStr = cbuf->dbuf = js_dtobasestr(cx->runtime()->dtoaState, base, d);
1209
js::NumberToCString(JSContext *cx, ToCStringBuf *cbuf, double d, int base/* = 10*/)
1212
return mozilla::DoubleIsInt32(d, &i)
1213
? IntToCString(cbuf, i, base)
1214
: FracNumberToCString(cx, cbuf, d, base);
1217
template <AllowGC allowGC>
1218
static JSString * JS_FASTCALL
1219
js_NumberToStringWithBase(JSContext *cx, double d, int base)
1225
* Caller is responsible for error reporting. When called from trace,
1226
* returning NULL here will cause us to fall of trace and then retry
1227
* from the interpreter (which will report the error).
1229
if (base < 2 || base > 36)
1232
JSCompartment *c = cx->compartment();
1235
if (mozilla::DoubleIsInt32(d, &i)) {
1236
if (base == 10 && StaticStrings::hasInt(i))
1237
return cx->runtime()->staticStrings.getInt(i);
1238
if (unsigned(i) < unsigned(base)) {
1240
return cx->runtime()->staticStrings.getInt(i);
1241
jschar c = 'a' + i - 10;
1242
JS_ASSERT(StaticStrings::hasUnit(c));
1243
return cx->runtime()->staticStrings.getUnit(c);
1246
if (JSFlatString *str = c->dtoaCache.lookup(base, d))
1249
numStr = IntToCString(&cbuf, i, base);
1250
JS_ASSERT(!cbuf.dbuf && numStr >= cbuf.sbuf && numStr < cbuf.sbuf + cbuf.sbufSize);
1252
if (JSFlatString *str = c->dtoaCache.lookup(base, d))
1255
numStr = FracNumberToCString(cx, &cbuf, d, base);
1257
JS_ReportOutOfMemory(cx);
1260
JS_ASSERT_IF(base == 10,
1261
!cbuf.dbuf && numStr >= cbuf.sbuf && numStr < cbuf.sbuf + cbuf.sbufSize);
1262
JS_ASSERT_IF(base != 10,
1263
cbuf.dbuf && cbuf.dbuf == numStr);
1266
JSFlatString *s = js_NewStringCopyZ<allowGC>(cx, numStr);
1267
c->dtoaCache.cache(base, d, s);
1271
template <AllowGC allowGC>
1273
js_NumberToString(JSContext *cx, double d)
1275
return js_NumberToStringWithBase<allowGC>(cx, d, 10);
1279
js_NumberToString<CanGC>(JSContext *cx, double d);
1282
js_NumberToString<NoGC>(JSContext *cx, double d);
1285
js::NumberToString(JSContext *cx, double d)
1287
if (JSString *str = js_NumberToStringWithBase<CanGC>(cx, d, 10))
1288
return &str->asFlat();
1293
js::IndexToString(JSContext *cx, uint32_t index)
1295
if (StaticStrings::hasUint(index))
1296
return cx->runtime()->staticStrings.getUint(index);
1298
JSCompartment *c = cx->compartment();
1299
if (JSFlatString *str = c->dtoaCache.lookup(10, index))
1302
JSShortString *str = js_NewGCShortString<CanGC>(cx);
1306
jschar buffer[JSShortString::MAX_SHORT_LENGTH + 1];
1307
RangedPtr<jschar> end(buffer + JSShortString::MAX_SHORT_LENGTH,
1308
buffer, JSShortString::MAX_SHORT_LENGTH + 1);
1310
RangedPtr<jschar> start = BackfillIndexInCharBuffer(index, end);
1312
jschar *dst = str->init(end - start);
1313
PodCopy(dst, start.get(), end - start + 1);
1315
c->dtoaCache.cache(10, index, str);
1320
js::NumberValueToStringBuffer(JSContext *cx, const Value &v, StringBuffer &sb)
1322
/* Convert to C-string. */
1326
cstr = IntToCString(&cbuf, v.toInt32());
1328
cstr = NumberToCString(cx, &cbuf, v.toDouble());
1330
JS_ReportOutOfMemory(cx);
1336
* Inflate to jschar string. The input C-string characters are < 127, so
1337
* even if jschars are UTF-8, all chars should map to one jschar.
1339
size_t cstrlen = strlen(cstr);
1340
JS_ASSERT(!cbuf.dbuf && cstrlen < cbuf.sbufSize);
1341
return sb.appendInflated(cstr, cstrlen);
1345
StringToNumber(JSContext *cx, JSString *str, double *result)
1347
size_t length = str->length();
1348
const jschar *chars = str->getChars(NULL);
1353
jschar c = chars[0];
1354
if ('0' <= c && c <= '9') {
1358
if (unicode::IsSpace(c)) {
1366
const jschar *end = chars + length;
1367
const jschar *bp = SkipSpace(chars, end);
1369
/* ECMA doesn't allow signed hex numbers (bug 273467). */
1370
if (end - bp >= 2 && bp[0] == '0' && (bp[1] == 'x' || bp[1] == 'X')) {
1372
* It's probably a hex number. Accept if there's at least one hex
1373
* digit after the 0x, and if no non-whitespace characters follow all
1376
const jschar *endptr;
1378
if (!GetPrefixInteger(cx, bp + 2, end, 16, &endptr, &d) ||
1380
SkipSpace(endptr, end) != end)
1390
* Note that ECMA doesn't treat a string beginning with a '0' as
1391
* an octal number here. This works because all such numbers will
1392
* be interpreted as decimal by js_strtod. Also, any hex numbers
1393
* that have made it here (which can only be negative ones) will
1394
* be treated as 0 without consuming the 'x' by js_strtod.
1398
if (!js_strtod(cx, bp, end, &ep, &d) || SkipSpace(ep, end) != end) {
1406
#if defined(_MSC_VER)
1407
# pragma optimize("g", off)
1410
js::ToNumberSlow(JSContext *cx, Value v, double *out)
1414
* MSVC bizarrely miscompiles this, complaining about the first brace below
1415
* being unmatched (!). The error message points at both this opening brace
1416
* and at the corresponding SkipRoot constructor. The error seems to derive
1417
* from the presence guard-object macros on the SkipRoot class/constructor,
1418
* which seems well in the weeds for an unmatched-brace syntax error.
1419
* Otherwise the problem is inscrutable, and I haven't found a workaround.
1420
* So for now just disable it when compiling with MSVC -- not ideal, but at
1421
* least Windows debug shell builds complete again.
1425
SkipRoot skip(cx, &v);
1426
MaybeCheckStackRoots(cx);
1431
JS_ASSERT(!v.isNumber());
1432
goto skip_int_double;
1435
*out = v.toNumber();
1440
return StringToNumber(cx, v.toString(), out);
1441
if (v.isBoolean()) {
1442
if (v.toBoolean()) {
1453
if (v.isUndefined())
1456
JS_ASSERT(v.isObject());
1457
RootedValue v2(cx, v);
1458
if (!ToPrimitive(cx, JSTYPE_NUMBER, &v2))
1468
#if defined(_MSC_VER)
1469
# pragma optimize("", on)
1473
* Convert a value to an int64_t, according to the WebIDL rules for long long
1474
* conversion. Return converted value in *out on success, false on failure.
1477
js::ToInt64Slow(JSContext *cx, const Value &v, int64_t *out)
1479
JS_ASSERT(!v.isInt32());
1484
if (!ToNumberSlow(cx, v, &d))
1492
* Convert a value to an uint64_t, according to the WebIDL rules for unsigned long long
1493
* conversion. Return converted value in *out on success, false on failure.
1496
js::ToUint64Slow(JSContext *cx, const Value &v, uint64_t *out)
1498
JS_ASSERT(!v.isInt32());
1503
if (!ToNumberSlow(cx, v, &d))
1511
js::ToInt32Slow(JSContext *cx, const Value &v, int32_t *out)
1513
JS_ASSERT(!v.isInt32());
1518
if (!ToNumberSlow(cx, v, &d))
1526
js::ToUint32Slow(JSContext *cx, const Value &v, uint32_t *out)
1528
JS_ASSERT(!v.isInt32());
1533
if (!ToNumberSlow(cx, v, &d))
1541
js::ToUint16Slow(JSContext *cx, const Value &v, uint16_t *out)
1543
JS_ASSERT(!v.isInt32());
1547
} else if (!ToNumberSlow(cx, v, &d)) {
1551
if (d == 0 || !mozilla::IsFinite(d)) {
1556
uint16_t u = (uint16_t) d;
1557
if ((double)u == d) {
1563
d = floor(neg ? -d : d);
1565
unsigned m = JS_BIT(16);
1566
d = fmod(d, (double) m);
1569
*out = (uint16_t) d;
1574
js_strtod(JSContext *cx, const jschar *s, const jschar *send,
1575
const jschar **ep, double *dp)
1579
char *cstr, *istr, *estr;
1583
const jschar *s1 = SkipSpace(s, send);
1584
size_t length = send - s1;
1586
/* Use cbuf to avoid malloc */
1587
if (length >= sizeof cbuf) {
1588
cstr = (char *) cx->malloc_(length + 1);
1595
for (i = 0; i != length; i++) {
1598
cstr[i] = (char)s1[i];
1603
if ((negative = (*istr == '-')) != 0 || *istr == '+')
1605
if (*istr == 'I' && !strncmp(istr, "Infinity", 8)) {
1606
d = negative ? js_NegativeInfinity : js_PositiveInfinity;
1610
d = js_strtod_harder(cx->runtime()->dtoaState, cstr, &estr, &err);
1612
d = js_PositiveInfinity;
1613
else if (d == -HUGE_VAL)
1614
d = js_NegativeInfinity;
1620
*ep = i ? s1 + i : s;