1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
3
* ***** BEGIN LICENSE BLOCK *****
4
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
6
* The contents of this file are subject to the Mozilla Public License Version
7
* 1.1 (the "License"); you may not use this file except in compliance with
8
* the License. You may obtain a copy of the License at
9
* http://www.mozilla.org/MPL/
11
* Software distributed under the License is distributed on an "AS IS" basis,
12
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13
* for the specific language governing rights and limitations under the
16
* The Original Code is Mozilla Communicator client code, released
19
* The Initial Developer of the Original Code is
20
* Netscape Communications Corporation.
21
* Portions created by the Initial Developer are Copyright (C) 1998
22
* the Initial Developer. All Rights Reserved.
27
* Alternatively, the contents of this file may be used under the terms of
28
* either of the GNU General Public License Version 2 or later (the "GPL"),
29
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
30
* in which case the provisions of the GPL or the LGPL are applicable instead
31
* of those above. If you wish to allow use of your version of this file only
32
* under the terms of either the GPL or the LGPL, and not to allow others to
33
* use your version of this file under the terms of the MPL, indicate your
34
* decision by deleting the provisions above and replace them with the notice
35
* and other provisions required by the GPL or the LGPL. If you do not delete
36
* the provisions above, a recipient may use your version of this file under
37
* the terms of any one of the MPL, the GPL or the LGPL.
39
* ***** END LICENSE BLOCK ***** */
42
* JS number type and wrapper class.
46
#define _MCW_EM MCW_EM
47
#define _MCW_PC MCW_PC
59
#include "jsbuiltins.h"
61
#include "jsversion.h"
74
#include "jsinterpinlines.h"
75
#include "jsobjinlines.h"
76
#include "jsstrinlines.h"
80
#ifndef JS_HAVE_STDINT_H /* Native support is innocent until proven guilty. */
82
JS_STATIC_ASSERT(uint8_t(-1) == UINT8_MAX);
83
JS_STATIC_ASSERT(uint16_t(-1) == UINT16_MAX);
84
JS_STATIC_ASSERT(uint32_t(-1) == UINT32_MAX);
85
JS_STATIC_ASSERT(uint64_t(-1) == UINT64_MAX);
87
JS_STATIC_ASSERT(INT8_MAX > INT8_MIN);
88
JS_STATIC_ASSERT(uint8_t(INT8_MAX) + uint8_t(1) == uint8_t(INT8_MIN));
89
JS_STATIC_ASSERT(INT16_MAX > INT16_MIN);
90
JS_STATIC_ASSERT(uint16_t(INT16_MAX) + uint16_t(1) == uint16_t(INT16_MIN));
91
JS_STATIC_ASSERT(INT32_MAX > INT32_MIN);
92
JS_STATIC_ASSERT(uint32_t(INT32_MAX) + uint32_t(1) == uint32_t(INT32_MIN));
93
JS_STATIC_ASSERT(INT64_MAX > INT64_MIN);
94
JS_STATIC_ASSERT(uint64_t(INT64_MAX) + uint64_t(1) == uint64_t(INT64_MIN));
96
JS_STATIC_ASSERT(INTPTR_MAX > INTPTR_MIN);
97
JS_STATIC_ASSERT(uintptr_t(INTPTR_MAX) + uintptr_t(1) == uintptr_t(INTPTR_MIN));
98
JS_STATIC_ASSERT(uintptr_t(-1) == UINTPTR_MAX);
99
JS_STATIC_ASSERT(size_t(-1) == SIZE_MAX);
100
JS_STATIC_ASSERT(PTRDIFF_MAX > PTRDIFF_MIN);
101
JS_STATIC_ASSERT(ptrdiff_t(PTRDIFF_MAX) == PTRDIFF_MAX);
102
JS_STATIC_ASSERT(ptrdiff_t(PTRDIFF_MIN) == PTRDIFF_MIN);
103
JS_STATIC_ASSERT(uintptr_t(PTRDIFF_MAX) + uintptr_t(1) == uintptr_t(PTRDIFF_MIN));
105
#endif /* JS_HAVE_STDINT_H */
108
* If we're accumulating a decimal number and the number is >= 2^53, then the
109
* fast result from the loop in GetPrefixInteger may be inaccurate. Call
110
* js_strtod_harder to get the correct answer.
113
ComputeAccurateDecimalInteger(JSContext *cx, const jschar *start, const jschar *end, jsdouble *dp)
115
size_t length = end - start;
116
char *cstr = static_cast<char *>(cx->malloc_(length + 1));
120
for (size_t i = 0; i < length; i++) {
121
char c = char(start[i]);
122
JS_ASSERT(('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'));
129
*dp = js_strtod_harder(JS_THREAD_DATA(cx)->dtoaState, cstr, &estr, &err);
130
if (err == JS_DTOA_ENOMEM) {
131
JS_ReportOutOfMemory(cx);
135
if (err == JS_DTOA_ERANGE && *dp == HUGE_VAL)
136
*dp = js_PositiveInfinity;
141
class BinaryDigitReader
143
const int base; /* Base of number; must be a power of 2 */
144
int digit; /* Current digit value in radix given by base */
145
int digitMask; /* Mask to extract the next bit from digit */
146
const jschar *start; /* Pointer to the remaining digits */
147
const jschar *end; /* Pointer to first non-digit */
150
BinaryDigitReader(int base, const jschar *start, const jschar *end)
151
: base(base), digit(0), digitMask(0), start(start), end(end)
155
/* Return the next binary digit from the number, or -1 if done. */
157
if (digitMask == 0) {
162
JS_ASSERT(('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'));
163
if ('0' <= c && c <= '9')
165
else if ('a' <= c && c <= 'z')
166
digit = c - 'a' + 10;
168
digit = c - 'A' + 10;
169
digitMask = base >> 1;
172
int bit = (digit & digitMask) != 0;
179
* The fast result might also have been inaccurate for power-of-two bases. This
180
* happens if the addition in value * 2 + digit causes a round-down to an even
181
* least significant mantissa bit when the first dropped bit is a one. If any
182
* of the following digits in the number (which haven't been added in yet) are
183
* nonzero, then the correct action would have been to round up instead of
184
* down. An example occurs when reading the number 0x1000000000000081, which
185
* rounds to 0x1000000000000000 instead of 0x1000000000000100.
188
ComputeAccurateBinaryBaseInteger(JSContext *cx, const jschar *start, const jschar *end, int base)
190
BinaryDigitReader bdr(base, start, end);
192
/* Skip leading zeroes. */
195
bit = bdr.nextDigit();
198
JS_ASSERT(bit == 1); // guaranteed by GetPrefixInteger
200
/* Gather the 53 significant bits (including the leading 1). */
201
jsdouble value = 1.0;
202
for (int j = 52; j > 0; j--) {
203
bit = bdr.nextDigit();
206
value = value * 2 + bit;
209
/* bit2 is the 54th bit (the first dropped from the mantissa). */
210
int bit2 = bdr.nextDigit();
212
jsdouble factor = 2.0;
213
int sticky = 0; /* sticky is 1 if any bit beyond the 54th is 1 */
216
while ((bit3 = bdr.nextDigit()) >= 0) {
220
value += bit2 & (bit | sticky);
230
GetPrefixInteger(JSContext *cx, const jschar *start, const jschar *end, int base,
231
const jschar **endp, jsdouble *dp)
233
JS_ASSERT(start <= end);
234
JS_ASSERT(2 <= base && base <= 36);
236
const jschar *s = start;
238
for (; s < end; s++) {
241
if ('0' <= c && c <= '9')
243
else if ('a' <= c && c <= 'z')
244
digit = c - 'a' + 10;
245
else if ('A' <= c && c <= 'Z')
246
digit = c - 'A' + 10;
251
d = d * base + digit;
257
/* If we haven't reached the limit of integer precision, we're done. */
258
if (d < DOUBLE_INTEGRAL_PRECISION_LIMIT)
262
* Otherwise compute the correct integer from the prefix of valid digits
263
* if we're computing for base ten or a power of two. Don't worry about
264
* other bases; see 15.1.2.2 step 13.
267
return ComputeAccurateDecimalInteger(cx, start, s, dp);
268
if ((base & (base - 1)) == 0)
269
*dp = ComputeAccurateBinaryBaseInteger(cx, start, s, base);
277
num_isNaN(JSContext *cx, uintN argc, Value *vp)
280
vp->setBoolean(true);
284
if (!ValueToNumber(cx, vp[2], &x))
286
vp->setBoolean(JSDOUBLE_IS_NaN(x));
291
num_isFinite(JSContext *cx, uintN argc, Value *vp)
294
vp->setBoolean(false);
298
if (!ValueToNumber(cx, vp[2], &x))
300
vp->setBoolean(JSDOUBLE_IS_FINITE(x));
305
num_parseFloat(JSContext *cx, uintN argc, Value *vp)
309
const jschar *bp, *end, *ep;
312
vp->setDouble(js_NaN);
315
str = js_ValueToString(cx, vp[2]);
318
bp = str->getChars(cx);
321
end = bp + str->length();
322
if (!js_strtod(cx, bp, end, &ep, &d))
325
vp->setDouble(js_NaN);
333
static jsdouble FASTCALL
334
ParseFloat(JSContext* cx, JSString* str)
336
TraceMonitor *tm = JS_TRACE_MONITOR_ON_TRACE(cx);
338
const jschar *bp = str->getChars(cx);
343
const jschar *end = bp + str->length();
347
if (!js_strtod(cx, bp, end, &ep, &d) || ep == bp)
354
ParseIntStringHelper(JSContext *cx, const jschar *ws, const jschar *end, int maybeRadix,
355
bool stripPrefix, jsdouble *dp)
357
JS_ASSERT(maybeRadix == 0 || (2 <= maybeRadix && maybeRadix <= 36));
358
JS_ASSERT(ws <= end);
360
const jschar *s = js_SkipWhiteSpace(ws, end);
364
/* 15.1.2.2 steps 3-4. */
365
bool negative = (s != end && s[0] == '-');
367
/* 15.1.2.2 step 5. */
368
if (s != end && (s[0] == '-' || s[0] == '+'))
371
/* 15.1.2.2 step 9. */
372
int radix = maybeRadix;
374
if (end - s >= 2 && s[0] == '0' && (s[1] != 'x' && s[1] != 'X')) {
376
* Non-standard: ES5 requires that parseInt interpret leading-zero
377
* strings not starting with "0x" or "0X" as decimal (absent an
378
* explicitly specified non-zero radix), but we continue to
379
* interpret such strings as octal, as per ES3 and web practice.
387
/* 15.1.2.2 step 10. */
389
if (end - s >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
395
/* 15.1.2.2 steps 11-14. */
396
const jschar *actualEnd;
397
if (!GetPrefixInteger(cx, s, end, radix, &actualEnd, dp))
407
ParseIntDoubleHelper(jsdouble d)
409
JS_ASSERT(-1e21 < d && d < 1e21);
417
/* See ECMA 15.1.2.2. */
419
num_parseInt(JSContext *cx, uintN argc, Value *vp)
421
/* Fast paths and exceptional cases. */
423
vp->setDouble(js_NaN);
427
if (argc == 1 || (vp[3].isInt32() && (vp[3].toInt32() == 0 || vp[3].toInt32() == 10))) {
428
if (vp[2].isInt32()) {
433
* Step 1 is |inputString = ToString(string)|. When string >=
434
* 1e21, ToString(string) is in the form "NeM". 'e' marks the end of
435
* the word, which would mean the result of parseInt(string) should be |N|.
437
* To preserve this behaviour, we can't use the fast-path when string >
438
* 1e21, or else the result would be |NeM|.
440
if (vp[2].isDouble() &&
441
vp[2].toDouble() > -1.0e21 &&
442
vp[2].toDouble() < 1.0e21) {
443
vp->setDouble(ParseIntDoubleHelper(vp[2].toDouble()));
449
JSString *inputString = js_ValueToString(cx, vp[2]);
452
vp[2].setString(inputString);
454
/* 15.1.2.2 steps 6-8. */
455
bool stripPrefix = true;
458
if (!ValueToECMAInt32(cx, vp[3], &radix))
461
if (radix < 2 || radix > 36) {
462
vp->setDouble(js_NaN);
470
/* Steps 2-5, 9-14. */
471
const jschar *ws = inputString->getChars(cx);
474
const jschar *end = ws + inputString->length();
477
if (!ParseIntStringHelper(cx, ws, end, radix, stripPrefix, &number))
481
vp->setNumber(number);
486
static jsdouble FASTCALL
487
ParseInt(JSContext* cx, JSString* str)
489
TraceMonitor *tm = JS_TRACE_MONITOR_ON_TRACE(cx);
491
const jschar *start = str->getChars(cx);
496
const jschar *end = start + str->length();
499
if (!ParseIntStringHelper(cx, start, end, 0, true, &d)) {
506
static jsdouble FASTCALL
507
ParseIntDouble(JSContext* cx, jsdouble d)
509
/* Fast path - see comment in numParseInt. */
510
if (-1.0e21 < d && d < 1.0e21)
511
return ParseIntDoubleHelper(d);
513
/* Slow path - convert to a string and parse normally. */
514
JSString *inputString = js_NumberToString(cx, d);
516
TraceMonitor *tm = JS_TRACE_MONITOR_ON_TRACE(cx);
521
return ParseInt(cx, inputString);
525
const char js_Infinity_str[] = "Infinity";
526
const char js_NaN_str[] = "NaN";
527
const char js_isNaN_str[] = "isNaN";
528
const char js_isFinite_str[] = "isFinite";
529
const char js_parseFloat_str[] = "parseFloat";
530
const char js_parseInt_str[] = "parseInt";
534
JS_DEFINE_TRCINFO_2(num_parseInt,
535
(2, (static, DOUBLE_FAIL, ParseInt, CONTEXT, STRING,1, nanojit::ACCSET_NONE)),
536
(2, (static, DOUBLE_FAIL, ParseIntDouble, CONTEXT, DOUBLE,1, nanojit::ACCSET_NONE)))
538
JS_DEFINE_TRCINFO_1(num_parseFloat,
539
(2, (static, DOUBLE_FAIL, ParseFloat, CONTEXT, STRING, 1, nanojit::ACCSET_NONE)))
541
#endif /* JS_TRACER */
543
static JSFunctionSpec number_functions[] = {
544
JS_FN(js_isNaN_str, num_isNaN, 1,0),
545
JS_FN(js_isFinite_str, num_isFinite, 1,0),
546
JS_TN(js_parseFloat_str, num_parseFloat, 1,0, &num_parseFloat_trcinfo),
547
JS_TN(js_parseInt_str, num_parseInt, 2,0, &num_parseInt_trcinfo),
551
Class js_NumberClass = {
553
JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_HAS_CACHED_PROTO(JSProto_Number),
554
PropertyStub, /* addProperty */
555
PropertyStub, /* delProperty */
556
PropertyStub, /* getProperty */
557
StrictPropertyStub, /* setProperty */
564
Number(JSContext *cx, uintN argc, Value *vp)
566
/* Sample JS_CALLEE before clobbering. */
567
bool isConstructing = IsConstructing(vp);
570
if (!ValueToNumber(cx, &vp[2]))
580
JSObject *obj = NewBuiltinClassInstance(cx, &js_NumberClass);
583
obj->setPrimitiveThis(vp[0]);
590
num_toSource(JSContext *cx, uintN argc, Value *vp)
593
if (!GetPrimitiveThis(cx, vp, &d))
597
char *numStr = NumberToCString(cx, &cbuf, d);
599
JS_ReportOutOfMemory(cx);
604
JS_snprintf(buf, sizeof buf, "(new %s(%s))", js_NumberClass.name, numStr);
605
JSString *str = js_NewStringCopyZ(cx, buf);
613
ToCStringBuf::ToCStringBuf() :dbuf(NULL)
615
JS_STATIC_ASSERT(sbufSize >= DTOSTR_STANDARD_BUFFER_SIZE);
618
ToCStringBuf::~ToCStringBuf()
621
UnwantedForeground::free_(dbuf);
624
JSString * JS_FASTCALL
625
js_IntToString(JSContext *cx, int32 si)
629
if (JSAtom::hasIntStatic(si))
630
return &JSAtom::intStatic(si);
634
JS_ASSERT_IF(si == INT32_MIN, ui == uint32(INT32_MAX) + 1);
637
JSCompartment *c = cx->compartment;
638
if (JSString *str = c->dtoaCache.lookup(10, si))
641
JSShortString *str = js_NewGCShortString(cx);
645
/* +1, since MAX_LENGTH does not count the null char. */
646
JS_STATIC_ASSERT(JSShortString::MAX_LENGTH + 1 >= sizeof("-2147483648"));
648
jschar *end = str->inlineStorageBeforeInit() + JSShortString::MAX_SHORT_LENGTH;
653
jsuint newui = ui / 10, digit = ui % 10; /* optimizers are our friends */
661
str->initAtOffsetInBuffer(cp, end - cp);
663
c->dtoaCache.cache(10, si, str);
667
/* Returns a non-NULL pointer to inside cbuf. */
669
IntToCString(ToCStringBuf *cbuf, jsint i, jsint base = 10)
674
u = (i < 0) ? -i : i;
676
cp = cbuf->sbuf + cbuf->sbufSize; /* one past last buffer cell */
677
*--cp = '\0'; /* null terminate the string to be */
680
* Build the string from behind. We use multiply and subtraction
681
* instead of modulus because that's much faster.
686
jsuint newu = u / 10;
687
*--cp = (char)(u - newu * 10) + '0';
693
jsuint newu = u / 16;
694
*--cp = "0123456789abcdef"[u - newu * 16];
699
JS_ASSERT(base >= 2 && base <= 36);
701
jsuint newu = u / base;
702
*--cp = "0123456789abcdefghijklmnopqrstuvwxyz"[u - newu * base];
710
JS_ASSERT(cp >= cbuf->sbuf);
714
static JSString * JS_FASTCALL
715
js_NumberToStringWithBase(JSContext *cx, jsdouble d, jsint base);
718
num_toString(JSContext *cx, uintN argc, Value *vp)
721
if (!GetPrimitiveThis(cx, vp, &d))
725
if (argc != 0 && !vp[2].isUndefined()) {
727
if (!ToInteger(cx, vp[2], &d2))
730
if (d2 < 2 || d2 > 36) {
731
JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_RADIX);
737
JSString *str = js_NumberToStringWithBase(cx, d, base);
739
JS_ReportOutOfMemory(cx);
747
num_toLocaleString(JSContext *cx, uintN argc, Value *vp)
749
size_t thousandsLength, decimalLength;
750
const char *numGrouping, *tmpGroup;
753
const char *num, *end, *tmpSrc;
756
int digits, buflen, remainder, nrepeat;
759
* Create the string, move back to bytes to make string twiddling
760
* a bit easier and so we can insert platform charset seperators.
762
if (!num_toString(cx, 0, vp))
764
JS_ASSERT(vp->isString());
765
JSAutoByteString numBytes(cx, vp->toString());
768
num = numBytes.ptr();
773
* Find the first non-integer value, whether it be a letter as in
774
* 'Infinity', a decimal point, or an 'e' from exponential notation.
779
while (*nint >= '0' && *nint <= '9')
787
thousandsLength = strlen(rt->thousandsSeparator);
788
decimalLength = strlen(rt->decimalSeparator);
790
/* Figure out how long resulting string will be. */
791
buflen = strlen(num);
793
buflen += decimalLength - 1; /* -1 to account for existing '.' */
795
numGrouping = tmpGroup = rt->numGrouping;
800
while (*tmpGroup != CHAR_MAX && *tmpGroup != '\0') {
801
if (*tmpGroup >= remainder)
803
buflen += thousandsLength;
804
remainder -= *tmpGroup;
807
if (*tmpGroup == '\0' && *numGrouping != '\0') {
808
nrepeat = (remainder - 1) / tmpGroup[-1];
809
buflen += thousandsLength * nrepeat;
810
remainder -= nrepeat * tmpGroup[-1];
816
buf = (char *)cx->malloc_(buflen + 1);
823
while (*tmpSrc == '-' || remainder--) {
824
JS_ASSERT(tmpDest - buf < buflen);
825
*tmpDest++ = *tmpSrc++;
827
while (tmpSrc < end) {
828
JS_ASSERT(tmpDest - buf + ptrdiff_t(thousandsLength) <= buflen);
829
strcpy(tmpDest, rt->thousandsSeparator);
830
tmpDest += thousandsLength;
831
JS_ASSERT(tmpDest - buf + *tmpGroup <= buflen);
832
memcpy(tmpDest, tmpSrc, *tmpGroup);
833
tmpDest += *tmpGroup;
840
JS_ASSERT(tmpDest - buf + ptrdiff_t(decimalLength) <= buflen);
841
strcpy(tmpDest, rt->decimalSeparator);
842
tmpDest += decimalLength;
843
JS_ASSERT(tmpDest - buf + ptrdiff_t(strlen(nint + 1)) <= buflen);
844
strcpy(tmpDest, nint + 1);
846
JS_ASSERT(tmpDest - buf + ptrdiff_t(strlen(nint)) <= buflen);
847
strcpy(tmpDest, nint);
850
if (cx->localeCallbacks && cx->localeCallbacks->localeToUnicode) {
851
JSBool ok = cx->localeCallbacks->localeToUnicode(cx, buf, Jsvalify(vp));
856
str = js_NewStringCopyN(cx, buf, buflen);
866
js_num_valueOf(JSContext *cx, uintN argc, Value *vp)
869
if (!GetPrimitiveThis(cx, vp, &d))
877
#define MAX_PRECISION 100
880
num_to(JSContext *cx, JSDToStrMode zeroArgMode, JSDToStrMode oneArgMode,
881
jsint precisionMin, jsint precisionMax, jsint precisionOffset,
882
uintN argc, Value *vp)
884
/* Use MAX_PRECISION+1 because precisionOffset can be 1. */
885
char buf[DTOSTR_VARIABLE_BUFFER_SIZE(MAX_PRECISION+1)];
889
if (!GetPrimitiveThis(cx, vp, &d))
895
oneArgMode = zeroArgMode;
897
if (!ToInteger(cx, vp[2], &precision))
899
if (precision < precisionMin || precision > precisionMax) {
901
numStr = IntToCString(&cbuf, jsint(precision));
903
JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_PRECISION_RANGE, numStr);
908
numStr = js_dtostr(JS_THREAD_DATA(cx)->dtoaState, buf, sizeof buf,
909
oneArgMode, (jsint)precision + precisionOffset, d);
911
JS_ReportOutOfMemory(cx);
914
JSString *str = js_NewStringCopyZ(cx, numStr);
922
* In the following three implementations, we allow a larger range of precision
923
* than ECMA requires; this is permitted by ECMA-262.
926
num_toFixed(JSContext *cx, uintN argc, Value *vp)
928
return num_to(cx, DTOSTR_FIXED, DTOSTR_FIXED, -20, MAX_PRECISION, 0,
933
num_toExponential(JSContext *cx, uintN argc, Value *vp)
935
return num_to(cx, DTOSTR_STANDARD_EXPONENTIAL, DTOSTR_EXPONENTIAL, 0, MAX_PRECISION, 1,
940
num_toPrecision(JSContext *cx, uintN argc, Value *vp)
942
if (argc == 0 || vp[2].isUndefined())
943
return num_toString(cx, 0, vp);
944
return num_to(cx, DTOSTR_STANDARD, DTOSTR_PRECISION, 1, MAX_PRECISION, 0,
950
JS_DEFINE_TRCINFO_2(num_toString,
951
(2, (extern, STRING_RETRY, js_NumberToString, CONTEXT, THIS_DOUBLE,
952
1, nanojit::ACCSET_NONE)),
953
(3, (static, STRING_RETRY, js_NumberToStringWithBase, CONTEXT, THIS_DOUBLE, INT32,
954
1, nanojit::ACCSET_NONE)))
956
#endif /* JS_TRACER */
958
static JSFunctionSpec number_methods[] = {
960
JS_FN(js_toSource_str, num_toSource, 0, 0),
962
JS_TN(js_toString_str, num_toString, 1, 0, &num_toString_trcinfo),
963
JS_FN(js_toLocaleString_str, num_toLocaleString, 0, 0),
964
JS_FN(js_valueOf_str, js_num_valueOf, 0, 0),
965
JS_FN("toFixed", num_toFixed, 1, 0),
966
JS_FN("toExponential", num_toExponential, 1, 0),
967
JS_FN("toPrecision", num_toPrecision, 1, 0),
971
/* NB: Keep this in synch with number_constants[]. */
974
NC_POSITIVE_INFINITY,
975
NC_NEGATIVE_INFINITY,
982
* Some to most C compilers forbid spelling these at compile time, or barf
983
* if you try, so all but MAX_VALUE are set up by js_InitRuntimeNumberState
984
* using union jsdpun.
986
static JSConstDoubleSpec number_constants[] = {
987
{0, js_NaN_str, 0,{0,0,0}},
988
{0, "POSITIVE_INFINITY", 0,{0,0,0}},
989
{0, "NEGATIVE_INFINITY", 0,{0,0,0}},
990
{1.7976931348623157E+308, "MAX_VALUE", 0,{0,0,0}},
991
{0, "MIN_VALUE", 0,{0,0,0}},
996
jsdouble js_PositiveInfinity;
997
jsdouble js_NegativeInfinity;
999
#if (defined __GNUC__ && defined __i386__) || \
1000
(defined __SUNPRO_CC && defined __i386)
1003
* Set the exception mask to mask all exceptions and set the FPU precision
1004
* to 53 bit mantissa (64 bit doubles).
1006
inline void FIX_FPU() {
1008
asm("fstcw %0" : "=m" (control) : );
1009
control &= ~0x300; // Lower bits 8 and 9 (precision control).
1010
control |= 0x2f3; // Raise bits 0-5 (exception masks) and 9 (64-bit precision).
1011
asm("fldcw %0" : : "m" (control) );
1016
#define FIX_FPU() ((void)0)
1021
js_InitRuntimeNumberState(JSContext *cx)
1023
JSRuntime *rt = cx->runtime;
1028
u.s.hi = JSDOUBLE_HI32_NAN;
1029
u.s.lo = JSDOUBLE_LO32_NAN;
1030
number_constants[NC_NaN].dval = js_NaN = u.d;
1031
rt->NaNValue.setDouble(u.d);
1033
u.s.hi = JSDOUBLE_HI32_EXPMASK;
1034
u.s.lo = 0x00000000;
1035
number_constants[NC_POSITIVE_INFINITY].dval = js_PositiveInfinity = u.d;
1036
rt->positiveInfinityValue.setDouble(u.d);
1038
u.s.hi = JSDOUBLE_HI32_SIGNBIT | JSDOUBLE_HI32_EXPMASK;
1039
u.s.lo = 0x00000000;
1040
number_constants[NC_NEGATIVE_INFINITY].dval = js_NegativeInfinity = u.d;
1041
rt->negativeInfinityValue.setDouble(u.d);
1045
number_constants[NC_MIN_VALUE].dval = u.d;
1047
#ifndef HAVE_LOCALECONV
1048
const char* thousands_sep = getenv("LOCALE_THOUSANDS_SEP");
1049
const char* decimal_point = getenv("LOCALE_DECIMAL_POINT");
1050
const char* grouping = getenv("LOCALE_GROUPING");
1052
rt->thousandsSeparator =
1053
JS_strdup(cx, thousands_sep ? thousands_sep : "'");
1054
rt->decimalSeparator =
1055
JS_strdup(cx, decimal_point ? decimal_point : ".");
1057
JS_strdup(cx, grouping ? grouping : "\3\0");
1059
struct lconv *locale = localeconv();
1060
rt->thousandsSeparator =
1061
JS_strdup(cx, locale->thousands_sep ? locale->thousands_sep : "'");
1062
rt->decimalSeparator =
1063
JS_strdup(cx, locale->decimal_point ? locale->decimal_point : ".");
1065
JS_strdup(cx, locale->grouping ? locale->grouping : "\3\0");
1068
return rt->thousandsSeparator && rt->decimalSeparator && rt->numGrouping;
1072
js_FinishRuntimeNumberState(JSContext *cx)
1074
JSRuntime *rt = cx->runtime;
1076
cx->free_((void *) rt->thousandsSeparator);
1077
cx->free_((void *) rt->decimalSeparator);
1078
cx->free_((void *) rt->numGrouping);
1079
rt->thousandsSeparator = rt->decimalSeparator = rt->numGrouping = NULL;
1083
js_InitNumberClass(JSContext *cx, JSObject *obj)
1085
JSObject *proto, *ctor;
1088
/* XXX must do at least once per new thread, so do it per JSContext... */
1091
if (!JS_DefineFunctions(cx, obj, number_functions))
1094
proto = js_InitClass(cx, obj, NULL, &js_NumberClass, Number, 1,
1095
NULL, number_methods, NULL, NULL);
1096
if (!proto || !(ctor = JS_GetConstructor(cx, proto)))
1098
proto->setPrimitiveThis(Int32Value(0));
1099
if (!JS_DefineConstDoubles(cx, ctor, number_constants))
1104
if (!JS_DefineProperty(cx, obj, js_NaN_str, Jsvalify(rt->NaNValue),
1105
JS_PropertyStub, JS_StrictPropertyStub,
1106
JSPROP_PERMANENT | JSPROP_READONLY)) {
1111
if (!JS_DefineProperty(cx, obj, js_Infinity_str, Jsvalify(rt->positiveInfinityValue),
1112
JS_PropertyStub, JS_StrictPropertyStub,
1113
JSPROP_PERMANENT | JSPROP_READONLY)) {
1120
namespace internal {
1121
extern char* DoubleToCString(double v, char* buffer, int buflen);
1128
FracNumberToCString(JSContext *cx, ToCStringBuf *cbuf, jsdouble d, jsint base = 10)
1133
JS_ASSERT(!JSDOUBLE_IS_INT32(d, &_));
1140
* This is V8's implementation of the algorithm described in the
1143
* Printing floating-point numbers quickly and accurately with integers.
1144
* Florian Loitsch, PLDI 2010.
1146
* It fails on a small number of cases, whereupon we fall back to
1147
* js_dtostr() (which uses David Gay's dtoa).
1149
numStr = v8::internal::DoubleToCString(d, cbuf->sbuf, cbuf->sbufSize);
1151
numStr = js_dtostr(JS_THREAD_DATA(cx)->dtoaState, cbuf->sbuf, cbuf->sbufSize,
1152
DTOSTR_STANDARD, 0, d);
1154
numStr = cbuf->dbuf = js_dtobasestr(JS_THREAD_DATA(cx)->dtoaState, base, d);
1160
NumberToCString(JSContext *cx, ToCStringBuf *cbuf, jsdouble d, jsint base/* = 10*/)
1163
return (JSDOUBLE_IS_INT32(d, &i))
1164
? IntToCString(cbuf, i, base)
1165
: FracNumberToCString(cx, cbuf, d, base);
1170
static JSString * JS_FASTCALL
1171
js_NumberToStringWithBase(JSContext *cx, jsdouble d, jsint base)
1177
* Caller is responsible for error reporting. When called from trace,
1178
* returning NULL here will cause us to fall of trace and then retry
1179
* from the interpreter (which will report the error).
1181
if (base < 2 || base > 36)
1184
JSCompartment *c = cx->compartment;
1187
if (JSDOUBLE_IS_INT32(d, &i)) {
1188
if (base == 10 && JSAtom::hasIntStatic(i))
1189
return &JSAtom::intStatic(i);
1190
if (jsuint(i) < jsuint(base)) {
1192
return &JSAtom::intStatic(i);
1193
jschar c = 'a' + i - 10;
1194
JS_ASSERT(JSAtom::hasUnitStatic(c));
1195
return &JSAtom::unitStatic(c);
1198
if (JSFlatString *str = c->dtoaCache.lookup(base, d))
1201
numStr = IntToCString(&cbuf, i, base);
1202
JS_ASSERT(!cbuf.dbuf && numStr >= cbuf.sbuf && numStr < cbuf.sbuf + cbuf.sbufSize);
1204
if (JSFlatString *str = c->dtoaCache.lookup(base, d))
1207
numStr = FracNumberToCString(cx, &cbuf, d, base);
1209
JS_ReportOutOfMemory(cx);
1212
JS_ASSERT_IF(base == 10,
1213
!cbuf.dbuf && numStr >= cbuf.sbuf && numStr < cbuf.sbuf + cbuf.sbufSize);
1214
JS_ASSERT_IF(base != 10,
1215
cbuf.dbuf && cbuf.dbuf == numStr);
1218
JSFixedString *s = js_NewStringCopyZ(cx, numStr);
1219
c->dtoaCache.cache(base, d, s);
1223
JSString * JS_FASTCALL
1224
js_NumberToString(JSContext *cx, jsdouble d)
1226
return js_NumberToStringWithBase(cx, d, 10);
1232
NumberToString(JSContext *cx, jsdouble d)
1234
if (JSString *str = js_NumberToStringWithBase(cx, d, 10))
1235
return &str->asFixed();
1240
NumberValueToStringBuffer(JSContext *cx, const Value &v, StringBuffer &sb)
1242
/* Convert to C-string. */
1246
cstr = IntToCString(&cbuf, v.toInt32());
1248
cstr = NumberToCString(cx, &cbuf, v.toDouble());
1250
JS_ReportOutOfMemory(cx);
1256
* Inflate to jschar string. The input C-string characters are < 127, so
1257
* even if jschars are UTF-8, all chars should map to one jschar.
1259
size_t cstrlen = strlen(cstr);
1260
JS_ASSERT(!cbuf.dbuf && cstrlen < cbuf.sbufSize);
1261
return sb.appendInflated(cstr, cstrlen);
1265
ValueToNumberSlow(JSContext *cx, Value v, double *out)
1267
JS_ASSERT(!v.isNumber());
1268
goto skip_int_double;
1271
*out = v.toNumber();
1276
return StringToNumberType<jsdouble>(cx, v.toString(), out);
1277
if (v.isBoolean()) {
1278
if (v.toBoolean()) {
1289
if (v.isUndefined())
1292
JS_ASSERT(v.isObject());
1293
if (!DefaultValue(cx, &v.toObject(), JSTYPE_NUMBER, &v))
1304
ValueToECMAInt32Slow(JSContext *cx, const Value &v, int32_t *out)
1306
JS_ASSERT(!v.isInt32());
1311
if (!ValueToNumberSlow(cx, v, &d))
1314
*out = js_DoubleToECMAInt32(d);
1319
ValueToECMAUint32Slow(JSContext *cx, const Value &v, uint32_t *out)
1321
JS_ASSERT(!v.isInt32());
1326
if (!ValueToNumberSlow(cx, v, &d))
1329
*out = js_DoubleToECMAUint32(d);
1333
} /* namespace js */
1336
js_DoubleToECMAUint32(jsdouble d)
1342
if (!JSDOUBLE_IS_FINITE(d))
1346
* We check whether d fits int32, not uint32, as all but the ">>>" bit
1347
* manipulation bytecode stores the result as int, not uint. When the
1348
* result does not fit int Value, it will be stored as a negative double.
1351
if ((jsdouble) i == d)
1355
d = floor(neg ? -d : d);
1358
two32 = 4294967296.0;
1361
return (uint32) (d >= 0 ? d : d + two32);
1367
ValueToInt32Slow(JSContext *cx, const Value &v, int32_t *out)
1369
JS_ASSERT(!v.isInt32());
1373
} else if (!ValueToNumberSlow(cx, v, &d)) {
1377
if (JSDOUBLE_IS_NaN(d) || d <= -2147483649.0 || 2147483648.0 <= d) {
1378
js_ReportValueError(cx, JSMSG_CANT_CONVERT,
1379
JSDVG_SEARCH_STACK, v, NULL);
1382
*out = (int32) floor(d + 0.5); /* Round to nearest */
1387
ValueToUint16Slow(JSContext *cx, const Value &v, uint16_t *out)
1389
JS_ASSERT(!v.isInt32());
1393
} else if (!ValueToNumberSlow(cx, v, &d)) {
1397
if (d == 0 || !JSDOUBLE_IS_FINITE(d)) {
1402
uint16 u = (uint16) d;
1403
if ((jsdouble)u == d) {
1409
d = floor(neg ? -d : d);
1411
jsuint m = JS_BIT(16);
1412
d = fmod(d, (double) m);
1415
*out = (uint16_t) d;
1419
} /* namespace js */
1422
js_strtod(JSContext *cx, const jschar *s, const jschar *send,
1423
const jschar **ep, jsdouble *dp)
1428
char *cstr, *istr, *estr;
1432
s1 = js_SkipWhiteSpace(s, send);
1435
/* Use cbuf to avoid malloc */
1436
if (length >= sizeof cbuf) {
1437
cstr = (char *) cx->malloc_(length + 1);
1444
for (i = 0; i != length; i++) {
1447
cstr[i] = (char)s1[i];
1452
if ((negative = (*istr == '-')) != 0 || *istr == '+')
1454
if (*istr == 'I' && !strncmp(istr, js_Infinity_str, sizeof js_Infinity_str - 1)) {
1455
d = negative ? js_NegativeInfinity : js_PositiveInfinity;
1459
d = js_strtod_harder(JS_THREAD_DATA(cx)->dtoaState, cstr, &estr, &err);
1461
d = js_PositiveInfinity;
1462
else if (d == -HUGE_VAL)
1463
d = js_NegativeInfinity;
1469
*ep = i ? s1 + i : s;