2 * Copyright (C) 1999-2000,2003 Harri Porten (porten@kde.org)
3 * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
23 #include "number_object.h"
24 #include "number_object.lut.h"
27 #include "error_object.h"
28 #include "operations.h"
29 #include <wtf/Assertions.h>
30 #include <wtf/MathExtras.h>
31 #include <wtf/Vector.h>
35 // ------------------------------ NumberInstance ----------------------------
37 const ClassInfo NumberInstance::info = { "Number", 0, 0, 0 };
39 NumberInstance::NumberInstance(JSObject* proto)
40 : JSWrapperObject(proto)
44 // ------------------------------ NumberPrototype ---------------------------
46 static JSValue* numberProtoFuncToString(ExecState*, JSObject*, const List&);
47 static JSValue* numberProtoFuncToLocaleString(ExecState*, JSObject*, const List&);
48 static JSValue* numberProtoFuncValueOf(ExecState*, JSObject*, const List&);
49 static JSValue* numberProtoFuncToFixed(ExecState*, JSObject*, const List&);
50 static JSValue* numberProtoFuncToExponential(ExecState*, JSObject*, const List&);
51 static JSValue* numberProtoFuncToPrecision(ExecState*, JSObject*, const List&);
55 NumberPrototype::NumberPrototype(ExecState* exec, ObjectPrototype* objectPrototype, FunctionPrototype* functionPrototype)
56 : NumberInstance(objectPrototype)
58 setInternalValue(jsNumber(0));
60 // The constructor will be added later, after NumberObjectImp has been constructed
62 putDirectFunction(new PrototypeFunction(exec, functionPrototype, 1, exec->propertyNames().toString, numberProtoFuncToString), DontEnum);
63 putDirectFunction(new PrototypeFunction(exec, functionPrototype, 0, exec->propertyNames().toLocaleString, numberProtoFuncToLocaleString), DontEnum);
64 putDirectFunction(new PrototypeFunction(exec, functionPrototype, 0, exec->propertyNames().valueOf, numberProtoFuncValueOf), DontEnum);
65 putDirectFunction(new PrototypeFunction(exec, functionPrototype, 1, exec->propertyNames().toFixed, numberProtoFuncToFixed), DontEnum);
66 putDirectFunction(new PrototypeFunction(exec, functionPrototype, 1, exec->propertyNames().toExponential, numberProtoFuncToExponential), DontEnum);
67 putDirectFunction(new PrototypeFunction(exec, functionPrototype, 1, exec->propertyNames().toPrecision, numberProtoFuncToPrecision), DontEnum);
70 // ------------------------------ Functions ---------------------------
72 // ECMA 15.7.4.2 - 15.7.4.7
74 static UString integer_part_noexp(double d)
78 char* result = dtoa(d, 0, &decimalPoint, &sign, NULL);
79 bool resultIsInfOrNan = (decimalPoint == 9999);
80 size_t length = strlen(result);
82 UString str = sign ? "-" : "";
85 else if (decimalPoint <= 0)
88 Vector<char, 1024> buf(decimalPoint + 1);
90 if (static_cast<int>(length) <= decimalPoint) {
91 strcpy(buf.data(), result);
92 memset(buf.data() + length, '0', decimalPoint - length);
94 strncpy(buf.data(), result, decimalPoint);
96 buf[decimalPoint] = '\0';
97 str += UString(buf.data());
105 static UString char_sequence(char c, int count)
107 Vector<char, 2048> buf(count + 1, c);
110 return UString(buf.data());
113 static double intPow10(int e)
115 // This function uses the "exponentiation by squaring" algorithm and
116 // long double to quickly and precisely calculate integer powers of 10.0.
118 // This is a handy workaround for <rdar://problem/4494756>
123 bool negative = e < 0;
124 unsigned exp = negative ? -e : e;
126 long double result = 10.0;
127 bool foundOne = false;
128 for (int bit = 31; bit >= 0; bit--) {
130 if ((exp >> bit) & 1)
133 result = result * result;
134 if ((exp >> bit) & 1)
135 result = result * 10.0;
140 return static_cast<double>(1.0 / result);
141 return static_cast<double>(result);
145 JSValue* numberProtoFuncToString(ExecState* exec, JSObject* thisObj, const List& args)
147 if (!thisObj->inherits(&NumberInstance::info))
148 return throwError(exec, TypeError);
150 JSValue* v = static_cast<NumberInstance*>(thisObj)->internalValue();
152 double radixAsDouble = args[0]->toInteger(exec); // nan -> 0
153 if (radixAsDouble == 10 || args[0]->isUndefined())
154 return jsString(v->toString(exec));
156 if (radixAsDouble < 2 || radixAsDouble > 36)
157 return throwError(exec, RangeError, "toString() radix argument must be between 2 and 36");
159 int radix = static_cast<int>(radixAsDouble);
160 const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
161 // INT_MAX results in 1024 characters left of the dot with radix 2
162 // give the same space on the right side. safety checks are in place
163 // unless someone finds a precise rule.
165 const char* lastCharInString = s + sizeof(s) - 1;
166 double x = v->toNumber(exec);
167 if (isnan(x) || isinf(x))
168 return jsString(UString::from(x));
170 bool isNegative = x < 0.0;
174 double integerPart = floor(x);
175 char* decimalPoint = s + sizeof(s) / 2;
177 // convert integer portion
178 char* p = decimalPoint;
179 double d = integerPart;
181 int remainderDigit = static_cast<int>(fmod(d, radix));
182 *--p = digits[remainderDigit];
184 } while ((d <= -1.0 || d >= 1.0) && s < p);
188 char* startOfResultString = p;
189 ASSERT(s <= startOfResultString);
193 const double epsilon = 0.001; // TODO: guessed. base on radix ?
194 bool hasFractionalPart = (d < -epsilon || d > epsilon);
195 if (hasFractionalPart) {
199 const int digit = static_cast<int>(d);
200 *p++ = digits[digit];
202 } while ((d < -epsilon || d > epsilon) && p < lastCharInString);
205 ASSERT(p < s + sizeof(s));
207 return jsString(startOfResultString);
210 JSValue* numberProtoFuncToLocaleString(ExecState* exec, JSObject* thisObj, const List&)
212 if (!thisObj->inherits(&NumberInstance::info))
213 return throwError(exec, TypeError);
216 return jsString(static_cast<NumberInstance*>(thisObj)->internalValue()->toString(exec));
219 JSValue* numberProtoFuncValueOf(ExecState* exec, JSObject* thisObj, const List&)
221 if (!thisObj->inherits(&NumberInstance::info))
222 return throwError(exec, TypeError);
224 return static_cast<NumberInstance*>(thisObj)->internalValue()->toJSNumber(exec);
227 JSValue* numberProtoFuncToFixed(ExecState* exec, JSObject* thisObj, const List& args)
229 if (!thisObj->inherits(&NumberInstance::info))
230 return throwError(exec, TypeError);
232 JSValue* v = static_cast<NumberInstance*>(thisObj)->internalValue();
234 JSValue* fractionDigits = args[0];
235 double df = fractionDigits->toInteger(exec);
236 if (!(df >= 0 && df <= 20))
237 return throwError(exec, RangeError, "toFixed() digits argument must be between 0 and 20");
240 double x = v->toNumber(exec);
242 return jsString("NaN");
248 } else if (x == -0.0)
251 if (x >= pow(10.0, 21.0))
252 return jsString(s + UString::from(x));
254 const double tenToTheF = pow(10.0, f);
255 double n = floor(x * tenToTheF);
256 if (fabs(n / tenToTheF - x) >= fabs((n + 1) / tenToTheF - x))
259 UString m = integer_part_noexp(n);
264 for (int i = 0; i < f + 1 - k; i++)
268 ASSERT(k == m.size());
271 if (kMinusf < m.size())
272 return jsString(s + m.substr(0, kMinusf) + "." + m.substr(kMinusf));
273 return jsString(s + m.substr(0, kMinusf));
276 static void fractionalPartToString(char* buf, int& i, const char* result, int resultLength, int fractionalDigits)
278 if (fractionalDigits <= 0)
281 int fDigitsInResult = static_cast<int>(resultLength) - 1;
283 if (fDigitsInResult > 0) {
284 if (fractionalDigits < fDigitsInResult) {
285 strncpy(buf + i, result + 1, fractionalDigits);
286 i += fractionalDigits;
288 strcpy(buf + i, result + 1);
289 i += static_cast<int>(resultLength) - 1;
293 for (int j = 0; j < fractionalDigits - fDigitsInResult; j++)
297 static void exponentialPartToString(char* buf, int& i, int decimalPoint)
300 buf[i++] = (decimalPoint >= 0) ? '+' : '-';
301 // decimalPoint can't be more than 3 digits decimal given the
302 // nature of float representation
303 int exponential = decimalPoint - 1;
306 if (exponential >= 100)
307 buf[i++] = static_cast<char>('0' + exponential / 100);
308 if (exponential >= 10)
309 buf[i++] = static_cast<char>('0' + (exponential % 100) / 10);
310 buf[i++] = static_cast<char>('0' + exponential % 10);
313 JSValue* numberProtoFuncToExponential(ExecState* exec, JSObject* thisObj, const List& args)
315 if (!thisObj->inherits(&NumberInstance::info))
316 return throwError(exec, TypeError);
318 JSValue* v = static_cast<NumberInstance*>(thisObj)->internalValue();
320 double x = v->toNumber(exec);
322 if (isnan(x) || isinf(x))
323 return jsString(UString::from(x));
325 JSValue* fractionalDigitsValue = args[0];
326 double df = fractionalDigitsValue->toInteger(exec);
327 if (!(df >= 0 && df <= 20))
328 return throwError(exec, RangeError, "toExponential() argument must between 0 and 20");
329 int fractionalDigits = (int)df;
330 bool includeAllDigits = fractionalDigitsValue->isUndefined();
332 int decimalAdjust = 0;
333 if (x && !includeAllDigits) {
334 double logx = floor(log10(fabs(x)));
335 x /= pow(10.0, logx);
336 const double tenToTheF = pow(10.0, fractionalDigits);
337 double fx = floor(x * tenToTheF) / tenToTheF;
338 double cx = ceil(x * tenToTheF) / tenToTheF;
340 if (fabs(fx - x) < fabs(cx - x))
345 decimalAdjust = static_cast<int>(logx);
349 return jsString("NaN");
351 if (x == -0.0) // (-0.0).toExponential() should print as 0 instead of -0
356 char* result = dtoa(x, 0, &decimalPoint, &sign, NULL);
357 size_t resultLength = strlen(result);
358 decimalPoint += decimalAdjust;
361 char buf[80]; // digit + '.' + fractionDigits (max 20) + 'e' + sign + exponent (max?)
365 if (decimalPoint == 999) // ? 9999 is the magical "result is Inf or NaN" value. what's 999??
366 strcpy(buf + i, result);
368 buf[i++] = result[0];
370 if (includeAllDigits)
371 fractionalDigits = static_cast<int>(resultLength) - 1;
373 fractionalPartToString(buf, i, result, resultLength, fractionalDigits);
374 exponentialPartToString(buf, i, decimalPoint);
381 return jsString(buf);
384 JSValue* numberProtoFuncToPrecision(ExecState* exec, JSObject* thisObj, const List& args)
386 if (!thisObj->inherits(&NumberInstance::info))
387 return throwError(exec, TypeError);
389 JSValue* v = static_cast<NumberInstance*>(thisObj)->internalValue();
391 double doublePrecision = args[0]->toIntegerPreserveNaN(exec);
392 double x = v->toNumber(exec);
393 if (args[0]->isUndefined() || isnan(x) || isinf(x))
394 return jsString(v->toString(exec));
402 if (!(doublePrecision >= 1 && doublePrecision <= 21)) // true for NaN
403 return throwError(exec, RangeError, "toPrecision() argument must be between 1 and 21");
404 int precision = (int)doublePrecision;
409 e = static_cast<int>(log10(x));
410 double tens = intPow10(e - precision + 1);
411 double n = floor(x / tens);
412 if (n < intPow10(precision - 1)) {
414 tens = intPow10(e - precision + 1);
418 if (fabs((n + 1.0) * tens - x) <= fabs(n * tens - x))
420 // maintain n < 10^(precision)
421 if (n >= intPow10(precision)) {
425 ASSERT(intPow10(precision - 1) <= n);
426 ASSERT(n < intPow10(precision));
428 m = integer_part_noexp(n);
429 if (e < -6 || e >= precision) {
431 m = m.substr(0, 1) + "." + m.substr(1);
433 return jsString(s + m + "e+" + UString::from(e));
434 return jsString(s + m + "e-" + UString::from(-e));
437 m = char_sequence('0', precision);
441 if (e == precision - 1)
442 return jsString(s + m);
444 if (e + 1 < m.size())
445 return jsString(s + m.substr(0, e + 1) + "." + m.substr(e + 1));
446 return jsString(s + m);
448 return jsString(s + "0." + char_sequence('0', -(e + 1)) + m);
451 // ------------------------------ NumberObjectImp ------------------------------
453 const ClassInfo NumberObjectImp::info = { "Function", &InternalFunctionImp::info, 0, ExecState::numberTable };
455 /* Source for number_object.lut.h
457 NaN NumberObjectImp::NaNValue DontEnum|DontDelete|ReadOnly
458 NEGATIVE_INFINITY NumberObjectImp::NegInfinity DontEnum|DontDelete|ReadOnly
459 POSITIVE_INFINITY NumberObjectImp::PosInfinity DontEnum|DontDelete|ReadOnly
460 MAX_VALUE NumberObjectImp::MaxValue DontEnum|DontDelete|ReadOnly
461 MIN_VALUE NumberObjectImp::MinValue DontEnum|DontDelete|ReadOnly
464 NumberObjectImp::NumberObjectImp(ExecState* exec, FunctionPrototype* funcProto, NumberPrototype* numberProto)
465 : InternalFunctionImp(funcProto, numberProto->classInfo()->className)
468 putDirect(exec->propertyNames().prototype, numberProto, DontEnum|DontDelete|ReadOnly);
470 // no. of arguments for constructor
471 putDirect(exec->propertyNames().length, jsNumber(1), ReadOnly|DontDelete|DontEnum);
474 bool NumberObjectImp::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
476 return getStaticValueSlot<NumberObjectImp, InternalFunctionImp>(exec, ExecState::numberTable(exec), this, propertyName, slot);
479 JSValue* NumberObjectImp::getValueProperty(ExecState*, int token) const
486 return jsNumberCell(-Inf);
488 return jsNumberCell(Inf);
490 return jsNumberCell(1.7976931348623157E+308);
492 return jsNumberCell(5E-324);
494 ASSERT_NOT_REACHED();
498 bool NumberObjectImp::implementsConstruct() const
504 JSObject* NumberObjectImp::construct(ExecState* exec, const List& args)
506 JSObject* proto = exec->lexicalGlobalObject()->numberPrototype();
507 NumberInstance* obj = new NumberInstance(proto);
509 // FIXME: Check args[0]->isUndefined() instead of args.isEmpty()?
510 double n = args.isEmpty() ? 0 : args[0]->toNumber(exec);
511 obj->setInternalValue(jsNumber(n));
516 JSValue* NumberObjectImp::callAsFunction(ExecState* exec, JSObject*, const List& args)
518 // FIXME: Check args[0]->isUndefined() instead of args.isEmpty()?
519 return jsNumber(args.isEmpty() ? 0 : args[0]->toNumber(exec));