blob: c34fe519c42f94c6652650c7acbd2c3d74e70c5c [file] [log] [blame]
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001// Copyright 2011 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include <stdarg.h>
ager@chromium.orgb26c50a2010-03-26 09:27:16 +000029#include <limits.h>
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000030
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000031#include "conversions-inl.h"
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +000032#include "dtoa.h"
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +000033#include "scanner-base.h"
ager@chromium.orgb61a0d12010-10-13 08:35:23 +000034#include "strtod.h"
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +000035#include "utils.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000036
kasperl@chromium.org71affb52009-05-26 05:44:31 +000037namespace v8 {
38namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000039
lrn@chromium.org25156de2010-04-06 13:10:27 +000040
41
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000042double StringToDouble(UnicodeCache* unicode_cache,
43 const char* str, int flags, double empty_string_val) {
ager@chromium.orgb26c50a2010-03-26 09:27:16 +000044 const char* end = str + StrLength(str);
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000045 return InternalStringToDouble(unicode_cache, str, end, flags,
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000046 empty_string_val);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000047}
48
49
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000050double StringToDouble(UnicodeCache* unicode_cache,
51 Vector<const char> str,
ricow@chromium.org65fae842010-08-25 15:26:24 +000052 int flags,
53 double empty_string_val) {
54 const char* end = str.start() + str.length();
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000055 return InternalStringToDouble(unicode_cache, str.start(), end, flags,
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000056 empty_string_val);
ricow@chromium.org65fae842010-08-25 15:26:24 +000057}
58
danno@chromium.org40cb8782011-05-25 07:58:50 +000059double StringToDouble(UnicodeCache* unicode_cache,
60 Vector<const uc16> str,
61 int flags,
62 double empty_string_val) {
63 const uc16* end = str.start() + str.length();
64 return InternalStringToDouble(unicode_cache, str.start(), end, flags,
65 empty_string_val);
66}
67
ricow@chromium.org65fae842010-08-25 15:26:24 +000068
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000069const char* DoubleToCString(double v, Vector<char> buffer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000070 switch (fpclassify(v)) {
ricow@chromium.org83aa5492011-02-07 12:42:56 +000071 case FP_NAN: return "NaN";
72 case FP_INFINITE: return (v < 0.0 ? "-Infinity" : "Infinity");
73 case FP_ZERO: return "0";
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000074 default: {
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +000075 SimpleStringBuilder builder(buffer.start(), buffer.length());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000076 int decimal_point;
77 int sign;
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +000078 const int kV8DtoaBufferCapacity = kBase10MaximalLength + 1;
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +000079 char decimal_rep[kV8DtoaBufferCapacity];
whesse@chromium.orgcec079d2010-03-22 14:44:04 +000080 int length;
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +000081
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +000082 DoubleToAscii(v, DTOA_SHORTEST, 0,
83 Vector<char>(decimal_rep, kV8DtoaBufferCapacity),
84 &sign, &length, &decimal_point);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000085
86 if (sign) builder.AddCharacter('-');
87
88 if (length <= decimal_point && decimal_point <= 21) {
89 // ECMA-262 section 9.8.1 step 6.
90 builder.AddString(decimal_rep);
91 builder.AddPadding('0', decimal_point - length);
92
93 } else if (0 < decimal_point && decimal_point <= 21) {
94 // ECMA-262 section 9.8.1 step 7.
95 builder.AddSubstring(decimal_rep, decimal_point);
96 builder.AddCharacter('.');
97 builder.AddString(decimal_rep + decimal_point);
98
99 } else if (decimal_point <= 0 && decimal_point > -6) {
100 // ECMA-262 section 9.8.1 step 8.
101 builder.AddString("0.");
102 builder.AddPadding('0', -decimal_point);
103 builder.AddString(decimal_rep);
104
105 } else {
106 // ECMA-262 section 9.8.1 step 9 and 10 combined.
107 builder.AddCharacter(decimal_rep[0]);
108 if (length != 1) {
109 builder.AddCharacter('.');
110 builder.AddString(decimal_rep + 1);
111 }
112 builder.AddCharacter('e');
113 builder.AddCharacter((decimal_point >= 0) ? '+' : '-');
114 int exponent = decimal_point - 1;
115 if (exponent < 0) exponent = -exponent;
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000116 builder.AddDecimalInteger(exponent);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000117 }
ricow@chromium.org83aa5492011-02-07 12:42:56 +0000118 return builder.Finalize();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000119 }
120 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000121}
122
123
124const char* IntToCString(int n, Vector<char> buffer) {
125 bool negative = false;
126 if (n < 0) {
127 // We must not negate the most negative int.
128 if (n == kMinInt) return DoubleToCString(n, buffer);
129 negative = true;
130 n = -n;
131 }
132 // Build the string backwards from the least significant digit.
133 int i = buffer.length();
134 buffer[--i] = '\0';
135 do {
136 buffer[--i] = '0' + (n % 10);
137 n /= 10;
138 } while (n);
139 if (negative) buffer[--i] = '-';
140 return buffer.start() + i;
141}
142
143
144char* DoubleToFixedCString(double value, int f) {
whesse@chromium.orgf0ac72d2010-11-08 12:47:26 +0000145 const int kMaxDigitsBeforePoint = 21;
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000146 const double kFirstNonFixed = 1e21;
147 const int kMaxDigitsAfterPoint = 20;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000148 ASSERT(f >= 0);
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000149 ASSERT(f <= kMaxDigitsAfterPoint);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000150
151 bool negative = false;
152 double abs_value = value;
153 if (value < 0) {
154 abs_value = -value;
155 negative = true;
156 }
157
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000158 // If abs_value has more than kMaxDigitsBeforePoint digits before the point
159 // use the non-fixed conversion routine.
160 if (abs_value >= kFirstNonFixed) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000161 char arr[100];
162 Vector<char> buffer(arr, ARRAY_SIZE(arr));
163 return StrDup(DoubleToCString(value, buffer));
164 }
165
166 // Find a sufficiently precise decimal representation of n.
167 int decimal_point;
168 int sign;
whesse@chromium.orgf0ac72d2010-11-08 12:47:26 +0000169 // Add space for the '\0' byte.
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000170 const int kDecimalRepCapacity =
whesse@chromium.orgf0ac72d2010-11-08 12:47:26 +0000171 kMaxDigitsBeforePoint + kMaxDigitsAfterPoint + 1;
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000172 char decimal_rep[kDecimalRepCapacity];
173 int decimal_rep_length;
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +0000174 DoubleToAscii(value, DTOA_FIXED, f,
175 Vector<char>(decimal_rep, kDecimalRepCapacity),
176 &sign, &decimal_rep_length, &decimal_point);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000177
178 // Create a representation that is padded with zeros if needed.
179 int zero_prefix_length = 0;
180 int zero_postfix_length = 0;
181
182 if (decimal_point <= 0) {
183 zero_prefix_length = -decimal_point + 1;
184 decimal_point = 1;
185 }
186
187 if (zero_prefix_length + decimal_rep_length < decimal_point + f) {
188 zero_postfix_length = decimal_point + f - decimal_rep_length -
189 zero_prefix_length;
190 }
191
192 unsigned rep_length =
193 zero_prefix_length + decimal_rep_length + zero_postfix_length;
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000194 SimpleStringBuilder rep_builder(rep_length + 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000195 rep_builder.AddPadding('0', zero_prefix_length);
196 rep_builder.AddString(decimal_rep);
197 rep_builder.AddPadding('0', zero_postfix_length);
198 char* rep = rep_builder.Finalize();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000199
200 // Create the result string by appending a minus and putting in a
201 // decimal point if needed.
202 unsigned result_size = decimal_point + f + 2;
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000203 SimpleStringBuilder builder(result_size + 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000204 if (negative) builder.AddCharacter('-');
205 builder.AddSubstring(rep, decimal_point);
206 if (f > 0) {
207 builder.AddCharacter('.');
208 builder.AddSubstring(rep + decimal_point, f);
209 }
210 DeleteArray(rep);
211 return builder.Finalize();
212}
213
214
215static char* CreateExponentialRepresentation(char* decimal_rep,
216 int exponent,
217 bool negative,
218 int significant_digits) {
219 bool negative_exponent = false;
220 if (exponent < 0) {
221 negative_exponent = true;
222 exponent = -exponent;
223 }
224
225 // Leave room in the result for appending a minus, for a period, the
226 // letter 'e', a minus or a plus depending on the exponent, and a
227 // three digit exponent.
228 unsigned result_size = significant_digits + 7;
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000229 SimpleStringBuilder builder(result_size + 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000230
231 if (negative) builder.AddCharacter('-');
232 builder.AddCharacter(decimal_rep[0]);
233 if (significant_digits != 1) {
234 builder.AddCharacter('.');
235 builder.AddString(decimal_rep + 1);
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000236 int rep_length = StrLength(decimal_rep);
237 builder.AddPadding('0', significant_digits - rep_length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000238 }
239
240 builder.AddCharacter('e');
241 builder.AddCharacter(negative_exponent ? '-' : '+');
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000242 builder.AddDecimalInteger(exponent);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000243 return builder.Finalize();
244}
245
246
247
248char* DoubleToExponentialCString(double value, int f) {
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000249 const int kMaxDigitsAfterPoint = 20;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000250 // f might be -1 to signal that f was undefined in JavaScript.
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000251 ASSERT(f >= -1 && f <= kMaxDigitsAfterPoint);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000252
253 bool negative = false;
254 if (value < 0) {
255 value = -value;
256 negative = true;
257 }
258
259 // Find a sufficiently precise decimal representation of n.
260 int decimal_point;
261 int sign;
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000262 // f corresponds to the digits after the point. There is always one digit
263 // before the point. The number of requested_digits equals hence f + 1.
264 // And we have to add one character for the null-terminator.
265 const int kV8DtoaBufferCapacity = kMaxDigitsAfterPoint + 1 + 1;
266 // Make sure that the buffer is big enough, even if we fall back to the
267 // shortest representation (which happens when f equals -1).
268 ASSERT(kBase10MaximalLength <= kMaxDigitsAfterPoint + 1);
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +0000269 char decimal_rep[kV8DtoaBufferCapacity];
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000270 int decimal_rep_length;
271
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000272 if (f == -1) {
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +0000273 DoubleToAscii(value, DTOA_SHORTEST, 0,
274 Vector<char>(decimal_rep, kV8DtoaBufferCapacity),
275 &sign, &decimal_rep_length, &decimal_point);
276 f = decimal_rep_length - 1;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000277 } else {
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +0000278 DoubleToAscii(value, DTOA_PRECISION, f + 1,
279 Vector<char>(decimal_rep, kV8DtoaBufferCapacity),
280 &sign, &decimal_rep_length, &decimal_point);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000281 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000282 ASSERT(decimal_rep_length > 0);
283 ASSERT(decimal_rep_length <= f + 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000284
285 int exponent = decimal_point - 1;
286 char* result =
287 CreateExponentialRepresentation(decimal_rep, exponent, negative, f+1);
288
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000289 return result;
290}
291
292
293char* DoubleToPrecisionCString(double value, int p) {
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000294 const int kMinimalDigits = 1;
295 const int kMaximalDigits = 21;
296 ASSERT(p >= kMinimalDigits && p <= kMaximalDigits);
297 USE(kMinimalDigits);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000298
299 bool negative = false;
300 if (value < 0) {
301 value = -value;
302 negative = true;
303 }
304
305 // Find a sufficiently precise decimal representation of n.
306 int decimal_point;
307 int sign;
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000308 // Add one for the terminating null character.
309 const int kV8DtoaBufferCapacity = kMaximalDigits + 1;
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +0000310 char decimal_rep[kV8DtoaBufferCapacity];
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000311 int decimal_rep_length;
312
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +0000313 DoubleToAscii(value, DTOA_PRECISION, p,
314 Vector<char>(decimal_rep, kV8DtoaBufferCapacity),
315 &sign, &decimal_rep_length, &decimal_point);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000316 ASSERT(decimal_rep_length <= p);
317
318 int exponent = decimal_point - 1;
319
320 char* result = NULL;
321
322 if (exponent < -6 || exponent >= p) {
323 result =
324 CreateExponentialRepresentation(decimal_rep, exponent, negative, p);
325 } else {
326 // Use fixed notation.
327 //
328 // Leave room in the result for appending a minus, a period and in
329 // the case where decimal_point is not positive for a zero in
330 // front of the period.
331 unsigned result_size = (decimal_point <= 0)
332 ? -decimal_point + p + 3
333 : p + 2;
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000334 SimpleStringBuilder builder(result_size + 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000335 if (negative) builder.AddCharacter('-');
336 if (decimal_point <= 0) {
337 builder.AddString("0.");
338 builder.AddPadding('0', -decimal_point);
339 builder.AddString(decimal_rep);
340 builder.AddPadding('0', p - decimal_rep_length);
341 } else {
342 const int m = Min(decimal_rep_length, decimal_point);
343 builder.AddSubstring(decimal_rep, m);
344 builder.AddPadding('0', decimal_point - decimal_rep_length);
345 if (decimal_point < p) {
346 builder.AddCharacter('.');
347 const int extra = negative ? 2 : 1;
348 if (decimal_rep_length > decimal_point) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000349 const int len = StrLength(decimal_rep + decimal_point);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000350 const int n = Min(len, p - (builder.position() - extra));
351 builder.AddSubstring(decimal_rep + decimal_point, n);
352 }
353 builder.AddPadding('0', extra + (p - builder.position()));
354 }
355 }
356 result = builder.Finalize();
357 }
358
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000359 return result;
360}
361
362
363char* DoubleToRadixCString(double value, int radix) {
364 ASSERT(radix >= 2 && radix <= 36);
365
366 // Character array used for conversion.
367 static const char chars[] = "0123456789abcdefghijklmnopqrstuvwxyz";
368
369 // Buffer for the integer part of the result. 1024 chars is enough
370 // for max integer value in radix 2. We need room for a sign too.
371 static const int kBufferSize = 1100;
372 char integer_buffer[kBufferSize];
373 integer_buffer[kBufferSize - 1] = '\0';
374
375 // Buffer for the decimal part of the result. We only generate up
376 // to kBufferSize - 1 chars for the decimal part.
377 char decimal_buffer[kBufferSize];
378 decimal_buffer[kBufferSize - 1] = '\0';
379
380 // Make sure the value is positive.
381 bool is_negative = value < 0.0;
382 if (is_negative) value = -value;
383
384 // Get the integer part and the decimal part.
385 double integer_part = floor(value);
386 double decimal_part = value - integer_part;
387
388 // Convert the integer part starting from the back. Always generate
389 // at least one digit.
390 int integer_pos = kBufferSize - 2;
391 do {
392 integer_buffer[integer_pos--] =
ager@chromium.org3811b432009-10-28 14:53:37 +0000393 chars[static_cast<int>(modulo(integer_part, radix))];
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000394 integer_part /= radix;
395 } while (integer_part >= 1.0);
396 // Sanity check.
397 ASSERT(integer_pos > 0);
398 // Add sign if needed.
399 if (is_negative) integer_buffer[integer_pos--] = '-';
400
401 // Convert the decimal part. Repeatedly multiply by the radix to
402 // generate the next char. Never generate more than kBufferSize - 1
403 // chars.
404 //
405 // TODO(1093998): We will often generate a full decimal_buffer of
406 // chars because hitting zero will often not happen. The right
407 // solution would be to continue until the string representation can
408 // be read back and yield the original value. To implement this
409 // efficiently, we probably have to modify dtoa.
410 int decimal_pos = 0;
411 while ((decimal_part > 0.0) && (decimal_pos < kBufferSize - 1)) {
412 decimal_part *= radix;
413 decimal_buffer[decimal_pos++] =
414 chars[static_cast<int>(floor(decimal_part))];
415 decimal_part -= floor(decimal_part);
416 }
417 decimal_buffer[decimal_pos] = '\0';
418
419 // Compute the result size.
420 int integer_part_size = kBufferSize - 2 - integer_pos;
421 // Make room for zero termination.
422 unsigned result_size = integer_part_size + decimal_pos;
423 // If the number has a decimal part, leave room for the period.
424 if (decimal_pos > 0) result_size++;
425 // Allocate result and fill in the parts.
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000426 SimpleStringBuilder builder(result_size + 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000427 builder.AddSubstring(integer_buffer + integer_pos + 1, integer_part_size);
428 if (decimal_pos > 0) builder.AddCharacter('.');
429 builder.AddSubstring(decimal_buffer, decimal_pos);
430 return builder.Finalize();
431}
432
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000433} } // namespace v8::internal