OSDN Git Service

Please enter the commit message for your changes. Lines starting
[eos/base.git] / util / src / TclTk / tcl8.6.12 / generic / tclStrToD.c
1 /*
2  * tclStrToD.c --
3  *
4  *      This file contains a collection of procedures for managing conversions
5  *      to/from floating-point in Tcl. They include TclParseNumber, which
6  *      parses numbers from strings; TclDoubleDigits, which formats numbers
7  *      into strings of digits, and procedures for interconversion among
8  *      'double' and 'mp_int' types.
9  *
10  * Copyright (c) 2005 by Kevin B. Kenny. All rights reserved.
11  *
12  * See the file "license.terms" for information on usage and redistribution of
13  * this file, and for a DISCLAIMER OF ALL WARRANTIES.
14  */
15
16 #include "tclInt.h"
17 #include "tommath.h"
18 #include <float.h>
19 #include <math.h>
20
21 #ifdef _WIN32
22 #define copysign _copysign
23 #endif
24
25 /*
26  * Define KILL_OCTAL to suppress interpretation of numbers with leading zero
27  * as octal. (Ceterum censeo: numeros octonarios delendos esse.)
28  */
29
30 #undef  KILL_OCTAL
31
32 /*
33  * This code supports (at least hypothetically), IBM, Cray, VAX and IEEE-754
34  * floating point; of these, only IEEE-754 can represent NaN. IEEE-754 can be
35  * uniquely determined by radix and by the widths of significand and exponent.
36  */
37
38 #if (FLT_RADIX == 2) && (DBL_MANT_DIG == 53) && (DBL_MAX_EXP == 1024)
39 #   define IEEE_FLOATING_POINT
40 #endif
41
42 /*
43  * Rounding controls. (Thanks a lot, Intel!)
44  */
45
46 #ifdef __i386
47 /*
48  * gcc on x86 needs access to rounding controls, because of a questionable
49  * feature where it retains intermediate results as IEEE 'long double' values
50  * somewhat unpredictably. It is tempting to include fpu_control.h, but that
51  * file exists only on Linux; it is missing on Cygwin and MinGW. Most gcc-isms
52  * and ix86-isms are factored out here.
53  */
54
55 #if defined(__GNUC__)
56 typedef unsigned int    fpu_control_t __attribute__ ((__mode__ (__HI__)));
57
58 #define _FPU_GETCW(cw)  __asm__ __volatile__ ("fnstcw %0" : "=m" (*&cw))
59 #define _FPU_SETCW(cw)  __asm__ __volatile__ ("fldcw %0" : : "m" (*&cw))
60 #   define FPU_IEEE_ROUNDING    0x027F
61 #   define ADJUST_FPU_CONTROL_WORD
62 #define TCL_IEEE_DOUBLE_ROUNDING \
63     fpu_control_t roundTo53Bits = FPU_IEEE_ROUNDING;    \
64     fpu_control_t oldRoundingMode;                      \
65     _FPU_GETCW(oldRoundingMode);                        \
66     _FPU_SETCW(roundTo53Bits)
67 #define TCL_DEFAULT_DOUBLE_ROUNDING \
68     _FPU_SETCW(oldRoundingMode)
69
70 /*
71  * Sun ProC needs sunmath for rounding control on x86 like gcc above.
72  */
73 #elif defined(__sun)
74 #include <sunmath.h>
75 #define TCL_IEEE_DOUBLE_ROUNDING \
76     ieee_flags("set","precision","double",NULL)
77 #define TCL_DEFAULT_DOUBLE_ROUNDING \
78     ieee_flags("clear","precision",NULL,NULL)
79
80 /*
81  * Other platforms are assumed to always operate in full IEEE mode, so we make
82  * the macros to go in and out of that mode do nothing.
83  */
84
85 #else /* !__GNUC__ && !__sun */
86 #define TCL_IEEE_DOUBLE_ROUNDING        ((void) 0)
87 #define TCL_DEFAULT_DOUBLE_ROUNDING     ((void) 0)
88 #endif
89 #else /* !__i386 */
90 #define TCL_IEEE_DOUBLE_ROUNDING        ((void) 0)
91 #define TCL_DEFAULT_DOUBLE_ROUNDING     ((void) 0)
92 #endif
93
94 /*
95  * MIPS floating-point units need special settings in control registers to use
96  * gradual underflow as we expect.  This fix is for the MIPSpro compiler.
97  */
98
99 #if defined(__sgi) && defined(_COMPILER_VERSION)
100 #include <sys/fpu.h>
101 #endif
102
103 /*
104  * HP's PA_RISC architecture uses 7ff4000000000000 to represent a quiet NaN.
105  * Everyone else uses 7ff8000000000000. (Why, HP, why?)
106  */
107
108 #ifdef __hppa
109 #   define NAN_START    0x7FF4
110 #   define NAN_MASK     (((Tcl_WideUInt) 1) << 50)
111 #else
112 #   define NAN_START    0x7FF8
113 #   define NAN_MASK     (((Tcl_WideUInt) 1) << 51)
114 #endif
115
116 /*
117  * Constants used by this file (most of which are only ever calculated at
118  * runtime).
119  */
120
121 /* Magic constants */
122
123 #define LOG10_2 0.3010299956639812
124 #define TWO_OVER_3LOG10 0.28952965460216784
125 #define LOG10_3HALVES_PLUS_FUDGE 0.1760912590558
126
127 /*
128  * Definitions of the parts of an IEEE754-format floating point number.
129  */
130
131 #define SIGN_BIT        0x80000000
132                                 /* Mask for the sign bit in the first word of
133                                  * a double. */
134 #define EXP_MASK        0x7FF00000
135                                 /* Mask for the exponent field in the first
136                                  * word of a double. */
137 #define EXP_SHIFT       20      /* Shift count to make the exponent an
138                                  * integer. */
139 #define HIDDEN_BIT      (((Tcl_WideUInt) 0x00100000) << 32)
140                                 /* Hidden 1 bit for the significand. */
141 #define HI_ORDER_SIG_MASK 0x000FFFFF
142                                 /* Mask for the high-order part of the
143                                  * significand in the first word of a
144                                  * double. */
145 #define SIG_MASK        (((Tcl_WideUInt) HI_ORDER_SIG_MASK << 32) \
146                         | 0xFFFFFFFF)
147                                 /* Mask for the 52-bit significand. */
148 #define FP_PRECISION    53      /* Number of bits of significand plus the
149                                  * hidden bit. */
150 #define EXPONENT_BIAS   0x3FF   /* Bias of the exponent 0. */
151
152 /*
153  * Derived quantities.
154  */
155
156 #define TEN_PMAX        22      /* floor(FP_PRECISION*log(2)/log(5)) */
157 #define QUICK_MAX       14      /* floor((FP_PRECISION-1)*log(2)/log(10))-1 */
158 #define BLETCH          0x10    /* Highest power of two that is greater than
159                                  * DBL_MAX_10_EXP, divided by 16. */
160 #define DIGIT_GROUP     8       /* floor(MP_DIGIT_BIT*log(2)/log(10)) */
161
162 /*
163  * Union used to dismantle floating point numbers.
164  */
165
166 typedef union Double {
167     struct {
168 #ifdef WORDS_BIGENDIAN
169         int word0;
170         int word1;
171 #else
172         int word1;
173         int word0;
174 #endif
175     } w;
176     double d;
177     Tcl_WideUInt q;
178 } Double;
179
180 static int maxpow10_wide;       /* The powers of ten that can be represented
181                                  * exactly as wide integers. */
182 static Tcl_WideUInt *pow10_wide;
183 #define MAXPOW  22
184 static double pow10vals[MAXPOW+1];
185                                 /* The powers of ten that can be represented
186                                  * exactly as IEEE754 doubles. */
187 static int mmaxpow;             /* Largest power of ten that can be
188                                  * represented exactly in a 'double'. */
189 static int log10_DIGIT_MAX;     /* The number of decimal digits that fit in an
190                                  * mp_digit. */
191 static int log2FLT_RADIX;       /* Logarithm of the floating point radix. */
192 static int mantBits;            /* Number of bits in a double's significand */
193 static mp_int pow5[9];          /* Table of powers of 5**(2**n), up to
194                                  * 5**256 */
195 static double tiny = 0.0;       /* The smallest representable double. */
196 static int maxDigits;           /* The maximum number of digits to the left of
197                                  * the decimal point of a double. */
198 static int minDigits;           /* The maximum number of digits to the right
199                                  * of the decimal point in a double. */
200 static const double pow_10_2_n[] = {    /* Inexact higher powers of ten. */
201     1.0,
202     100.0,
203     10000.0,
204     1.0e+8,
205     1.0e+16,
206     1.0e+32,
207     1.0e+64,
208     1.0e+128,
209     1.0e+256
210 };
211
212 static int n770_fp;             /* Flag is 1 on Nokia N770 floating point.
213                                  * Nokia's floating point has the words
214                                  * reversed: if big-endian is 7654 3210,
215                                  * and little-endian is       0123 4567,
216                                  * then Nokia's FP is         4567 0123;
217                                  * little-endian within the 32-bit words but
218                                  * big-endian between them. */
219
220 /*
221  * Table of powers of 5 that are small enough to fit in an mp_digit.
222  */
223
224 static const mp_digit dpow5[13] = {
225                1,              5,             25,            125,
226              625,           3125,          15625,          78125,
227           390625,        1953125,        9765625,       48828125,
228        244140625
229 };
230
231 /*
232  * Table of powers: pow5_13[n] = 5**(13*2**(n+1))
233  */
234
235 static mp_int pow5_13[5];       /* Table of powers: 5**13, 5**26, 5**52,
236                                  * 5**104, 5**208 */
237 static const double tens[] = {
238     1e00, 1e01, 1e02, 1e03, 1e04, 1e05, 1e06, 1e07, 1e08, 1e09,
239     1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
240     1e20, 1e21, 1e22
241 };
242
243 static const int itens [] = {
244     1,
245     10,
246     100,
247     1000,
248     10000,
249     100000,
250     1000000,
251     10000000,
252     100000000
253 };
254
255 static const double bigtens[] = {
256     1e016, 1e032, 1e064, 1e128, 1e256
257 };
258 #define N_BIGTENS 5
259
260 static const int log2pow5[27] = {
261     01,  3,  5,  7, 10, 12, 14, 17, 19, 21,
262     24, 26, 28, 31, 33, 35, 38, 40, 42, 45,
263     47, 49, 52, 54, 56, 59, 61
264 };
265 #define N_LOG2POW5 27
266
267 static const Tcl_WideUInt wuipow5[27] = {
268     (Tcl_WideUInt) 1,           /* 5**0 */
269     (Tcl_WideUInt) 5,
270     (Tcl_WideUInt) 25,
271     (Tcl_WideUInt) 125,
272     (Tcl_WideUInt) 625,
273     (Tcl_WideUInt) 3125,        /* 5**5 */
274     (Tcl_WideUInt) 3125*5,
275     (Tcl_WideUInt) 3125*25,
276     (Tcl_WideUInt) 3125*125,
277     (Tcl_WideUInt) 3125*625,
278     (Tcl_WideUInt) 3125*3125,   /* 5**10 */
279     (Tcl_WideUInt) 3125*3125*5,
280     (Tcl_WideUInt) 3125*3125*25,
281     (Tcl_WideUInt) 3125*3125*125,
282     (Tcl_WideUInt) 3125*3125*625,
283     (Tcl_WideUInt) 3125*3125*3125, /* 5**15 */
284     (Tcl_WideUInt) 3125*3125*3125*5,
285     (Tcl_WideUInt) 3125*3125*3125*25,
286     (Tcl_WideUInt) 3125*3125*3125*125,
287     (Tcl_WideUInt) 3125*3125*3125*625,
288     (Tcl_WideUInt) 3125*3125*3125*3125, /* 5**20 */
289     (Tcl_WideUInt) 3125*3125*3125*3125*5,
290     (Tcl_WideUInt) 3125*3125*3125*3125*25,
291     (Tcl_WideUInt) 3125*3125*3125*3125*125,
292     (Tcl_WideUInt) 3125*3125*3125*3125*625,
293     (Tcl_WideUInt) 3125*3125*3125*3125*3125,  /* 5**25 */
294     (Tcl_WideUInt) 3125*3125*3125*3125*3125*5 /* 5**26 */
295 };
296
297 /*
298  * Static functions defined in this file.
299  */
300
301 static int              AccumulateDecimalDigit(unsigned, int,
302                             Tcl_WideUInt *, mp_int *, int);
303 static double           MakeHighPrecisionDouble(int signum,
304                             mp_int *significand, int nSigDigs, long exponent);
305 static double           MakeLowPrecisionDouble(int signum,
306                             Tcl_WideUInt significand, int nSigDigs,
307                             long exponent);
308 #ifdef IEEE_FLOATING_POINT
309 static double           MakeNaN(int signum, Tcl_WideUInt tag);
310 #endif
311 static double           RefineApproximation(double approx,
312                             mp_int *exactSignificand, int exponent);
313 static void             MulPow5(mp_int *, unsigned, mp_int *);
314 static int              NormalizeRightward(Tcl_WideUInt *);
315 static int              RequiredPrecision(Tcl_WideUInt);
316 static void             DoubleToExpAndSig(double, Tcl_WideUInt *, int *,
317                             int *);
318 static void             TakeAbsoluteValue(Double *, int *);
319 static char *           FormatInfAndNaN(Double *, int *, char **);
320 static char *           FormatZero(int *, char **);
321 static int              ApproximateLog10(Tcl_WideUInt, int, int);
322 static int              BetterLog10(double, int, int *);
323 static void             ComputeScale(int, int, int *, int *, int *, int *);
324 static void             SetPrecisionLimits(int, int, int *, int *, int *,
325                             int *);
326 static char *           BumpUp(char *, char *, int *);
327 static int              AdjustRange(double *, int);
328 static char *           ShorteningQuickFormat(double, int, int, double,
329                             char *, int *);
330 static char *           StrictQuickFormat(double, int, int, double,
331                             char *, int *);
332 static char *           QuickConversion(double, int, int, int, int, int, int,
333                             int *, char **);
334 static void             CastOutPowersOf2(int *, int *, int *);
335 static char *           ShorteningInt64Conversion(Double *, int, Tcl_WideUInt,
336                             int, int, int, int, int, int, int, int, int,
337                             int, int, int *, char **);
338 static char *           StrictInt64Conversion(Double *, int, Tcl_WideUInt,
339                             int, int, int, int, int, int,
340                             int, int, int *, char **);
341 static int              ShouldBankerRoundUpPowD(mp_int *, int, int);
342 static int              ShouldBankerRoundUpToNextPowD(mp_int *, mp_int *,
343                             int, int, int, mp_int *);
344 static char *           ShorteningBignumConversionPowD(Double *dPtr,
345                             int convType, Tcl_WideUInt bw, int b2, int b5,
346                             int m2plus, int m2minus, int m5,
347                             int sd, int k, int len,
348                             int ilim, int ilim1, int *decpt,
349                             char **endPtr);
350 static char *           StrictBignumConversionPowD(Double *dPtr, int convType,
351                             Tcl_WideUInt bw, int b2, int b5,
352                             int sd, int k, int len,
353                             int ilim, int ilim1, int *decpt,
354                             char **endPtr);
355 static int              ShouldBankerRoundUp(mp_int *, mp_int *, int);
356 static int              ShouldBankerRoundUpToNext(mp_int *, mp_int *,
357                             mp_int *, int, int, mp_int *);
358 static char *           ShorteningBignumConversion(Double *dPtr, int convType,
359                             Tcl_WideUInt bw, int b2,
360                             int m2plus, int m2minus,
361                             int s2, int s5, int k, int len,
362                             int ilim, int ilim1, int *decpt,
363                             char **endPtr);
364 static char *           StrictBignumConversion(Double *dPtr, int convType,
365                             Tcl_WideUInt bw, int b2,
366                             int s2, int s5, int k, int len,
367                             int ilim, int ilim1, int *decpt,
368                             char **endPtr);
369 static double           BignumToBiasedFrExp(const mp_int *big, int *machexp);
370 static double           Pow10TimesFrExp(int exponent, double fraction,
371                             int *machexp);
372 static double           SafeLdExp(double fraction, int exponent);
373 #ifdef IEEE_FLOATING_POINT
374 static Tcl_WideUInt     Nokia770Twiddle(Tcl_WideUInt w);
375 #endif
376 \f
377 /*
378  *----------------------------------------------------------------------
379  *
380  * TclParseNumber --
381  *
382  *      Scans bytes, interpreted as characters in Tcl's internal encoding, and
383  *      parses the longest prefix that is the string representation of a
384  *      number in a format recognized by Tcl.
385  *
386  *      The arguments bytes, numBytes, and objPtr are the inputs which
387  *      determine the string to be parsed. If bytes is non-NULL, it points to
388  *      the first byte to be scanned. If bytes is NULL, then objPtr must be
389  *      non-NULL, and the string representation of objPtr will be scanned
390  *      (generated first, if necessary). The numBytes argument determines the
391  *      number of bytes to be scanned. If numBytes is negative, the first NUL
392  *      byte encountered will terminate the scan. If numBytes is non-negative,
393  *      then no more than numBytes bytes will be scanned.
394  *
395  *      The argument flags is an input that controls the numeric formats
396  *      recognized by the parser. The flag bits are:
397  *
398  *      - TCL_PARSE_INTEGER_ONLY:       accept only integer values; reject
399  *              strings that denote floating point values (or accept only the
400  *              leading portion of them that are integer values).
401  *      - TCL_PARSE_SCAN_PREFIXES:      ignore the prefixes 0b and 0o that are
402  *              not part of the [scan] command's vocabulary. Use only in
403  *              combination with TCL_PARSE_INTEGER_ONLY.
404  *      - TCL_PARSE_BINARY_ONLY:        parse only in the binary format, whether
405  *              or not a prefix is present that would lead to binary parsing.
406  *              Use only in combination with TCL_PARSE_INTEGER_ONLY.
407  *      - TCL_PARSE_OCTAL_ONLY:         parse only in the octal format, whether
408  *              or not a prefix is present that would lead to octal parsing.
409  *              Use only in combination with TCL_PARSE_INTEGER_ONLY.
410  *      - TCL_PARSE_HEXADECIMAL_ONLY:   parse only in the hexadecimal format,
411  *              whether or not a prefix is present that would lead to
412  *              hexadecimal parsing. Use only in combination with
413  *              TCL_PARSE_INTEGER_ONLY.
414  *      - TCL_PARSE_DECIMAL_ONLY:       parse only in the decimal format, no
415  *              matter whether a 0 prefix would normally force a different
416  *              base.
417  *      - TCL_PARSE_NO_WHITESPACE:      reject any leading/trailing whitespace
418  *
419  *      The arguments interp and expected are inputs that control error
420  *      message generation. If interp is NULL, no error message will be
421  *      generated. If interp is non-NULL, then expected must also be non-NULL.
422  *      When TCL_ERROR is returned, an error message will be left in the
423  *      result of interp, and the expected argument will appear in the error
424  *      message as the thing TclParseNumber expected, but failed to find in
425  *      the string.
426  *
427  *      The arguments objPtr and endPtrPtr as well as the return code are the
428  *      outputs.
429  *
430  *      When the parser cannot find any prefix of the string that matches a
431  *      format it is looking for, TCL_ERROR is returned and an error message
432  *      may be generated and returned as described above. The contents of
433  *      objPtr will not be changed. If endPtrPtr is non-NULL, a pointer to the
434  *      character in the string that terminated the scan will be written to
435  *      *endPtrPtr.
436  *
437  *      When the parser determines that the entire string matches a format it
438  *      is looking for, TCL_OK is returned, and if objPtr is non-NULL, then
439  *      the internal rep and Tcl_ObjType of objPtr are set to the "canonical"
440  *      numeric value that matches the scanned string. If endPtrPtr is not
441  *      NULL, a pointer to the end of the string will be written to *endPtrPtr
442  *      (that is, either bytes+numBytes or a pointer to a terminating NUL
443  *      byte).
444  *
445  *      When the parser determines that a partial string matches a format it
446  *      is looking for, the value of endPtrPtr determines what happens:
447  *
448  *      - If endPtrPtr is NULL, then TCL_ERROR is returned, with error message
449  *              generation as above.
450  *
451  *      - If endPtrPtr is non-NULL, then TCL_OK is returned and objPtr
452  *              internals are set as above. Also, a pointer to the first
453  *              character following the parsed numeric string is written to
454  *              *endPtrPtr.
455  *
456  *      In some cases where the string being scanned is the string rep of
457  *      objPtr, this routine can leave objPtr in an inconsistent state where
458  *      its string rep and its internal rep do not agree. In these cases the
459  *      internal rep will be in agreement with only some substring of the
460  *      string rep. This might happen if the caller passes in a non-NULL bytes
461  *      value that points somewhere into the string rep. It might happen if
462  *      the caller passes in a numBytes value that limits the scan to only a
463  *      prefix of the string rep. Or it might happen if a non-NULL value of
464  *      endPtrPtr permits a TCL_OK return from only a partial string match. It
465  *      is the responsibility of the caller to detect and correct such
466  *      inconsistencies when they can and do arise.
467  *
468  * Results:
469  *      Returns a standard Tcl result.
470  *
471  * Side effects:
472  *      The string representaton of objPtr may be generated.
473  *
474  *      The internal representation and Tcl_ObjType of objPtr may be changed.
475  *      This may involve allocation and/or freeing of memory.
476  *
477  *----------------------------------------------------------------------
478  */
479
480 int
481 TclParseNumber(
482     Tcl_Interp *interp,         /* Used for error reporting. May be NULL. */
483     Tcl_Obj *objPtr,            /* Object to receive the internal rep. */
484     const char *expected,       /* Description of the type of number the
485                                  * caller expects to be able to parse
486                                  * ("integer", "boolean value", etc.). */
487     const char *bytes,          /* Pointer to the start of the string to
488                                  * scan. */
489     int numBytes,               /* Maximum number of bytes to scan, see
490                                  * above. */
491     const char **endPtrPtr,     /* Place to store pointer to the character
492                                  * that terminated the scan. */
493     int flags)                  /* Flags governing the parse. */
494 {
495     enum State {
496         INITIAL, SIGNUM, ZERO, ZERO_X,
497         ZERO_O, ZERO_B, BINARY,
498         HEXADECIMAL, OCTAL, BAD_OCTAL, DECIMAL,
499         LEADING_RADIX_POINT, FRACTION,
500         EXPONENT_START, EXPONENT_SIGNUM, EXPONENT,
501         sI, sIN, sINF, sINFI, sINFIN, sINFINI, sINFINIT, sINFINITY
502 #ifdef IEEE_FLOATING_POINT
503         , sN, sNA, sNAN, sNANPAREN, sNANHEX, sNANFINISH
504 #endif
505     } state = INITIAL;
506     enum State acceptState = INITIAL;
507
508     int signum = 0;             /* Sign of the number being parsed. */
509     Tcl_WideUInt significandWide = 0;
510                                 /* Significand of the number being parsed (if
511                                  * no overflow). */
512     mp_int significandBig;      /* Significand of the number being parsed (if
513                                  * it overflows significandWide). */
514     int significandOverflow = 0;/* Flag==1 iff significandBig is used. */
515     Tcl_WideUInt octalSignificandWide = 0;
516                                 /* Significand of an octal number; needed
517                                  * because we don't know whether a number with
518                                  * a leading zero is octal or decimal until
519                                  * we've scanned forward to a '.' or 'e'. */
520     mp_int octalSignificandBig; /* Significand of octal number once
521                                  * octalSignificandWide overflows. */
522     int octalSignificandOverflow = 0;
523                                 /* Flag==1 if octalSignificandBig is used. */
524     int numSigDigs = 0;         /* Number of significant digits in the decimal
525                                  * significand. */
526     int numTrailZeros = 0;      /* Number of trailing zeroes at the current
527                                  * point in the parse. */
528     int numDigitsAfterDp = 0;   /* Number of digits scanned after the decimal
529                                  * point. */
530     int exponentSignum = 0;     /* Signum of the exponent of a floating point
531                                  * number. */
532     long exponent = 0;          /* Exponent of a floating point number. */
533     const char *p;              /* Pointer to next character to scan. */
534     size_t len;                 /* Number of characters remaining after p. */
535     const char *acceptPoint;    /* Pointer to position after last character in
536                                  * an acceptable number. */
537     size_t acceptLen;           /* Number of characters following that
538                                  * point. */
539     int status = TCL_OK;        /* Status to return to caller. */
540     char d = 0;                 /* Last hexadecimal digit scanned; initialized
541                                  * to avoid a compiler warning. */
542     int shift = 0;              /* Amount to shift when accumulating binary */
543     int explicitOctal = 0;
544
545 #define ALL_BITS        (~(Tcl_WideUInt)0)
546 #define MOST_BITS       (ALL_BITS >> 1)
547
548     /*
549      * Initialize bytes to start of the object's string rep if the caller
550      * didn't pass anything else.
551      */
552
553     if (bytes == NULL) {
554         bytes = TclGetString(objPtr);
555     }
556
557     p = bytes;
558     len = numBytes;
559     acceptPoint = p;
560     acceptLen = len;
561     while (1) {
562         char c = len ? *p : '\0';
563         switch (state) {
564
565         case INITIAL:
566             /*
567              * Initial state. Acceptable characters are +, -, digits, period,
568              * I, N, and whitespace.
569              */
570
571             if (TclIsSpaceProcM(c)) {
572                 if (flags & TCL_PARSE_NO_WHITESPACE) {
573                     goto endgame;
574                 }
575                 break;
576             } else if (c == '+') {
577                 state = SIGNUM;
578                 break;
579             } else if (c == '-') {
580                 signum = 1;
581                 state = SIGNUM;
582                 break;
583             }
584             /* FALLTHROUGH */
585
586         case SIGNUM:
587             /*
588              * Scanned a leading + or -. Acceptable characters are digits,
589              * period, I, and N.
590              */
591
592             if (c == '0') {
593                 if (flags & TCL_PARSE_DECIMAL_ONLY) {
594                     state = DECIMAL;
595                 } else {
596                     state = ZERO;
597                 }
598                 break;
599             } else if (flags & TCL_PARSE_HEXADECIMAL_ONLY) {
600                 goto zerox;
601             } else if (flags & TCL_PARSE_BINARY_ONLY) {
602                 goto zerob;
603             } else if (flags & TCL_PARSE_OCTAL_ONLY) {
604                 goto zeroo;
605             } else if (isdigit(UCHAR(c))) {
606                 significandWide = c - '0';
607                 numSigDigs = 1;
608                 state = DECIMAL;
609                 break;
610             } else if (flags & TCL_PARSE_INTEGER_ONLY) {
611                 goto endgame;
612             } else if (c == '.') {
613                 state = LEADING_RADIX_POINT;
614                 break;
615             } else if (c == 'I' || c == 'i') {
616                 state = sI;
617                 break;
618 #ifdef IEEE_FLOATING_POINT
619             } else if (c == 'N' || c == 'n') {
620                 state = sN;
621                 break;
622 #endif
623             }
624             goto endgame;
625
626         case ZERO:
627             /*
628              * Scanned a leading zero (perhaps with a + or -). Acceptable
629              * inputs are digits, period, X, b, and E. If 8 or 9 is
630              * encountered, the number can't be octal. This state and the
631              * OCTAL state differ only in whether they recognize 'X' and 'b'.
632              */
633
634             acceptState = state;
635             acceptPoint = p;
636             acceptLen = len;
637             if (c == 'x' || c == 'X') {
638                 if (flags & (TCL_PARSE_OCTAL_ONLY|TCL_PARSE_BINARY_ONLY)) {
639                     goto endgame;
640                 }
641                 state = ZERO_X;
642                 break;
643             }
644             if (flags & TCL_PARSE_HEXADECIMAL_ONLY) {
645                 goto zerox;
646             }
647             if (flags & TCL_PARSE_SCAN_PREFIXES) {
648                 goto zeroo;
649             }
650             if (c == 'b' || c == 'B') {
651                 if (flags & TCL_PARSE_OCTAL_ONLY) {
652                     goto endgame;
653                 }
654                 state = ZERO_B;
655                 break;
656             }
657             if (flags & TCL_PARSE_BINARY_ONLY) {
658                 goto zerob;
659             }
660             if (c == 'o' || c == 'O') {
661                 explicitOctal = 1;
662                 state = ZERO_O;
663                 break;
664             }
665 #ifdef KILL_OCTAL
666             goto decimal;
667 #endif
668             /* FALLTHROUGH */
669
670         case OCTAL:
671             /*
672              * Scanned an optional + or -, followed by a string of octal
673              * digits. Acceptable inputs are more digits, period, or E. If 8
674              * or 9 is encountered, commit to floating point.
675              */
676
677             acceptState = state;
678             acceptPoint = p;
679             acceptLen = len;
680             /* FALLTHROUGH */
681         case ZERO_O:
682         zeroo:
683             if (c == '0') {
684                 numTrailZeros++;
685                 state = OCTAL;
686                 break;
687             } else if (c >= '1' && c <= '7') {
688                 if (objPtr != NULL) {
689                     shift = 3 * (numTrailZeros + 1);
690                     significandOverflow = AccumulateDecimalDigit(
691                             (unsigned)(c-'0'), numTrailZeros,
692                             &significandWide, &significandBig,
693                             significandOverflow);
694
695                     if (!octalSignificandOverflow) {
696                         /*
697                          * Shifting by more bits than are in the value being
698                          * shifted is at least de facto nonportable. Check for
699                          * too large shifts first.
700                          */
701
702                         if ((octalSignificandWide != 0)
703                                 && (((size_t)shift >=
704                                         CHAR_BIT*sizeof(Tcl_WideUInt))
705                                 || (octalSignificandWide >
706                                         (~(Tcl_WideUInt)0 >> shift)))) {
707                             octalSignificandOverflow = 1;
708                             TclBNInitBignumFromWideUInt(&octalSignificandBig,
709                                     octalSignificandWide);
710                         }
711                     }
712                     if (!octalSignificandOverflow) {
713                         octalSignificandWide =
714                                 (octalSignificandWide << shift) + (c - '0');
715                     } else {
716                         mp_mul_2d(&octalSignificandBig, shift,
717                                 &octalSignificandBig);
718                         mp_add_d(&octalSignificandBig, (mp_digit)(c - '0'),
719                                 &octalSignificandBig);
720                     }
721                 }
722                 if (numSigDigs != 0) {
723                     numSigDigs += numTrailZeros+1;
724                 } else {
725                     numSigDigs = 1;
726                 }
727                 numTrailZeros = 0;
728                 state = OCTAL;
729                 break;
730             }
731             /* FALLTHROUGH */
732
733         case BAD_OCTAL:
734             if (explicitOctal) {
735                 /*
736                  * No forgiveness for bad digits in explicitly octal numbers.
737                  */
738
739                 goto endgame;
740             }
741             if (flags & TCL_PARSE_INTEGER_ONLY) {
742                 /*
743                  * No seeking floating point when parsing only integer.
744                  */
745
746                 goto endgame;
747             }
748 #ifndef KILL_OCTAL
749
750             /*
751              * Scanned a number with a leading zero that contains an 8, 9,
752              * radix point or E. This is an invalid octal number, but might
753              * still be floating point.
754              */
755
756             if (c == '0') {
757                 numTrailZeros++;
758                 state = BAD_OCTAL;
759                 break;
760             } else if (isdigit(UCHAR(c))) {
761                 if (objPtr != NULL) {
762                     significandOverflow = AccumulateDecimalDigit(
763                             (unsigned)(c-'0'), numTrailZeros,
764                             &significandWide, &significandBig,
765                             significandOverflow);
766                 }
767                 if (numSigDigs != 0) {
768                     numSigDigs += (numTrailZeros + 1);
769                 } else {
770                     numSigDigs = 1;
771                 }
772                 numTrailZeros = 0;
773                 state = BAD_OCTAL;
774                 break;
775             } else if (c == '.') {
776                 state = FRACTION;
777                 break;
778             } else if (c == 'E' || c == 'e') {
779                 state = EXPONENT_START;
780                 break;
781             }
782 #endif
783             goto endgame;
784
785             /*
786              * Scanned 0x. If state is HEXADECIMAL, scanned at least one
787              * character following the 0x. The only acceptable inputs are
788              * hexadecimal digits.
789              */
790
791         case HEXADECIMAL:
792             acceptState = state;
793             acceptPoint = p;
794             acceptLen = len;
795             /* FALLTHROUGH */
796
797         case ZERO_X:
798         zerox:
799             if (c == '0') {
800                 numTrailZeros++;
801                 state = HEXADECIMAL;
802                 break;
803             } else if (isdigit(UCHAR(c))) {
804                 d = (c-'0');
805             } else if (c >= 'A' && c <= 'F') {
806                 d = (c-'A'+10);
807             } else if (c >= 'a' && c <= 'f') {
808                 d = (c-'a'+10);
809             } else {
810                 goto endgame;
811             }
812             if (objPtr != NULL) {
813                 shift = 4 * (numTrailZeros + 1);
814                 if (!significandOverflow) {
815                     /*
816                      * Shifting by more bits than are in the value being
817                      * shifted is at least de facto nonportable. Check for too
818                      * large shifts first.
819                      */
820
821                     if (significandWide != 0 &&
822                             ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
823                             significandWide > (~(Tcl_WideUInt)0 >> shift))) {
824                         significandOverflow = 1;
825                         TclBNInitBignumFromWideUInt(&significandBig,
826                                 significandWide);
827                     }
828                 }
829                 if (!significandOverflow) {
830                     significandWide = (significandWide << shift) + d;
831                 } else {
832                     mp_mul_2d(&significandBig, shift, &significandBig);
833                     mp_add_d(&significandBig, (mp_digit) d, &significandBig);
834                 }
835             }
836             numTrailZeros = 0;
837             state = HEXADECIMAL;
838             break;
839
840         case BINARY:
841             acceptState = state;
842             acceptPoint = p;
843             acceptLen = len;
844             /* FALLTHRU */
845         case ZERO_B:
846         zerob:
847             if (c == '0') {
848                 numTrailZeros++;
849                 state = BINARY;
850                 break;
851             } else if (c != '1') {
852                 goto endgame;
853             }
854             if (objPtr != NULL) {
855                 shift = numTrailZeros + 1;
856                 if (!significandOverflow) {
857                     /*
858                      * Shifting by more bits than are in the value being
859                      * shifted is at least de facto nonportable. Check for too
860                      * large shifts first.
861                      */
862
863                     if (significandWide != 0 &&
864                             ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
865                             significandWide > (~(Tcl_WideUInt)0 >> shift))) {
866                         significandOverflow = 1;
867                         TclBNInitBignumFromWideUInt(&significandBig,
868                                 significandWide);
869                     }
870                 }
871                 if (!significandOverflow) {
872                     significandWide = (significandWide << shift) + 1;
873                 } else {
874                     mp_mul_2d(&significandBig, shift, &significandBig);
875                     mp_add_d(&significandBig, (mp_digit) 1, &significandBig);
876                 }
877             }
878             numTrailZeros = 0;
879             state = BINARY;
880             break;
881
882         case DECIMAL:
883             /*
884              * Scanned an optional + or - followed by a string of decimal
885              * digits.
886              */
887
888 #ifdef KILL_OCTAL
889         decimal:
890 #endif
891             acceptState = state;
892             acceptPoint = p;
893             acceptLen = len;
894             if (c == '0') {
895                 numTrailZeros++;
896                 state = DECIMAL;
897                 break;
898             } else if (isdigit(UCHAR(c))) {
899                 if (objPtr != NULL) {
900                     significandOverflow = AccumulateDecimalDigit(
901                             (unsigned)(c - '0'), numTrailZeros,
902                             &significandWide, &significandBig,
903                             significandOverflow);
904                 }
905                 numSigDigs += numTrailZeros+1;
906                 numTrailZeros = 0;
907                 state = DECIMAL;
908                 break;
909             } else if (flags & TCL_PARSE_INTEGER_ONLY) {
910                 goto endgame;
911             } else if (c == '.') {
912                 state = FRACTION;
913                 break;
914             } else if (c == 'E' || c == 'e') {
915                 state = EXPONENT_START;
916                 break;
917             }
918             goto endgame;
919
920             /*
921              * Found a decimal point. If no digits have yet been scanned, E is
922              * not allowed; otherwise, it introduces the exponent. If at least
923              * one digit has been found, we have a possible complete number.
924              */
925
926         case FRACTION:
927             acceptState = state;
928             acceptPoint = p;
929             acceptLen = len;
930             if (c == 'E' || c=='e') {
931                 state = EXPONENT_START;
932                 break;
933             }
934             /* FALLTHROUGH */
935
936         case LEADING_RADIX_POINT:
937             if (c == '0') {
938                 numDigitsAfterDp++;
939                 numTrailZeros++;
940                 state = FRACTION;
941                 break;
942             } else if (isdigit(UCHAR(c))) {
943                 numDigitsAfterDp++;
944                 if (objPtr != NULL) {
945                     significandOverflow = AccumulateDecimalDigit(
946                             (unsigned)(c-'0'), numTrailZeros,
947                             &significandWide, &significandBig,
948                             significandOverflow);
949                 }
950                 if (numSigDigs != 0) {
951                     numSigDigs += numTrailZeros+1;
952                 } else {
953                     numSigDigs = 1;
954                 }
955                 numTrailZeros = 0;
956                 state = FRACTION;
957                 break;
958             }
959             goto endgame;
960
961         case EXPONENT_START:
962             /*
963              * Scanned the E at the start of an exponent. Make sure a legal
964              * character follows before using the C library strtol routine,
965              * which allows whitespace.
966              */
967
968             if (c == '+') {
969                 state = EXPONENT_SIGNUM;
970                 break;
971             } else if (c == '-') {
972                 exponentSignum = 1;
973                 state = EXPONENT_SIGNUM;
974                 break;
975             }
976             /* FALLTHROUGH */
977
978         case EXPONENT_SIGNUM:
979             /*
980              * Found the E at the start of the exponent, followed by a sign
981              * character.
982              */
983
984             if (isdigit(UCHAR(c))) {
985                 exponent = c - '0';
986                 state = EXPONENT;
987                 break;
988             }
989             goto endgame;
990
991         case EXPONENT:
992             /*
993              * Found an exponent with at least one digit. Accumulate it,
994              * making sure to hard-pin it to LONG_MAX on overflow.
995              */
996
997             acceptState = state;
998             acceptPoint = p;
999             acceptLen = len;
1000             if (isdigit(UCHAR(c))) {
1001                 if (exponent < (LONG_MAX - 9) / 10) {
1002                     exponent = 10 * exponent + (c - '0');
1003                 } else {
1004                     exponent = LONG_MAX;
1005                 }
1006                 state = EXPONENT;
1007                 break;
1008             }
1009             goto endgame;
1010
1011             /*
1012              * Parse out INFINITY by simply spelling it out. INF is accepted
1013              * as an abbreviation; other prefices are not.
1014              */
1015
1016         case sI:
1017             if (c == 'n' || c == 'N') {
1018                 state = sIN;
1019                 break;
1020             }
1021             goto endgame;
1022         case sIN:
1023             if (c == 'f' || c == 'F') {
1024                 state = sINF;
1025                 break;
1026             }
1027             goto endgame;
1028         case sINF:
1029             acceptState = state;
1030             acceptPoint = p;
1031             acceptLen = len;
1032             if (c == 'i' || c == 'I') {
1033                 state = sINFI;
1034                 break;
1035             }
1036             goto endgame;
1037         case sINFI:
1038             if (c == 'n' || c == 'N') {
1039                 state = sINFIN;
1040                 break;
1041             }
1042             goto endgame;
1043         case sINFIN:
1044             if (c == 'i' || c == 'I') {
1045                 state = sINFINI;
1046                 break;
1047             }
1048             goto endgame;
1049         case sINFINI:
1050             if (c == 't' || c == 'T') {
1051                 state = sINFINIT;
1052                 break;
1053             }
1054             goto endgame;
1055         case sINFINIT:
1056             if (c == 'y' || c == 'Y') {
1057                 state = sINFINITY;
1058                 break;
1059             }
1060             goto endgame;
1061
1062             /*
1063              * Parse NaN's.
1064              */
1065 #ifdef IEEE_FLOATING_POINT
1066         case sN:
1067             if (c == 'a' || c == 'A') {
1068                 state = sNA;
1069                 break;
1070             }
1071             goto endgame;
1072         case sNA:
1073             if (c == 'n' || c == 'N') {
1074                 state = sNAN;
1075                 break;
1076             }
1077             goto endgame;
1078         case sNAN:
1079             acceptState = state;
1080             acceptPoint = p;
1081             acceptLen = len;
1082             if (c == '(') {
1083                 state = sNANPAREN;
1084                 break;
1085             }
1086             goto endgame;
1087
1088             /*
1089              * Parse NaN(hexdigits)
1090              */
1091         case sNANHEX:
1092             if (c == ')') {
1093                 state = sNANFINISH;
1094                 break;
1095             }
1096             /* FALLTHROUGH */
1097         case sNANPAREN:
1098             if (TclIsSpaceProcM(c)) {
1099                 break;
1100             }
1101             if (numSigDigs < 13) {
1102                 if (c >= '0' && c <= '9') {
1103                     d = c - '0';
1104                 } else if (c >= 'a' && c <= 'f') {
1105                     d = 10 + c - 'a';
1106                 } else if (c >= 'A' && c <= 'F') {
1107                     d = 10 + c - 'A';
1108                 } else {
1109                     goto endgame;
1110                 }
1111                 numSigDigs++;
1112                 significandWide = (significandWide << 4) + d;
1113                 state = sNANHEX;
1114                 break;
1115             }
1116             goto endgame;
1117         case sNANFINISH:
1118 #endif
1119
1120         case sINFINITY:
1121             acceptState = state;
1122             acceptPoint = p;
1123             acceptLen = len;
1124             goto endgame;
1125         }
1126         p++;
1127         len--;
1128     }
1129
1130   endgame:
1131     if (acceptState == INITIAL) {
1132         /*
1133          * No numeric string at all found.
1134          */
1135
1136         status = TCL_ERROR;
1137         if (endPtrPtr != NULL) {
1138             *endPtrPtr = p;
1139         }
1140     } else {
1141         /*
1142          * Back up to the last accepting state in the lexer.
1143          */
1144
1145         p = acceptPoint;
1146         len = acceptLen;
1147         if (!(flags & TCL_PARSE_NO_WHITESPACE)) {
1148             /*
1149              * Accept trailing whitespace.
1150              */
1151
1152             while (len != 0 && TclIsSpaceProcM(*p)) {
1153                 p++;
1154                 len--;
1155             }
1156         }
1157         if (endPtrPtr == NULL) {
1158             if ((len != 0) && ((numBytes > 0) || (*p != '\0'))) {
1159                 status = TCL_ERROR;
1160             }
1161         } else {
1162             *endPtrPtr = p;
1163         }
1164     }
1165
1166     /*
1167      * Generate and store the appropriate internal rep.
1168      */
1169
1170     if (status == TCL_OK && objPtr != NULL) {
1171         TclFreeIntRep(objPtr);
1172         switch (acceptState) {
1173         case SIGNUM:
1174         case BAD_OCTAL:
1175         case ZERO_X:
1176         case ZERO_O:
1177         case ZERO_B:
1178         case LEADING_RADIX_POINT:
1179         case EXPONENT_START:
1180         case EXPONENT_SIGNUM:
1181         case sI:
1182         case sIN:
1183         case sINFI:
1184         case sINFIN:
1185         case sINFINI:
1186         case sINFINIT:
1187 #ifdef IEEE_FLOATING_POINT
1188         case sN:
1189         case sNA:
1190         case sNANPAREN:
1191         case sNANHEX:
1192 #endif
1193             Tcl_Panic("TclParseNumber: bad acceptState %d parsing '%s'",
1194                     acceptState, bytes);
1195         case BINARY:
1196             shift = numTrailZeros;
1197             if (!significandOverflow && significandWide != 0 &&
1198                     ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
1199                     significandWide > (MOST_BITS + signum) >> shift)) {
1200                 significandOverflow = 1;
1201                 TclBNInitBignumFromWideUInt(&significandBig, significandWide);
1202             }
1203             if (shift) {
1204                 if (!significandOverflow) {
1205                     significandWide <<= shift;
1206                 } else {
1207                     mp_mul_2d(&significandBig, shift, &significandBig);
1208                 }
1209             }
1210             goto returnInteger;
1211
1212         case HEXADECIMAL:
1213             /*
1214              * Returning a hex integer. Final scaling step.
1215              */
1216
1217             shift = 4 * numTrailZeros;
1218             if (!significandOverflow && significandWide !=0 &&
1219                     ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
1220                     significandWide > (MOST_BITS + signum) >> shift)) {
1221                 significandOverflow = 1;
1222                 TclBNInitBignumFromWideUInt(&significandBig, significandWide);
1223             }
1224             if (shift) {
1225                 if (!significandOverflow) {
1226                     significandWide <<= shift;
1227                 } else {
1228                     mp_mul_2d(&significandBig, shift, &significandBig);
1229                 }
1230             }
1231             goto returnInteger;
1232
1233         case OCTAL:
1234             /*
1235              * Returning an octal integer. Final scaling step.
1236              */
1237
1238             shift = 3 * numTrailZeros;
1239             if (!octalSignificandOverflow && octalSignificandWide != 0 &&
1240                     ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
1241                     octalSignificandWide > (MOST_BITS + signum) >> shift)) {
1242                 octalSignificandOverflow = 1;
1243                 TclBNInitBignumFromWideUInt(&octalSignificandBig,
1244                         octalSignificandWide);
1245             }
1246             if (shift) {
1247                 if (!octalSignificandOverflow) {
1248                     octalSignificandWide <<= shift;
1249                 } else {
1250                     mp_mul_2d(&octalSignificandBig, shift,
1251                             &octalSignificandBig);
1252                 }
1253             }
1254             if (!octalSignificandOverflow) {
1255                 if (octalSignificandWide >
1256                         (Tcl_WideUInt)(((~(unsigned long)0) >> 1) + signum)) {
1257 #ifndef TCL_WIDE_INT_IS_LONG
1258                     if (octalSignificandWide <= (MOST_BITS + signum)) {
1259                         objPtr->typePtr = &tclWideIntType;
1260                         if (signum) {
1261                             objPtr->internalRep.wideValue =
1262                                     - (Tcl_WideInt) octalSignificandWide;
1263                         } else {
1264                             objPtr->internalRep.wideValue =
1265                                     (Tcl_WideInt) octalSignificandWide;
1266                         }
1267                         break;
1268                     }
1269 #endif
1270                     TclBNInitBignumFromWideUInt(&octalSignificandBig,
1271                             octalSignificandWide);
1272                     octalSignificandOverflow = 1;
1273                 } else {
1274                     objPtr->typePtr = &tclIntType;
1275                     if (signum) {
1276                         objPtr->internalRep.longValue =
1277                                 - (long) octalSignificandWide;
1278                     } else {
1279                         objPtr->internalRep.longValue =
1280                                 (long) octalSignificandWide;
1281                     }
1282                 }
1283             }
1284             if (octalSignificandOverflow) {
1285                 if (signum) {
1286                     (void)mp_neg(&octalSignificandBig, &octalSignificandBig);
1287                 }
1288                 TclSetBignumInternalRep(objPtr, &octalSignificandBig);
1289             }
1290             break;
1291
1292         case ZERO:
1293         case DECIMAL:
1294             significandOverflow = AccumulateDecimalDigit(0, numTrailZeros-1,
1295                     &significandWide, &significandBig, significandOverflow);
1296             if (!significandOverflow && (significandWide > MOST_BITS+signum)) {
1297                 significandOverflow = 1;
1298                 TclBNInitBignumFromWideUInt(&significandBig, significandWide);
1299             }
1300         returnInteger:
1301             if (!significandOverflow) {
1302                 if (significandWide >
1303                         (Tcl_WideUInt)(((~(unsigned long)0) >> 1) + signum)) {
1304 #ifndef TCL_WIDE_INT_IS_LONG
1305                     if (significandWide <= MOST_BITS+signum) {
1306                         objPtr->typePtr = &tclWideIntType;
1307                         if (signum) {
1308                             objPtr->internalRep.wideValue =
1309                                     - (Tcl_WideInt) significandWide;
1310                         } else {
1311                             objPtr->internalRep.wideValue =
1312                                     (Tcl_WideInt) significandWide;
1313                         }
1314                         break;
1315                     }
1316 #endif
1317                     TclBNInitBignumFromWideUInt(&significandBig,
1318                             significandWide);
1319                     significandOverflow = 1;
1320                 } else {
1321                     objPtr->typePtr = &tclIntType;
1322                     if (signum) {
1323                         objPtr->internalRep.longValue =
1324                                 - (long) significandWide;
1325                     } else {
1326                         objPtr->internalRep.longValue =
1327                                 (long) significandWide;
1328                     }
1329                 }
1330             }
1331             if (significandOverflow) {
1332                 if (signum) {
1333                     (void)mp_neg(&significandBig, &significandBig);
1334                 }
1335                 TclSetBignumInternalRep(objPtr, &significandBig);
1336             }
1337             break;
1338
1339         case FRACTION:
1340         case EXPONENT:
1341
1342             /*
1343              * Here, we're parsing a floating-point number. 'significandWide'
1344              * or 'significandBig' contains the exact significand, according
1345              * to whether 'significandOverflow' is set. The desired floating
1346              * point value is significand * 10**k, where
1347              * k = numTrailZeros+exponent-numDigitsAfterDp.
1348              */
1349
1350             objPtr->typePtr = &tclDoubleType;
1351             if (exponentSignum) {
1352                 /*
1353                  * At this point exponent>=0, so the following calculation
1354                  * cannot underflow.
1355                  */
1356                 exponent = -exponent;
1357             }
1358
1359             /*
1360              * Adjust the exponent for the number of trailing zeros that
1361              * have not been accumulated, and the number of digits after
1362              * the decimal point. Pin any overflow to LONG_MAX/LONG_MIN
1363              * respectively.
1364              */
1365
1366             if (exponent >= 0) {
1367                 if (exponent - numDigitsAfterDp > LONG_MAX - numTrailZeros) {
1368                     exponent = LONG_MAX;
1369                 } else {
1370                     exponent = exponent - numDigitsAfterDp + numTrailZeros;
1371                 }
1372             } else {
1373                 if (exponent + numTrailZeros < LONG_MIN + numDigitsAfterDp) {
1374                     exponent = LONG_MIN;
1375                 } else {
1376                     exponent = exponent + numTrailZeros - numDigitsAfterDp;
1377                 }
1378             }
1379
1380             /*
1381              * The desired number is now significandWide * 10**exponent
1382              * or significandBig * 10**exponent, depending on whether
1383              * the significand has overflowed a wide int.
1384              */
1385             if (!significandOverflow) {
1386                 objPtr->internalRep.doubleValue = MakeLowPrecisionDouble(
1387                         signum, significandWide, numSigDigs, exponent);
1388             } else {
1389                 objPtr->internalRep.doubleValue = MakeHighPrecisionDouble(
1390                         signum, &significandBig, numSigDigs, exponent);
1391             }
1392             break;
1393
1394         case sINF:
1395         case sINFINITY:
1396             if (signum) {
1397                 objPtr->internalRep.doubleValue = -HUGE_VAL;
1398             } else {
1399                 objPtr->internalRep.doubleValue = HUGE_VAL;
1400             }
1401             objPtr->typePtr = &tclDoubleType;
1402             break;
1403
1404 #ifdef IEEE_FLOATING_POINT
1405         case sNAN:
1406         case sNANFINISH:
1407             objPtr->internalRep.doubleValue = MakeNaN(signum, significandWide);
1408             objPtr->typePtr = &tclDoubleType;
1409             break;
1410 #endif
1411         case INITIAL:
1412             /* This case only to silence compiler warning. */
1413             Tcl_Panic("TclParseNumber: state INITIAL can't happen here");
1414         }
1415     }
1416
1417     /*
1418      * Format an error message when an invalid number is encountered.
1419      */
1420
1421     if (status != TCL_OK) {
1422         if (interp != NULL) {
1423             Tcl_Obj *msg = Tcl_ObjPrintf("expected %s but got \"",
1424                     expected);
1425
1426             Tcl_AppendLimitedToObj(msg, bytes, numBytes, 50, "");
1427             Tcl_AppendToObj(msg, "\"", -1);
1428             if (state == BAD_OCTAL) {
1429                 Tcl_AppendToObj(msg, " (looks like invalid octal number)", -1);
1430             }
1431             Tcl_SetObjResult(interp, msg);
1432             Tcl_SetErrorCode(interp, "TCL", "VALUE", "NUMBER", NULL);
1433         }
1434     }
1435
1436     /*
1437      * Free memory.
1438      */
1439
1440     if (octalSignificandOverflow) {
1441         mp_clear(&octalSignificandBig);
1442     }
1443     if (significandOverflow) {
1444         mp_clear(&significandBig);
1445     }
1446     return status;
1447 }
1448 \f
1449 /*
1450  *----------------------------------------------------------------------
1451  *
1452  * AccumulateDecimalDigit --
1453  *
1454  *      Consume a decimal digit in a number being scanned.
1455  *
1456  * Results:
1457  *      Returns 1 if the number has overflowed to a bignum, 0 if it still fits
1458  *      in a wide integer.
1459  *
1460  * Side effects:
1461  *      Updates either the wide or bignum representation.
1462  *
1463  *----------------------------------------------------------------------
1464  */
1465
1466 static int
1467 AccumulateDecimalDigit(
1468     unsigned digit,             /* Digit being scanned. */
1469     int numZeros,               /* Count of zero digits preceding the digit
1470                                  * being scanned. */
1471     Tcl_WideUInt *wideRepPtr,   /* Representation of the partial number as a
1472                                  * wide integer. */
1473     mp_int *bignumRepPtr,       /* Representation of the partial number as a
1474                                  * bignum. */
1475     int bignumFlag)             /* Flag == 1 if the number overflowed previous
1476                                  * to this digit. */
1477 {
1478     int i, n;
1479     Tcl_WideUInt w;
1480
1481     /*
1482      * Try wide multiplication first.
1483      */
1484
1485     if (!bignumFlag) {
1486         w = *wideRepPtr;
1487         if (w == 0) {
1488             /*
1489              * There's no need to multiply if the multiplicand is zero.
1490              */
1491
1492             *wideRepPtr = digit;
1493             return 0;
1494         } else if (numZeros >= maxpow10_wide
1495                 || w > ((~(Tcl_WideUInt)0)-digit)/pow10_wide[numZeros+1]) {
1496             /*
1497              * Wide multiplication will overflow.  Expand the number to a
1498              * bignum and fall through into the bignum case.
1499              */
1500
1501             TclBNInitBignumFromWideUInt(bignumRepPtr, w);
1502         } else {
1503             /*
1504              * Wide multiplication.
1505              */
1506
1507             *wideRepPtr = w * pow10_wide[numZeros+1] + digit;
1508             return 0;
1509         }
1510     }
1511
1512     /*
1513      * Bignum multiplication.
1514      */
1515
1516     if (numZeros < log10_DIGIT_MAX) {
1517         /*
1518          * Up to about 8 zeros - single digit multiplication.
1519          */
1520
1521         mp_mul_d(bignumRepPtr, (mp_digit) pow10_wide[numZeros+1],
1522                 bignumRepPtr);
1523         mp_add_d(bignumRepPtr, (mp_digit) digit, bignumRepPtr);
1524     } else {
1525         /*
1526          * More than single digit multiplication. Multiply by the appropriate
1527          * small powers of 5, and then shift. Large strings of zeroes are
1528          * eaten 256 at a time; this is less efficient than it could be, but
1529          * seems implausible. We presume that MP_DIGIT_BIT is at least 27. The
1530          * first multiplication, by up to 10**7, is done with a one-DIGIT
1531          * multiply (this presumes that MP_DIGIT_BIT >= 24).
1532          */
1533
1534         n = numZeros + 1;
1535         mp_mul_d(bignumRepPtr, (mp_digit) pow10_wide[n&0x7], bignumRepPtr);
1536         for (i=3; i<=7; ++i) {
1537             if (n & (1 << i)) {
1538                 mp_mul(bignumRepPtr, pow5+i, bignumRepPtr);
1539             }
1540         }
1541         while (n >= 256) {
1542             mp_mul(bignumRepPtr, pow5+8, bignumRepPtr);
1543             n -= 256;
1544         }
1545         mp_mul_2d(bignumRepPtr, (int)(numZeros+1)&~0x7, bignumRepPtr);
1546         mp_add_d(bignumRepPtr, (mp_digit) digit, bignumRepPtr);
1547     }
1548
1549     return 1;
1550 }
1551 \f
1552 /*
1553  *----------------------------------------------------------------------
1554  *
1555  * MakeLowPrecisionDouble --
1556  *
1557  *      Makes the double precision number, signum*significand*10**exponent.
1558  *
1559  * Results:
1560  *      Returns the constructed number.
1561  *
1562  *      Common cases, where there are few enough digits that the number can be
1563  *      represented with at most roundoff, are handled specially here. If the
1564  *      number requires more than one rounded operation to compute, the code
1565  *      promotes the significand to a bignum and calls MakeHighPrecisionDouble
1566  *      to do it instead.
1567  *
1568  *----------------------------------------------------------------------
1569  */
1570
1571 static double
1572 MakeLowPrecisionDouble(
1573     int signum,                 /* 1 if the number is negative, 0 otherwise */
1574     Tcl_WideUInt significand,   /* Significand of the number */
1575     int numSigDigs,             /* Number of digits in the significand */
1576     long exponent)              /* Power of ten */
1577 {
1578     double retval;              /* Value of the number. */
1579     mp_int significandBig;      /* Significand expressed as a bignum. */
1580
1581     /*
1582      * With gcc on x86, the floating point rounding mode is double-extended.
1583      * This causes the result of double-precision calculations to be rounded
1584      * twice: once to the precision of double-extended and then again to the
1585      * precision of double. Double-rounding introduces gratuitous errors of 1
1586      * ulp, so we need to change rounding mode to 53-bits.
1587      */
1588
1589     TCL_IEEE_DOUBLE_ROUNDING;
1590
1591     /*
1592      * Test for the easy cases.
1593      */
1594
1595     if (significand == 0) {
1596         return copysign(0.0, -signum);
1597     }
1598     if (numSigDigs <= QUICK_MAX) {
1599         if (exponent >= 0) {
1600             if (exponent <= mmaxpow) {
1601                 /*
1602                  * The significand is an exact integer, and so is
1603                  * 10**exponent. The product will be correct to within 1/2 ulp
1604                  * without special handling.
1605                  */
1606
1607                 retval = (double)
1608                         ((Tcl_WideInt)significand * pow10vals[exponent]);
1609                 goto returnValue;
1610             } else {
1611                 int diff = QUICK_MAX - numSigDigs;
1612
1613                 if (exponent-diff <= mmaxpow) {
1614                     /*
1615                      * 10**exponent is not an exact integer, but
1616                      * 10**(exponent-diff) is exact, and so is
1617                      * significand*10**diff, so we can still compute the value
1618                      * with only one roundoff.
1619                      */
1620
1621                     volatile double factor = (double)
1622                             ((Tcl_WideInt)significand * pow10vals[diff]);
1623                     retval = factor * pow10vals[exponent-diff];
1624                     goto returnValue;
1625                 }
1626             }
1627         } else {
1628             if (exponent >= -mmaxpow) {
1629                 /*
1630                  * 10**-exponent is an exact integer, and so is the
1631                  * significand. Compute the result by one division, again with
1632                  * only one rounding.
1633                  */
1634
1635                 retval = (double)
1636                         ((Tcl_WideInt)significand / pow10vals[-exponent]);
1637                 goto returnValue;
1638             }
1639         }
1640     }
1641
1642     /*
1643      * All the easy cases have failed. Promote ths significand to bignum and
1644      * call MakeHighPrecisionDouble to do it the hard way.
1645      */
1646
1647     TclBNInitBignumFromWideUInt(&significandBig, significand);
1648     retval = MakeHighPrecisionDouble(0, &significandBig, numSigDigs,
1649             exponent);
1650     mp_clear(&significandBig);
1651
1652     /*
1653      * Come here to return the computed value.
1654      */
1655
1656   returnValue:
1657     if (signum) {
1658         retval = -retval;
1659     }
1660
1661     /*
1662      * On gcc on x86, restore the floating point mode word.
1663      */
1664
1665     TCL_DEFAULT_DOUBLE_ROUNDING;
1666
1667     return retval;
1668 }
1669 \f
1670 /*
1671  *----------------------------------------------------------------------
1672  *
1673  * MakeHighPrecisionDouble --
1674  *
1675  *      Makes the double precision number, signum*significand*10**exponent.
1676  *
1677  * Results:
1678  *      Returns the constructed number.
1679  *
1680  *      MakeHighPrecisionDouble is used when arbitrary-precision arithmetic is
1681  *      needed to ensure correct rounding. It begins by calculating a
1682  *      low-precision approximation to the desired number, and then refines
1683  *      the answer in high precision.
1684  *
1685  *----------------------------------------------------------------------
1686  */
1687
1688 static double
1689 MakeHighPrecisionDouble(
1690     int signum,                 /* 1=negative, 0=nonnegative */
1691     mp_int *significand,        /* Exact significand of the number */
1692     int numSigDigs,             /* Number of significant digits */
1693     long exponent)              /* Power of 10 by which to multiply */
1694 {
1695     double retval;
1696     int machexp;                /* Machine exponent of a power of 10. */
1697
1698     /*
1699      * With gcc on x86, the floating point rounding mode is double-extended.
1700      * This causes the result of double-precision calculations to be rounded
1701      * twice: once to the precision of double-extended and then again to the
1702      * precision of double. Double-rounding introduces gratuitous errors of 1
1703      * ulp, so we need to change rounding mode to 53-bits.
1704      */
1705
1706     TCL_IEEE_DOUBLE_ROUNDING;
1707
1708     /*
1709      * Quick checks for zero, and over/underflow. Be careful to avoid
1710      * integer overflow when calculating with 'exponent'.
1711      */
1712
1713     if (mp_iszero(significand)) {
1714         return copysign(0.0, -signum);
1715     }
1716     if (exponent >= 0 && exponent-1 > maxDigits-numSigDigs) {
1717         retval = HUGE_VAL;
1718         goto returnValue;
1719     } else if (exponent < 0 && numSigDigs+exponent < minDigits+1) {
1720         retval = 0.0;
1721         goto returnValue;
1722     }
1723
1724     /*
1725      * Develop a first approximation to the significand. It is tempting simply
1726      * to force bignum to double, but that will overflow on input numbers like
1727      * 1.[string repeat 0 1000]1; while this is a not terribly likely
1728      * scenario, we still have to deal with it. Use fraction and exponent
1729      * instead. Once we have the significand, multiply by 10**exponent. Test
1730      * for overflow. Convert back to a double, and test for underflow.
1731      */
1732
1733     retval = BignumToBiasedFrExp(significand, &machexp);
1734     retval = Pow10TimesFrExp(exponent, retval, &machexp);
1735     if (machexp > DBL_MAX_EXP*log2FLT_RADIX) {
1736         retval = HUGE_VAL;
1737         goto returnValue;
1738     }
1739     retval = SafeLdExp(retval, machexp);
1740         if (tiny == 0.0) {
1741             tiny = SafeLdExp(1.0, DBL_MIN_EXP * log2FLT_RADIX - mantBits);
1742         }
1743     if (retval < tiny) {
1744         retval = tiny;
1745     }
1746
1747     /*
1748      * Refine the result twice. (The second refinement should be necessary
1749      * only if the best approximation is a power of 2 minus 1/2 ulp).
1750      */
1751
1752     retval = RefineApproximation(retval, significand, exponent);
1753     retval = RefineApproximation(retval, significand, exponent);
1754
1755     /*
1756      * Come here to return the computed value.
1757      */
1758
1759   returnValue:
1760     if (signum) {
1761         retval = -retval;
1762     }
1763
1764     /*
1765      * On gcc on x86, restore the floating point mode word.
1766      */
1767
1768     TCL_DEFAULT_DOUBLE_ROUNDING;
1769
1770     return retval;
1771 }
1772 \f
1773 /*
1774  *----------------------------------------------------------------------
1775  *
1776  * MakeNaN --
1777  *
1778  *      Makes a "Not a Number" given a set of bits to put in the tag bits
1779  *
1780  *      Note that a signalling NaN is never returned.
1781  *
1782  *----------------------------------------------------------------------
1783  */
1784
1785 #ifdef IEEE_FLOATING_POINT
1786 static double
1787 MakeNaN(
1788     int signum,                 /* Sign bit (1=negative, 0=nonnegative. */
1789     Tcl_WideUInt tags)          /* Tag bits to put in the NaN. */
1790 {
1791     union {
1792         Tcl_WideUInt iv;
1793         double dv;
1794     } theNaN;
1795
1796     theNaN.iv = tags;
1797     theNaN.iv &= (((Tcl_WideUInt) 1) << 51) - 1;
1798     if (signum) {
1799         theNaN.iv |= ((Tcl_WideUInt) (0x8000 | NAN_START)) << 48;
1800     } else {
1801         theNaN.iv |= ((Tcl_WideUInt) NAN_START) << 48;
1802     }
1803     if (n770_fp) {
1804         theNaN.iv = Nokia770Twiddle(theNaN.iv);
1805     }
1806     return theNaN.dv;
1807 }
1808 #endif
1809 \f
1810 /*
1811  *----------------------------------------------------------------------
1812  *
1813  * RefineApproximation --
1814  *
1815  *      Given a poor approximation to a floating point number, returns a
1816  *      better one. (The better approximation is correct to within 1 ulp, and
1817  *      is entirely correct if the poor approximation is correct to 1 ulp.)
1818  *
1819  * Results:
1820  *      Returns the improved result.
1821  *
1822  *----------------------------------------------------------------------
1823  */
1824
1825 static double
1826 RefineApproximation(
1827     double approxResult,        /* Approximate result of conversion. */
1828     mp_int *exactSignificand,   /* Integer significand. */
1829     int exponent)               /* Power of 10 to multiply by significand. */
1830 {
1831     int M2, M5;                 /* Powers of 2 and of 5 needed to put the
1832                                  * decimal and binary numbers over a common
1833                                  * denominator. */
1834     double significand;         /* Sigificand of the binary number. */
1835     int binExponent;            /* Exponent of the binary number. */
1836     int msb;                    /* Most significant bit position of an
1837                                  * intermediate result. */
1838     int nDigits;                /* Number of mp_digit's in an intermediate
1839                                  * result. */
1840     mp_int twoMv;               /* Approx binary value expressed as an exact
1841                                  * integer scaled by the multiplier 2M. */
1842     mp_int twoMd;               /* Exact decimal value expressed as an exact
1843                                  * integer scaled by the multiplier 2M. */
1844     int scale;                  /* Scale factor for M. */
1845     int multiplier;             /* Power of two to scale M. */
1846     double num, den;            /* Numerator and denominator of the correction
1847                                  * term. */
1848     double quot;                /* Correction term. */
1849     double minincr;             /* Lower bound on the absolute value of the
1850                                  * correction term. */
1851     int roundToEven = 0;        /* Flag == TRUE if we need to invoke
1852                                  * "round to even" functionality */
1853     double rteSignificand;      /* Significand of the round-to-even result */
1854     int rteExponent;            /* Exponent of the round-to-even result */
1855     int shift;                  /* Shift count for converting numerator
1856                                  * and denominator of corrector to floating
1857                                  * point */
1858     Tcl_WideInt rteSigWide;     /* Wide integer version of the significand
1859                                  * for testing evenness */
1860     int i;
1861
1862     /*
1863      * The first approximation is always low. If we find that it's HUGE_VAL,
1864      * we're done.
1865      */
1866
1867     if (approxResult == HUGE_VAL) {
1868         return approxResult;
1869     }
1870     significand = frexp(approxResult, &binExponent);
1871
1872     /*
1873      * We are trying to compute a corrector term that, when added to the
1874      * approximate result, will yield close to the exact result.
1875      * The exact result is exactSignificand * 10**exponent.
1876      * The approximate result is significand * 2**binExponent
1877      * If exponent<0, we need to multiply the exact value by 10**-exponent
1878      * to make it an integer, plus another factor of 2 to decide on rounding.
1879      *  Similarly if binExponent<FP_PRECISION, we need
1880      * to multiply by 2**FP_PRECISION to make the approximate value an integer.
1881      *
1882      * Let M = 2**M2 * 5**M5 be the least common multiple of these two
1883      * multipliers.
1884      */
1885
1886     i = mantBits - binExponent;
1887     if (i < 0) {
1888         M2 = 0;
1889     } else {
1890         M2 = i;
1891     }
1892     if (exponent > 0) {
1893         M5 = 0;
1894     } else {
1895         M5 = -exponent;
1896         if (M5 - 1 > M2) {
1897             M2 = M5 - 1;
1898         }
1899     }
1900
1901     /*
1902      * Compute twoMv as 2*M*v, where v is the approximate value.
1903      * This is done by bit-whacking to calculate 2**(M2+1)*significand,
1904      * and then multiplying by 5**M5.
1905      */
1906
1907     msb = binExponent + M2;     /* 1008 */
1908     nDigits = msb / MP_DIGIT_BIT + 1;
1909     mp_init_size(&twoMv, nDigits);
1910     i = (msb % MP_DIGIT_BIT + 1);
1911     twoMv.used = nDigits;
1912     significand *= SafeLdExp(1.0, i);
1913     while (--nDigits >= 0) {
1914         twoMv.dp[nDigits] = (mp_digit) significand;
1915         significand -= (mp_digit) significand;
1916         significand = SafeLdExp(significand, MP_DIGIT_BIT);
1917     }
1918     for (i = 0; i <= 8; ++i) {
1919         if (M5 & (1 << i)) {
1920             mp_mul(&twoMv, pow5+i, &twoMv);
1921         }
1922     }
1923
1924     /*
1925      * Compute twoMd as 2*M*d, where d is the exact value.
1926      * This is done by multiplying by 5**(M5+exponent) and then multiplying
1927      * by 2**(M5+exponent+1), which is, of couse, a left shift.
1928      */
1929
1930     mp_init_copy(&twoMd, exactSignificand);
1931     for (i=0; i<=8; ++i) {
1932         if ((M5 + exponent) & (1 << i)) {
1933             mp_mul(&twoMd, pow5+i, &twoMd);
1934         }
1935     }
1936     mp_mul_2d(&twoMd, M2+exponent+1, &twoMd);
1937
1938     /*
1939      * Now let twoMd = twoMd - twoMv, the difference between the exact and
1940      * approximate values.
1941      */
1942
1943     mp_sub(&twoMd, &twoMv, &twoMd);
1944
1945     /*
1946      * The result, 2Mv-2Md, needs to be divided by 2M to yield a correction
1947      * term. Because 2M may well overflow a double, we need to scale the
1948      * denominator by a factor of 2**binExponent-mantBits. Place that factor
1949      * times 1/2 ULP into twoMd.
1950      */
1951
1952     scale = binExponent - mantBits - 1;
1953     mp_set(&twoMv, 1);
1954     for (i=0; i<=8; ++i) {
1955         if (M5 & (1 << i)) {
1956             mp_mul(&twoMv, pow5+i, &twoMv);
1957         }
1958     }
1959     multiplier = M2 + scale + 1;
1960     if (multiplier > 0) {
1961         mp_mul_2d(&twoMv, multiplier, &twoMv);
1962     } else if (multiplier < 0) {
1963         mp_div_2d(&twoMv, -multiplier, &twoMv, NULL);
1964     }
1965
1966     /*
1967      * Will the eventual correction term be less than, equal to, or
1968      * greater than 1/2 ULP?
1969      */
1970
1971     switch (mp_cmp_mag(&twoMd, &twoMv)) {
1972     case MP_LT:
1973         /*
1974          * If the error is less than 1/2 ULP, there's no correction to make.
1975          */
1976         mp_clear(&twoMd);
1977         mp_clear(&twoMv);
1978         return approxResult;
1979     case MP_EQ:
1980         /*
1981          * If the error is exactly 1/2 ULP, we need to round to even.
1982          */
1983         roundToEven = 1;
1984         break;
1985     case MP_GT:
1986         /*
1987          * We need to correct the result if the error exceeds 1/2 ULP.
1988          */
1989         break;
1990     }
1991
1992     /*
1993      * If we're in the 'round to even' case, and the significand is already
1994      * even, we're done. Return the approximate result.
1995      */
1996     if (roundToEven) {
1997         rteSignificand = frexp(approxResult, &rteExponent);
1998         rteSigWide = (Tcl_WideInt) ldexp(rteSignificand, FP_PRECISION);
1999         if ((rteSigWide & 1) == 0) {
2000             mp_clear(&twoMd);
2001             mp_clear(&twoMv);
2002             return approxResult;
2003         }
2004     }
2005
2006     /*
2007      * Reduce the numerator and denominator of the corrector term so that
2008      * they will fit in the floating point precision.
2009      */
2010     shift = mp_count_bits(&twoMv) - FP_PRECISION - 1;
2011     if (shift > 0) {
2012         mp_div_2d(&twoMv, shift, &twoMv, NULL);
2013         mp_div_2d(&twoMd, shift, &twoMd, NULL);
2014     }
2015
2016     /*
2017      * Convert the numerator and denominator of the corrector term accurately
2018      * to floating point numbers.
2019      */
2020
2021     num = TclBignumToDouble(&twoMd);
2022     den = TclBignumToDouble(&twoMv);
2023
2024     quot = SafeLdExp(num/den, scale);
2025     minincr = SafeLdExp(1.0, binExponent-mantBits);
2026
2027     if (quot<0. && quot>-minincr) {
2028         quot = -minincr;
2029     } else if (quot>0. && quot<minincr) {
2030         quot = minincr;
2031     }
2032
2033     mp_clear(&twoMd);
2034     mp_clear(&twoMv);
2035
2036     return approxResult + quot;
2037 }
2038 \f
2039 /*
2040  *----------------------------------------------------------------------
2041  *
2042  * MultPow5 --
2043  *
2044  *      Multiply a bignum by a power of 5.
2045  *
2046  * Side effects:
2047  *      Stores base*5**n in result.
2048  *
2049  *----------------------------------------------------------------------
2050  */
2051
2052 static inline void
2053 MulPow5(
2054     mp_int *base,               /* Number to multiply. */
2055     unsigned n,                 /* Power of 5 to multiply by. */
2056     mp_int *result)             /* Place to store the result. */
2057 {
2058     mp_int *p = base;
2059     int n13 = n / 13;
2060     int r = n % 13;
2061
2062     if (r != 0) {
2063         mp_mul_d(p, dpow5[r], result);
2064         p = result;
2065     }
2066     r = 0;
2067     while (n13 != 0) {
2068         if (n13 & 1) {
2069             mp_mul(p, pow5_13+r, result);
2070             p = result;
2071         }
2072         n13 >>= 1;
2073         ++r;
2074     }
2075     if (p != result) {
2076         mp_copy(p, result);
2077     }
2078 }
2079 \f
2080 /*
2081  *----------------------------------------------------------------------
2082  *
2083  * NormalizeRightward --
2084  *
2085  *      Shifts a number rightward until it is odd (that is, until the least
2086  *      significant bit is nonzero.
2087  *
2088  * Results:
2089  *      Returns the number of bit positions by which the number was shifted.
2090  *
2091  * Side effects:
2092  *      Shifts the number in place; *wPtr is replaced by the shifted number.
2093  *
2094  *----------------------------------------------------------------------
2095  */
2096
2097 static inline int
2098 NormalizeRightward(
2099     Tcl_WideUInt *wPtr)         /* INOUT: Number to shift. */
2100 {
2101     int rv = 0;
2102     Tcl_WideUInt w = *wPtr;
2103
2104     if (!(w & (Tcl_WideUInt) 0xFFFFFFFF)) {
2105         w >>= 32; rv += 32;
2106     }
2107     if (!(w & (Tcl_WideUInt) 0xFFFF)) {
2108         w >>= 16; rv += 16;
2109     }
2110     if (!(w & (Tcl_WideUInt) 0xFF)) {
2111         w >>= 8; rv += 8;
2112     }
2113     if (!(w & (Tcl_WideUInt) 0xF)) {
2114         w >>= 4; rv += 4;
2115     }
2116     if (!(w & 0x3)) {
2117         w >>= 2; rv += 2;
2118     }
2119     if (!(w & 0x1)) {
2120         w >>= 1; ++rv;
2121     }
2122     *wPtr = w;
2123     return rv;
2124 }
2125 \f
2126 /*
2127  *----------------------------------------------------------------------
2128  *
2129  * RequiredPrecision --
2130  *
2131  *      Determines the number of bits needed to hold an intger.
2132  *
2133  * Results:
2134  *      Returns the position of the most significant bit (0 - 63).  Returns 0
2135  *      if the number is zero.
2136  *
2137  *----------------------------------------------------------------------
2138  */
2139
2140 static int
2141 RequiredPrecision(
2142     Tcl_WideUInt w)             /* Number to interrogate. */
2143 {
2144     int rv;
2145     unsigned long wi;
2146
2147     if (w & ((Tcl_WideUInt) 0xFFFFFFFF << 32)) {
2148         wi = (unsigned long) (w >> 32); rv = 32;
2149     } else {
2150         wi = (unsigned long) w; rv = 0;
2151     }
2152     if (wi & 0xFFFF0000) {
2153         wi >>= 16; rv += 16;
2154     }
2155     if (wi & 0xFF00) {
2156         wi >>= 8; rv += 8;
2157     }
2158     if (wi & 0xF0) {
2159         wi >>= 4; rv += 4;
2160     }
2161     if (wi & 0xC) {
2162         wi >>= 2; rv += 2;
2163     }
2164     if (wi & 0x2) {
2165         wi >>= 1; ++rv;
2166     }
2167     if (wi & 0x1) {
2168         ++rv;
2169     }
2170     return rv;
2171 }
2172 \f
2173 /*
2174  *----------------------------------------------------------------------
2175  *
2176  * DoubleToExpAndSig --
2177  *
2178  *      Separates a 'double' into exponent and significand.
2179  *
2180  * Side effects:
2181  *      Stores the significand in '*significand' and the exponent in '*expon'
2182  *      so that dv == significand * 2.0**expon, and significand is odd.  Also
2183  *      stores the position of the leftmost 1-bit in 'significand' in 'bits'.
2184  *
2185  *----------------------------------------------------------------------
2186  */
2187
2188 static inline void
2189 DoubleToExpAndSig(
2190     double dv,                  /* Number to convert. */
2191     Tcl_WideUInt *significand,  /* OUTPUT: Significand of the number. */
2192     int *expon,                 /* OUTPUT: Exponent to multiply the number
2193                                  * by. */
2194     int *bits)                  /* OUTPUT: Number of significant bits. */
2195 {
2196     Double d;                   /* Number being converted. */
2197     Tcl_WideUInt z;             /* Significand under construction. */
2198     int de;                     /* Exponent of the number. */
2199     int k;                      /* Bit count. */
2200
2201     d.d = dv;
2202
2203     /*
2204      * Extract exponent and significand.
2205      */
2206
2207     de = (d.w.word0 & EXP_MASK) >> EXP_SHIFT;
2208     z = d.q & SIG_MASK;
2209     if (de != 0) {
2210         z |= HIDDEN_BIT;
2211         k = NormalizeRightward(&z);
2212         *bits = FP_PRECISION - k;
2213         *expon = k + (de - EXPONENT_BIAS) - (FP_PRECISION-1);
2214     } else {
2215         k = NormalizeRightward(&z);
2216         *expon = k + (de - EXPONENT_BIAS) - (FP_PRECISION-1) + 1;
2217         *bits = RequiredPrecision(z);
2218     }
2219     *significand = z;
2220 }
2221 \f
2222 /*
2223  *----------------------------------------------------------------------
2224  *
2225  * TakeAbsoluteValue --
2226  *
2227  *      Takes the absolute value of a 'double' including 0, Inf and NaN
2228  *
2229  * Side effects:
2230  *      The 'double' in *d is replaced with its absolute value. The signum is
2231  *      stored in 'sign': 1 for negative, 0 for nonnegative.
2232  *
2233  *----------------------------------------------------------------------
2234  */
2235
2236 static inline void
2237 TakeAbsoluteValue(
2238     Double *d,                  /* Number to replace with absolute value. */
2239     int *sign)                  /* Place to put the signum. */
2240 {
2241     if (d->w.word0 & SIGN_BIT) {
2242         *sign = 1;
2243         d->w.word0 &= ~SIGN_BIT;
2244     } else {
2245         *sign = 0;
2246     }
2247 }
2248 \f
2249 /*
2250  *----------------------------------------------------------------------
2251  *
2252  * FormatInfAndNaN --
2253  *
2254  *      Bailout for formatting infinities and Not-A-Number.
2255  *
2256  * Results:
2257  *      Returns one of the strings 'Infinity' and 'NaN'.  The string returned
2258  *      must be freed by the caller using 'ckfree'.
2259  *
2260  * Side effects:
2261  *      Stores 9999 in *decpt, and sets '*endPtr' to designate the terminating
2262  *      NUL byte of the string if 'endPtr' is not NULL.
2263  *
2264  *----------------------------------------------------------------------
2265  */
2266
2267 static inline char *
2268 FormatInfAndNaN(
2269     Double *d,                  /* Exceptional number to format. */
2270     int *decpt,                 /* Decimal point to set to a bogus value. */
2271     char **endPtr)              /* Pointer to the end of the formatted data */
2272 {
2273     char *retval;
2274
2275     *decpt = 9999;
2276     if (!(d->w.word1) && !(d->w.word0 & HI_ORDER_SIG_MASK)) {
2277         retval = ckalloc(9);
2278         strcpy(retval, "Infinity");
2279         if (endPtr) {
2280             *endPtr = retval + 8;
2281         }
2282     } else {
2283         retval = ckalloc(4);
2284         strcpy(retval, "NaN");
2285         if (endPtr) {
2286             *endPtr = retval + 3;
2287         }
2288     }
2289     return retval;
2290 }
2291 \f
2292 /*
2293  *----------------------------------------------------------------------
2294  *
2295  * FormatZero --
2296  *
2297  *      Bailout to format a zero floating-point number.
2298  *
2299  * Results:
2300  *      Returns the constant string "0"
2301  *
2302  * Side effects:
2303  *      Stores 1 in '*decpt' and puts a pointer to the NUL byte terminating
2304  *      the string in '*endPtr' if 'endPtr' is not NULL.
2305  *
2306  *----------------------------------------------------------------------
2307  */
2308
2309 static inline char *
2310 FormatZero(
2311     int *decpt,                 /* Location of the decimal point. */
2312     char **endPtr)              /* Pointer to the end of the formatted data */
2313 {
2314     char *retval = ckalloc(2);
2315
2316     strcpy(retval, "0");
2317     if (endPtr) {
2318         *endPtr = retval+1;
2319     }
2320     *decpt = 0;
2321     return retval;
2322 }
2323 \f
2324 /*
2325  *----------------------------------------------------------------------
2326  *
2327  * ApproximateLog10 --
2328  *
2329  *      Computes a two-term Taylor series approximation to the common log of a
2330  *      number, and computes the number's binary log.
2331  *
2332  * Results:
2333  *      Return an approximation to floor(log10(bw*2**be)) that is either exact
2334  *      or 1 too high.
2335  *
2336  *----------------------------------------------------------------------
2337  */
2338
2339 static inline int
2340 ApproximateLog10(
2341     Tcl_WideUInt bw,            /* Integer significand of the number. */
2342     int be,                     /* Power of two to scale bw. */
2343     int bbits)                  /* Number of bits of precision in bw. */
2344 {
2345     int i;                      /* Log base 2 of the number. */
2346     int k;                      /* Floor(Log base 10 of the number) */
2347     double ds;                  /* Mantissa of the number. */
2348     Double d2;
2349
2350     /*
2351      * Compute i and d2 such that d = d2*2**i, and 1 < d2 < 2.
2352      * Compute an approximation to log10(d),
2353      *   log10(d) ~ log10(2) * i + log10(1.5)
2354      *            + (significand-1.5)/(1.5 * log(10))
2355      */
2356
2357     d2.q = bw << (FP_PRECISION - bbits) & SIG_MASK;
2358     d2.w.word0 |= (EXPONENT_BIAS) << EXP_SHIFT;
2359     i = be + bbits - 1;
2360     ds = (d2.d - 1.5) * TWO_OVER_3LOG10
2361             + LOG10_3HALVES_PLUS_FUDGE + LOG10_2 * i;
2362     k = (int) ds;
2363     if (k > ds) {
2364         --k;
2365     }
2366     return k;
2367 }
2368 \f
2369 /*
2370  *----------------------------------------------------------------------
2371  *
2372  * BetterLog10 --
2373  *
2374  *      Improves the result of ApproximateLog10 for numbers in the range
2375  *      1 .. 10**(TEN_PMAX)-1
2376  *
2377  * Side effects:
2378  *      Sets k_check to 0 if the new result is known to be exact, and to 1 if
2379  *      it may still be one too high.
2380  *
2381  * Results:
2382  *      Returns the improved approximation to log10(d).
2383  *
2384  *----------------------------------------------------------------------
2385  */
2386
2387 static inline int
2388 BetterLog10(
2389     double d,                   /* Original number to format. */
2390     int k,                      /* Characteristic(Log base 10) of the
2391                                  * number. */
2392     int *k_check)               /* Flag == 1 if k is inexact. */
2393 {
2394     /*
2395      * Performance hack. If k is in the range 0..TEN_PMAX, then we can use a
2396      * powers-of-ten table to check it.
2397      */
2398
2399     if (k >= 0 && k <= TEN_PMAX) {
2400         if (d < tens[k]) {
2401             k--;
2402         }
2403         *k_check = 0;
2404     } else {
2405         *k_check = 1;
2406     }
2407     return k;
2408 }
2409 \f
2410 /*
2411  *----------------------------------------------------------------------
2412  *
2413  * ComputeScale --
2414  *
2415  *      Prepares to format a floating-point number as decimal.
2416  *
2417  * Parameters:
2418  *      floor(log10*x) is k (or possibly k-1).  floor(log2(x) is i.  The
2419  *      significand of x requires bbits bits to represent.
2420  *
2421  * Results:
2422  *      Determines integers b2, b5, s2, s5 so that sig*2**b2*5**b5/2**s2*2**s5
2423  *      exactly represents the value of the x/10**k. This value will lie in
2424  *      the range [1 .. 10), and allows for computing successive digits by
2425  *      multiplying sig%10 by 10.
2426  *
2427  *----------------------------------------------------------------------
2428  */
2429
2430 static inline void
2431 ComputeScale(
2432     int be,                     /* Exponent part of number: d = bw * 2**be. */
2433     int k,                      /* Characteristic of log10(number). */
2434     int *b2,                    /* OUTPUT: Power of 2 in the numerator. */
2435     int *b5,                    /* OUTPUT: Power of 5 in the numerator. */
2436     int *s2,                    /* OUTPUT: Power of 2 in the denominator. */
2437     int *s5)                    /* OUTPUT: Power of 5 in the denominator. */
2438 {
2439     /*
2440      * Scale numerator and denominator powers of 2 so that the input binary
2441      * number is the ratio of integers.
2442      */
2443
2444     if (be <= 0) {
2445         *b2 = 0;
2446         *s2 = -be;
2447     } else {
2448         *b2 = be;
2449         *s2 = 0;
2450     }
2451
2452     /*
2453      * Scale numerator and denominator so that the output decimal number is
2454      * the ratio of integers.
2455      */
2456
2457     if (k >= 0) {
2458         *b5 = 0;
2459         *s5 = k;
2460         *s2 += k;
2461     } else {
2462         *b2 -= k;
2463         *b5 = -k;
2464         *s5 = 0;
2465     }
2466 }
2467 \f
2468 /*
2469  *----------------------------------------------------------------------
2470  *
2471  * SetPrecisionLimits --
2472  *
2473  *      Determines how many digits of significance should be computed (and,
2474  *      hence, how much memory need be allocated) for formatting a floating
2475  *      point number.
2476  *
2477  * Given that 'k' is floor(log10(x)):
2478  * if 'shortest' format is used, there will be at most 18 digits in the
2479  * result.
2480  * if 'F' format is used, there will be at most 'ndigits' + k + 1 digits
2481  * if 'E' format is used, there will be exactly 'ndigits' digits.
2482  *
2483  * Side effects:
2484  *      Adjusts '*ndigitsPtr' to have a valid value. Stores the maximum memory
2485  *      allocation needed in *iPtr.  Sets '*iLimPtr' to the limiting number of
2486  *      digits to convert if k has been guessed correctly, and '*iLim1Ptr' to
2487  *      the limiting number of digits to convert if k has been guessed to be
2488  *      one too high.
2489  *
2490  *----------------------------------------------------------------------
2491  */
2492
2493 static inline void
2494 SetPrecisionLimits(
2495     int convType,               /* Type of conversion: TCL_DD_SHORTEST,
2496                                  * TCL_DD_STEELE0, TCL_DD_E_FMT,
2497                                  * TCL_DD_F_FMT. */
2498     int k,                      /* Floor(log10(number to convert)) */
2499     int *ndigitsPtr,            /* IN/OUT: Number of digits requested (will be
2500                                  *         adjusted if needed). */
2501     int *iPtr,                  /* OUT: Maximum number of digits to return. */
2502     int *iLimPtr,               /* OUT: Number of digits of significance if
2503                                  *      the bignum method is used.*/
2504     int *iLim1Ptr)              /* OUT: Number of digits of significance if
2505                                  *      the quick method is used. */
2506 {
2507     switch (convType) {
2508     case TCL_DD_SHORTEST0:
2509     case TCL_DD_STEELE0:
2510         *iLimPtr = *iLim1Ptr = -1;
2511         *iPtr = 18;
2512         *ndigitsPtr = 0;
2513         break;
2514     case TCL_DD_E_FORMAT:
2515         if (*ndigitsPtr <= 0) {
2516             *ndigitsPtr = 1;
2517         }
2518         *iLimPtr = *iLim1Ptr = *iPtr = *ndigitsPtr;
2519         break;
2520     case TCL_DD_F_FORMAT:
2521         *iPtr = *ndigitsPtr + k + 1;
2522         *iLimPtr = *iPtr;
2523         *iLim1Ptr = *iPtr - 1;
2524         if (*iPtr <= 0) {
2525             *iPtr = 1;
2526         }
2527         break;
2528     default:
2529         *iPtr = -1;
2530         *iLimPtr = -1;
2531         *iLim1Ptr = -1;
2532         Tcl_Panic("impossible conversion type in TclDoubleDigits");
2533     }
2534 }
2535 \f
2536 /*
2537  *----------------------------------------------------------------------
2538  *
2539  * BumpUp --
2540  *
2541  *      Increases a string of digits ending in a series of nines to designate
2542  *      the next higher number.  xxxxb9999... -> xxxx(b+1)0000...
2543  *
2544  * Results:
2545  *      Returns a pointer to the end of the adjusted string.
2546  *
2547  * Side effects:
2548  *      In the case that the string consists solely of '999999', sets it to
2549  *      "1" and moves the decimal point (*kPtr) one place to the right.
2550  *
2551  *----------------------------------------------------------------------
2552  */
2553
2554 static inline char *
2555 BumpUp(
2556     char *s,                    /* Cursor pointing one past the end of the
2557                                  * string. */
2558     char *retval,               /* Start of the string of digits. */
2559     int *kPtr)                  /* Position of the decimal point. */
2560 {
2561     while (*--s == '9') {
2562         if (s == retval) {
2563             ++(*kPtr);
2564             *s = '1';
2565             return s+1;
2566         }
2567     }
2568     ++*s;
2569     ++s;
2570     return s;
2571 }
2572 \f
2573 /*
2574  *----------------------------------------------------------------------
2575  *
2576  * AdjustRange --
2577  *
2578  *      Rescales a 'double' in preparation for formatting it using the 'quick'
2579  *      double-to-string method.
2580  *
2581  * Results:
2582  *      Returns the precision that has been lost in the prescaling as a count
2583  *      of units in the least significant place.
2584  *
2585  *----------------------------------------------------------------------
2586  */
2587
2588 static inline int
2589 AdjustRange(
2590     double *dPtr,               /* INOUT: Number to adjust. */
2591     int k)                      /* IN: floor(log10(d)) */
2592 {
2593     int ieps;                   /* Number of roundoff errors that have
2594                                  * accumulated. */
2595     double d = *dPtr;           /* Number to adjust. */
2596     double ds;
2597     int i, j, j1;
2598
2599     ieps = 2;
2600
2601     if (k > 0) {
2602         /*
2603          * The number must be reduced to bring it into range.
2604          */
2605
2606         ds = tens[k & 0xF];
2607         j = k >> 4;
2608         if (j & BLETCH) {
2609             j &= (BLETCH-1);
2610             d /= bigtens[N_BIGTENS - 1];
2611             ieps++;
2612         }
2613         i = 0;
2614         for (; j != 0; j>>=1) {
2615             if (j & 1) {
2616                 ds *= bigtens[i];
2617                 ++ieps;
2618             }
2619             ++i;
2620         }
2621         d /= ds;
2622     } else if ((j1 = -k) != 0) {
2623         /*
2624          * The number must be increased to bring it into range.
2625          */
2626
2627         d *= tens[j1 & 0xF];
2628         i = 0;
2629         for (j = j1>>4; j; j>>=1) {
2630             if (j & 1) {
2631                 ieps++;
2632                 d *= bigtens[i];
2633             }
2634             ++i;
2635         }
2636     }
2637
2638     *dPtr = d;
2639     return ieps;
2640 }
2641 \f
2642 /*
2643  *----------------------------------------------------------------------
2644  *
2645  * ShorteningQuickFormat --
2646  *
2647  *      Returns a 'quick' format of a double precision number to a string of
2648  *      digits, preferring a shorter string of digits if the shorter string is
2649  *      still within 1/2 ulp of the number.
2650  *
2651  * Results:
2652  *      Returns the string of digits. Returns NULL if the 'quick' method fails
2653  *      and the bignum method must be used.
2654  *
2655  * Side effects:
2656  *      Stores the position of the decimal point at '*kPtr'.
2657  *
2658  *----------------------------------------------------------------------
2659  */
2660
2661 static inline char *
2662 ShorteningQuickFormat(
2663     double d,                   /* Number to convert. */
2664     int k,                      /* floor(log10(d)) */
2665     int ilim,                   /* Number of significant digits to return. */
2666     double eps,                 /* Estimated roundoff error. */
2667     char *retval,               /* Buffer to receive the digit string. */
2668     int *kPtr)                  /* Pointer to stash the position of the
2669                                  * decimal point. */
2670 {
2671     char *s = retval;           /* Cursor in the return value. */
2672     int digit;                  /* Current digit. */
2673     int i;
2674
2675     eps = 0.5 / tens[ilim-1] - eps;
2676     i = 0;
2677     for (;;) {
2678         /*
2679          * Convert a digit.
2680          */
2681
2682         digit = (int) d;
2683         d -= digit;
2684         *s++ = '0' + digit;
2685
2686         /*
2687          * Truncate the conversion if the string of digits is within 1/2 ulp
2688          * of the actual value.
2689          */
2690
2691         if (d < eps) {
2692             *kPtr = k;
2693             return s;
2694         }
2695         if ((1. - d) < eps) {
2696             *kPtr = k;
2697             return BumpUp(s, retval, kPtr);
2698         }
2699
2700         /*
2701          * Bail out if the conversion fails to converge to a sufficiently
2702          * precise value.
2703          */
2704
2705         if (++i >= ilim) {
2706             return NULL;
2707         }
2708
2709         /*
2710          * Bring the next digit to the integer part.
2711          */
2712
2713         eps *= 10;
2714         d *= 10.0;
2715     }
2716 }
2717 \f
2718 /*
2719  *----------------------------------------------------------------------
2720  *
2721  * StrictQuickFormat --
2722  *
2723  *      Convert a double precision number of a string of a precise number of
2724  *      digits, using the 'quick' double precision method.
2725  *
2726  * Results:
2727  *      Returns the digit string, or NULL if the bignum method must be used to
2728  *      do the formatting.
2729  *
2730  * Side effects:
2731  *      Stores the position of the decimal point in '*kPtr'.
2732  *
2733  *----------------------------------------------------------------------
2734  */
2735
2736 static inline char *
2737 StrictQuickFormat(
2738     double d,                   /* Number to convert. */
2739     int k,                      /* floor(log10(d)) */
2740     int ilim,                   /* Number of significant digits to return. */
2741     double eps,                 /* Estimated roundoff error. */
2742     char *retval,               /* Start of the digit string. */
2743     int *kPtr)                  /* Pointer to stash the position of the
2744                                  * decimal point. */
2745 {
2746     char *s = retval;           /* Cursor in the return value. */
2747     int digit;                  /* Current digit of the answer. */
2748     int i;
2749
2750     eps *= tens[ilim-1];
2751     i = 1;
2752     for (;;) {
2753         /*
2754          * Extract a digit.
2755          */
2756
2757         digit = (int) d;
2758         d -= digit;
2759         if (d == 0.0) {
2760             ilim = i;
2761         }
2762         *s++ = '0' + digit;
2763
2764         /*
2765          * When the given digit count is reached, handle trailing strings of 0
2766          * and 9.
2767          */
2768
2769         if (i == ilim) {
2770             if (d > 0.5 + eps) {
2771                 *kPtr = k;
2772                 return BumpUp(s, retval, kPtr);
2773             } else if (d < 0.5 - eps) {
2774                 while (*--s == '0') {
2775                     /* do nothing */
2776                 }
2777                 s++;
2778                 *kPtr = k;
2779                 return s;
2780             } else {
2781                 return NULL;
2782             }
2783         }
2784
2785         /*
2786          * Advance to the next digit.
2787          */
2788
2789         ++i;
2790         d *= 10.0;
2791     }
2792 }
2793 \f
2794 /*
2795  *----------------------------------------------------------------------
2796  *
2797  * QuickConversion --
2798  *
2799  *      Converts a floating point number the 'quick' way, when only a limited
2800  *      number of digits is required and floating point arithmetic can
2801  *      therefore be used for the intermediate results.
2802  *
2803  * Results:
2804  *      Returns the converted string, or NULL if the bignum method must be
2805  *      used.
2806  *
2807  *----------------------------------------------------------------------
2808  */
2809
2810 static inline char *
2811 QuickConversion(
2812     double e,                   /* Number to format. */
2813     int k,                      /* floor(log10(d)), approximately. */
2814     int k_check,                /* 0 if k is exact, 1 if it may be too high */
2815     int flags,                  /* Flags passed to dtoa:
2816                                  *    TCL_DD_SHORTEN_FLAG */
2817     int len,                    /* Length of the return value. */
2818     int ilim,                   /* Number of digits to store. */
2819     int ilim1,                  /* Number of digits to store if we misguessed
2820                                  * k. */
2821     int *decpt,                 /* OUTPUT: Location of the decimal point. */
2822     char **endPtr)              /* OUTPUT: Pointer to the terminal null
2823                                  * byte. */
2824 {
2825     int ieps;                   /* Number of 1-ulp roundoff errors that have
2826                                  * accumulated in the calculation. */
2827     Double eps;                 /* Estimated roundoff error. */
2828     char *retval;               /* Returned string. */
2829     char *end;                  /* Pointer to the terminal null byte in the
2830                                  * returned string. */
2831     volatile double d;          /* Workaround for a bug in mingw gcc 3.4.5 */
2832
2833     /*
2834      * Bring d into the range [1 .. 10).
2835      */
2836
2837     ieps = AdjustRange(&e, k);
2838     d = e;
2839
2840     /*
2841      * If the guessed value of k didn't get d into range, adjust it by one. If
2842      * that leaves us outside the range in which quick format is accurate,
2843      * bail out.
2844      */
2845
2846     if (k_check && d < 1. && ilim > 0) {
2847         if (ilim1 < 0) {
2848             return NULL;
2849         }
2850         ilim = ilim1;
2851         --k;
2852         d = d * 10.0;
2853         ++ieps;
2854     }
2855
2856     /*
2857      * Compute estimated roundoff error.
2858      */
2859
2860     eps.d = ieps * d + 7.;
2861     eps.w.word0 -= (FP_PRECISION-1) << EXP_SHIFT;
2862
2863     /*
2864      * Handle the peculiar case where the result has no significant digits.
2865      */
2866
2867     retval = ckalloc(len + 1);
2868     if (ilim == 0) {
2869         d = d - 5.;
2870         if (d > eps.d) {
2871             *retval = '1';
2872             *decpt = k;
2873             return retval;
2874         } else if (d < -eps.d) {
2875             *decpt = k;
2876             return retval;
2877         } else {
2878             ckfree(retval);
2879             return NULL;
2880         }
2881     }
2882
2883     /*
2884      * Format the digit string.
2885      */
2886
2887     if (flags & TCL_DD_SHORTEN_FLAG) {
2888         end = ShorteningQuickFormat(d, k, ilim, eps.d, retval, decpt);
2889     } else {
2890         end = StrictQuickFormat(d, k, ilim, eps.d, retval, decpt);
2891     }
2892     if (end == NULL) {
2893         ckfree(retval);
2894         return NULL;
2895     }
2896     *end = '\0';
2897     if (endPtr != NULL) {
2898         *endPtr = end;
2899     }
2900     return retval;
2901 }
2902 \f
2903 /*
2904  *----------------------------------------------------------------------
2905  *
2906  * CastOutPowersOf2 --
2907  *
2908  *      Adjust the factors 'b2', 'm2', and 's2' to cast out common powers of 2
2909  *      from numerator and denominator in preparation for the 'bignum' method
2910  *      of floating point conversion.
2911  *
2912  *----------------------------------------------------------------------
2913  */
2914
2915 static inline void
2916 CastOutPowersOf2(
2917     int *b2,                    /* Power of 2 to multiply the significand. */
2918     int *m2,                    /* Power of 2 to multiply 1/2 ulp. */
2919     int *s2)                    /* Power of 2 to multiply the common
2920                                  * denominator. */
2921 {
2922     int i;
2923
2924     if (*m2 > 0 && *s2 > 0) {   /* Find the smallest power of 2 in the
2925                                  * numerator. */
2926         if (*m2 < *s2) {        /* Find the lowest common denominator. */
2927             i = *m2;
2928         } else {
2929             i = *s2;
2930         }
2931         *b2 -= i;               /* Reduce to lowest terms. */
2932         *m2 -= i;
2933         *s2 -= i;
2934     }
2935 }
2936 \f
2937 /*
2938  *----------------------------------------------------------------------
2939  *
2940  * ShorteningInt64Conversion --
2941  *
2942  *      Converts a double-precision number to the shortest string of digits
2943  *      that reconverts exactly to the given number, or to 'ilim' digits if
2944  *      that will yield a shorter result. The numerator and denominator in
2945  *      David Gay's conversion algorithm are known to fit in Tcl_WideUInt,
2946  *      giving considerably faster arithmetic than mp_int's.
2947  *
2948  * Results:
2949  *      Returns the string of significant decimal digits, in newly allocated
2950  *      memory
2951  *
2952  * Side effects:
2953  *      Stores the location of the decimal point in '*decpt' and the location
2954  *      of the terminal null byte in '*endPtr'.
2955  *
2956  *----------------------------------------------------------------------
2957  */
2958
2959 static inline char *
2960 ShorteningInt64Conversion(
2961     Double *dPtr,               /* Original number to convert. */
2962     int convType,               /* Type of conversion (shortest, Steele,
2963                                  * E format, F format). */
2964     Tcl_WideUInt bw,            /* Integer significand. */
2965     int b2, int b5,             /* Scale factor for the significand in the
2966                                  * numerator. */
2967     int m2plus, int m2minus, int m5,
2968                                 /* Scale factors for 1/2 ulp in the numerator
2969                                  * (will be different if bw == 1. */
2970     int s2, int s5,             /* Scale factors for the denominator. */
2971     int k,                      /* Number of output digits before the decimal
2972                                  * point. */
2973     int len,                    /* Number of digits to allocate. */
2974     int ilim,                   /* Number of digits to convert if b >= s */
2975     int ilim1,                  /* Number of digits to convert if b < s */
2976     int *decpt,                 /* OUTPUT: Position of the decimal point. */
2977     char **endPtr)              /* OUTPUT: Position of the terminal '\0' at
2978                                  *         the end of the returned string. */
2979 {
2980     char *retval = ckalloc(len + 1);
2981                                 /* Output buffer. */
2982     Tcl_WideUInt b = (bw * wuipow5[b5]) << b2;
2983                                 /* Numerator of the fraction being
2984                                  * converted. */
2985     Tcl_WideUInt S = wuipow5[s5] << s2;
2986                                 /* Denominator of the fraction being
2987                                  * converted. */
2988     Tcl_WideUInt mplus, mminus; /* Ranges for testing whether the result is
2989                                  * within roundoff of being exact. */
2990     int digit;                  /* Current output digit. */
2991     char *s = retval;           /* Cursor in the output buffer. */
2992     int i;                      /* Current position in the output buffer. */
2993
2994     /*
2995      * Adjust if the logarithm was guessed wrong.
2996      */
2997
2998     if (b < S) {
2999         b = 10 * b;
3000         ++m2plus; ++m2minus; ++m5;
3001         ilim = ilim1;
3002         --k;
3003     }
3004
3005     /*
3006      * Compute roundoff ranges.
3007      */
3008
3009     mplus = wuipow5[m5] << m2plus;
3010     mminus = wuipow5[m5] << m2minus;
3011
3012     /*
3013      * Loop through the digits.
3014      */
3015
3016     i = 1;
3017     for (;;) {
3018         digit = (int)(b / S);
3019         if (digit > 10) {
3020             Tcl_Panic("wrong digit!");
3021         }
3022         b = b % S;
3023
3024         /*
3025          * Does the current digit put us on the low side of the exact value
3026          * but within within roundoff of being exact?
3027          */
3028
3029         if (b < mplus || (b == mplus
3030                 && convType != TCL_DD_STEELE0 && (dPtr->w.word1 & 1) == 0)) {
3031             /*
3032              * Make sure we shouldn't be rounding *up* instead, in case the
3033              * next number above is closer.
3034              */
3035
3036             if (2 * b > S || (2 * b == S && (digit & 1) != 0)) {
3037                 ++digit;
3038                 if (digit == 10) {
3039                     *s++ = '9';
3040                     s = BumpUp(s, retval, &k);
3041                     break;
3042                 }
3043             }
3044
3045             /*
3046              * Stash the current digit.
3047              */
3048
3049             *s++ = '0' + digit;
3050             break;
3051         }
3052
3053         /*
3054          * Does one plus the current digit put us within roundoff of the
3055          * number?
3056          */
3057
3058         if (b > S - mminus || (b == S - mminus
3059                 && convType != TCL_DD_STEELE0 && (dPtr->w.word1 & 1) == 0)) {
3060             if (digit == 9) {
3061                 *s++ = '9';
3062                 s = BumpUp(s, retval, &k);
3063                 break;
3064             }
3065             ++digit;
3066             *s++ = '0' + digit;
3067             break;
3068         }
3069
3070         /*
3071          * Have we converted all the requested digits?
3072          */
3073
3074         *s++ = '0' + digit;
3075         if (i == ilim) {
3076             if (2*b > S || (2*b == S && (digit & 1) != 0)) {
3077                 s = BumpUp(s, retval, &k);
3078             }
3079             break;
3080         }
3081
3082         /*
3083          * Advance to the next digit.
3084          */
3085
3086         b = 10 * b;
3087         mplus = 10 * mplus;
3088         mminus = 10 * mminus;
3089         ++i;
3090     }
3091
3092     /*
3093      * Endgame - store the location of the decimal point and the end of the
3094      * string.
3095      */
3096
3097     *s = '\0';
3098     *decpt = k;
3099     if (endPtr) {
3100         *endPtr = s;
3101     }
3102     return retval;
3103 }
3104 \f
3105 /*
3106  *----------------------------------------------------------------------
3107  *
3108  * StrictInt64Conversion --
3109  *
3110  *      Converts a double-precision number to a fixed-length string of 'ilim'
3111  *      digits that reconverts exactly to the given number.  ('ilim' should be
3112  *      replaced with 'ilim1' in the case where log10(d) has been
3113  *      overestimated).  The numerator and denominator in David Gay's
3114  *      conversion algorithm are known to fit in Tcl_WideUInt, giving
3115  *      considerably faster arithmetic than mp_int's.
3116  *
3117  * Results:
3118  *      Returns the string of significant decimal digits, in newly allocated
3119  *      memory
3120  *
3121  * Side effects:
3122  *      Stores the location of the decimal point in '*decpt' and the location
3123  *      of the terminal null byte in '*endPtr'.
3124  *
3125  *----------------------------------------------------------------------
3126  */
3127
3128 static inline char *
3129 StrictInt64Conversion(
3130     Double *dPtr,               /* Original number to convert. */
3131     int convType,               /* Type of conversion (shortest, Steele,
3132                                  * E format, F format). */
3133     Tcl_WideUInt bw,            /* Integer significand. */
3134     int b2, int b5,             /* Scale factor for the significand in the
3135                                  * numerator. */
3136     int s2, int s5,             /* Scale factors for the denominator. */
3137     int k,                      /* Number of output digits before the decimal
3138                                  * point. */
3139     int len,                    /* Number of digits to allocate. */
3140     int ilim,                   /* Number of digits to convert if b >= s */
3141     int ilim1,                  /* Number of digits to convert if b < s */
3142     int *decpt,                 /* OUTPUT: Position of the decimal point. */
3143     char **endPtr)              /* OUTPUT: Position of the terminal '\0' at
3144                                  *         the end of the returned string. */
3145 {
3146     char *retval = ckalloc(len + 1);
3147                                 /* Output buffer. */
3148     Tcl_WideUInt b = (bw * wuipow5[b5]) << b2;
3149                                 /* Numerator of the fraction being
3150                                  * converted. */
3151     Tcl_WideUInt S = wuipow5[s5] << s2;
3152                                 /* Denominator of the fraction being
3153                                  * converted. */
3154     int digit;                  /* Current output digit. */
3155     char *s = retval;           /* Cursor in the output buffer. */
3156     int i;                      /* Current position in the output buffer. */
3157
3158     /*
3159      * Adjust if the logarithm was guessed wrong.
3160      */
3161
3162     if (b < S) {
3163         b = 10 * b;
3164         ilim = ilim1;
3165         --k;
3166     }
3167
3168     /*
3169      * Loop through the digits.
3170      */
3171
3172     i = 1;
3173     for (;;) {
3174         digit = (int)(b / S);
3175         if (digit > 10) {
3176             Tcl_Panic("wrong digit!");
3177         }
3178         b = b % S;
3179
3180         /*
3181          * Have we converted all the requested digits?
3182          */
3183
3184         *s++ = '0' + digit;
3185         if (i == ilim) {
3186             if (2*b > S || (2*b == S && (digit & 1) != 0)) {
3187                 s = BumpUp(s, retval, &k);
3188             } else {
3189                 while (*--s == '0') {
3190                     /* do nothing */
3191                 }
3192                 ++s;
3193             }
3194             break;
3195         }
3196
3197         /*
3198          * Advance to the next digit.
3199          */
3200
3201         b = 10 * b;
3202         ++i;
3203     }
3204
3205     /*
3206      * Endgame - store the location of the decimal point and the end of the
3207      * string.
3208      */
3209
3210     *s = '\0';
3211     *decpt = k;
3212     if (endPtr) {
3213         *endPtr = s;
3214     }
3215     return retval;
3216 }
3217 \f
3218 /*
3219  *----------------------------------------------------------------------
3220  *
3221  * ShouldBankerRoundUpPowD --
3222  *
3223  *      Test whether bankers' rounding should round a digit up. Assumption is
3224  *      made that the denominator of the fraction being tested is a power of
3225  *      2**MP_DIGIT_BIT.
3226  *
3227  * Results:
3228  *      Returns 1 iff the fraction is more than 1/2, or if the fraction is
3229  *      exactly 1/2 and the digit is odd.
3230  *
3231  *----------------------------------------------------------------------
3232  */
3233
3234 static inline int
3235 ShouldBankerRoundUpPowD(
3236     mp_int *b,                  /* Numerator of the fraction. */
3237     int sd,                     /* Denominator is 2**(sd*MP_DIGIT_BIT). */
3238     int isodd)                  /* 1 if the digit is odd, 0 if even. */
3239 {
3240     int i;
3241     static const mp_digit topbit = ((mp_digit)1) << (MP_DIGIT_BIT - 1);
3242
3243     if (b->used < sd || (b->dp[sd-1] & topbit) == 0) {
3244         return 0;
3245     }
3246     if (b->dp[sd-1] != topbit) {
3247         return 1;
3248     }
3249     for (i = sd-2; i >= 0; --i) {
3250         if (b->dp[i] != 0) {
3251             return 1;
3252         }
3253     }
3254     return isodd;
3255 }
3256 \f
3257 /*
3258  *----------------------------------------------------------------------
3259  *
3260  * ShouldBankerRoundUpToNextPowD --
3261  *
3262  *      Tests whether bankers' rounding will round down in the "denominator is
3263  *      a power of 2**MP_DIGIT" case.
3264  *
3265  * Results:
3266  *      Returns 1 if the rounding will be performed - which increases the
3267  *      digit by one - and 0 otherwise.
3268  *
3269  *----------------------------------------------------------------------
3270  */
3271
3272 static inline int
3273 ShouldBankerRoundUpToNextPowD(
3274     mp_int *b,                  /* Numerator of the fraction. */
3275     mp_int *m,                  /* Numerator of the rounding tolerance. */
3276     int sd,                     /* Common denominator is 2**(sd*MP_DIGIT_BIT). */
3277     int convType,               /* Conversion type: STEELE defeats
3278                                  * round-to-even (not sure why one wants to do
3279                                  * this; I copied it from Gay). FIXME */
3280     int isodd,                  /* 1 if the integer significand is odd. */
3281     mp_int *temp)               /* Work area for the calculation. */
3282 {
3283     int i;
3284
3285     /*
3286      * Compare B and S-m - which is the same as comparing B+m and S - which we
3287      * do by computing b+m and doing a bitwhack compare against
3288      * 2**(MP_DIGIT_BIT*sd)
3289      */
3290
3291     mp_add(b, m, temp);
3292     if (temp->used <= sd) {     /* Too few digits to be > s */
3293         return 0;
3294     }
3295     if (temp->used > sd+1 || temp->dp[sd] > 1) {
3296                                 /* >= 2s */
3297         return 1;
3298     }
3299     for (i = sd-1; i >= 0; --i) {
3300                                 /* Check for ==s */
3301         if (temp->dp[i] != 0) { /* > s */
3302             return 1;
3303         }
3304     }
3305     if (convType == TCL_DD_STEELE0) {
3306                                 /* Biased rounding. */
3307         return 0;
3308     }
3309     return isodd;
3310 }
3311 \f
3312 /*
3313  *----------------------------------------------------------------------
3314  *
3315  * ShorteningBignumConversionPowD --
3316  *
3317  *      Converts a double-precision number to the shortest string of digits
3318  *      that reconverts exactly to the given number, or to 'ilim' digits if
3319  *      that will yield a shorter result. The denominator in David Gay's
3320  *      conversion algorithm is known to be a power of 2**MP_DIGIT_BIT, and hence
3321  *      the division in the main loop may be replaced by a digit shift and
3322  *      mask.
3323  *
3324  * Results:
3325  *      Returns the string of significant decimal digits, in newly allocated
3326  *      memory
3327  *
3328  * Side effects:
3329  *      Stores the location of the decimal point in '*decpt' and the location
3330  *      of the terminal null byte in '*endPtr'.
3331  *
3332  *----------------------------------------------------------------------
3333  */
3334
3335 static inline char *
3336 ShorteningBignumConversionPowD(
3337     Double *dPtr,               /* Original number to convert. */
3338     int convType,               /* Type of conversion (shortest, Steele,
3339                                  * E format, F format). */
3340     Tcl_WideUInt bw,            /* Integer significand. */
3341     int b2, int b5,             /* Scale factor for the significand in the
3342                                  * numerator. */
3343     int m2plus, int m2minus, int m5,
3344                                 /* Scale factors for 1/2 ulp in the numerator
3345                                  * (will be different if bw == 1). */
3346     int sd,                     /* Scale factor for the denominator. */
3347     int k,                      /* Number of output digits before the decimal
3348                                  * point. */
3349     int len,                    /* Number of digits to allocate. */
3350     int ilim,                   /* Number of digits to convert if b >= s */
3351     int ilim1,                  /* Number of digits to convert if b < s */
3352     int *decpt,                 /* OUTPUT: Position of the decimal point. */
3353     char **endPtr)              /* OUTPUT: Position of the terminal '\0' at
3354                                  *         the end of the returned string. */
3355 {
3356     char *retval = ckalloc(len + 1);
3357                                 /* Output buffer. */
3358     mp_int b;                   /* Numerator of the fraction being
3359                                  * converted. */
3360     mp_int mplus, mminus;       /* Bounds for roundoff. */
3361     mp_digit digit;             /* Current output digit. */
3362     char *s = retval;           /* Cursor in the output buffer. */
3363     int i;                      /* Index in the output buffer. */
3364     mp_int temp;
3365     int r1;
3366
3367     /*
3368      * b = bw * 2**b2 * 5**b5
3369      * mminus = 5**m5
3370      */
3371
3372     TclBNInitBignumFromWideUInt(&b, bw);
3373     mp_init_set(&mminus, 1);
3374     MulPow5(&b, b5, &b);
3375     mp_mul_2d(&b, b2, &b);
3376
3377     /*
3378      * Adjust if the logarithm was guessed wrong.
3379      */
3380
3381     if (b.used <= sd) {
3382         mp_mul_d(&b, 10, &b);
3383         ++m2plus; ++m2minus; ++m5;
3384         ilim = ilim1;
3385         --k;
3386     }
3387
3388     /*
3389      * mminus = 5**m5 * 2**m2minus
3390      * mplus = 5**m5 * 2**m2plus
3391      */
3392
3393     mp_mul_2d(&mminus, m2minus, &mminus);
3394     MulPow5(&mminus, m5, &mminus);
3395     if (m2plus > m2minus) {
3396         mp_init_copy(&mplus, &mminus);
3397         mp_mul_2d(&mplus, m2plus-m2minus, &mplus);
3398     }
3399     mp_init(&temp);
3400
3401     /*
3402      * Loop through the digits. Do division and mod by s == 2**(sd*MP_DIGIT_BIT)
3403      * by mp_digit extraction.
3404      */
3405
3406     i = 0;
3407     for (;;) {
3408         if (b.used <= sd) {
3409             digit = 0;
3410         } else {
3411             digit = b.dp[sd];
3412             if (b.used > sd+1 || digit >= 10) {
3413                 Tcl_Panic("wrong digit!");
3414             }
3415             --b.used; mp_clamp(&b);
3416         }
3417
3418         /*
3419          * Does the current digit put us on the low side of the exact value
3420          * but within within roundoff of being exact?
3421          */
3422
3423         r1 = mp_cmp_mag(&b, (m2plus > m2minus)? &mplus : &mminus);
3424         if (r1 == MP_LT || (r1 == MP_EQ
3425                 && convType != TCL_DD_STEELE0 && (dPtr->w.word1 & 1) == 0)) {
3426             /*
3427              * Make sure we shouldn't be rounding *up* instead, in case the
3428              * next number above is closer.
3429              */
3430
3431             if (ShouldBankerRoundUpPowD(&b, sd, digit&1)) {
3432                 ++digit;
3433                 if (digit == 10) {
3434                     *s++ = '9';
3435                     s = BumpUp(s, retval, &k);
3436                     break;
3437                 }
3438             }
3439
3440             /*
3441              * Stash the last digit.
3442              */
3443
3444             *s++ = '0' + digit;
3445             break;
3446         }
3447
3448         /*
3449          * Does one plus the current digit put us within roundoff of the
3450          * number?
3451          */
3452
3453         if (ShouldBankerRoundUpToNextPowD(&b, &mminus, sd, convType,
3454                 dPtr->w.word1 & 1, &temp)) {
3455             if (digit == 9) {
3456                 *s++ = '9';
3457                 s = BumpUp(s, retval, &k);
3458                 break;
3459             }
3460             ++digit;
3461             *s++ = '0' + digit;
3462             break;
3463         }
3464
3465         /*
3466          * Have we converted all the requested digits?
3467          */
3468
3469         *s++ = '0' + digit;
3470         if (i == ilim) {
3471             if (ShouldBankerRoundUpPowD(&b, sd, digit&1)) {
3472                 s = BumpUp(s, retval, &k);
3473             }
3474             break;
3475         }
3476
3477         /*
3478          * Advance to the next digit.
3479          */
3480
3481         mp_mul_d(&b, 10, &b);
3482         mp_mul_d(&mminus, 10, &mminus);
3483         if (m2plus > m2minus) {
3484             mp_mul_2d(&mminus, m2plus-m2minus, &mplus);
3485         }
3486         ++i;
3487     }
3488
3489     /*
3490      * Endgame - store the location of the decimal point and the end of the
3491      * string.
3492      */
3493
3494     if (m2plus > m2minus) {
3495         mp_clear(&mplus);
3496     }
3497     mp_clear_multi(&b, &mminus, &temp, NULL);
3498     *s = '\0';
3499     *decpt = k;
3500     if (endPtr) {
3501         *endPtr = s;
3502     }
3503     return retval;
3504 }
3505 \f
3506 /*
3507  *----------------------------------------------------------------------
3508  *
3509  * StrictBignumConversionPowD --
3510  *
3511  *      Converts a double-precision number to a fixed-lengt string of 'ilim'
3512  *      digits (or 'ilim1' if log10(d) has been overestimated).  The
3513  *      denominator in David Gay's conversion algorithm is known to be a power
3514  *      of 2**MP_DIGIT_BIT, and hence the division in the main loop may be
3515  *      replaced by a digit shift and mask.
3516  *
3517  * Results:
3518  *      Returns the string of significant decimal digits, in newly allocated
3519  *      memory.
3520  *
3521  * Side effects:
3522  *      Stores the location of the decimal point in '*decpt' and the location
3523  *      of the terminal null byte in '*endPtr'.
3524  *
3525  *----------------------------------------------------------------------
3526  */
3527
3528 static inline char *
3529 StrictBignumConversionPowD(
3530     Double *dPtr,               /* Original number to convert. */
3531     int convType,               /* Type of conversion (shortest, Steele,
3532                                  * E format, F format). */
3533     Tcl_WideUInt bw,            /* Integer significand. */
3534     int b2, int b5,             /* Scale factor for the significand in the
3535                                  * numerator. */
3536     int sd,                     /* Scale factor for the denominator. */
3537     int k,                      /* Number of output digits before the decimal
3538                                  * point. */
3539     int len,                    /* Number of digits to allocate. */
3540     int ilim,                   /* Number of digits to convert if b >= s */
3541     int ilim1,                  /* Number of digits to convert if b < s */
3542     int *decpt,                 /* OUTPUT: Position of the decimal point. */
3543     char **endPtr)              /* OUTPUT: Position of the terminal '\0' at
3544                                  *         the end of the returned string. */
3545 {
3546     char *retval = ckalloc(len + 1);
3547                                 /* Output buffer. */
3548     mp_int b;                   /* Numerator of the fraction being
3549                                  * converted. */
3550     mp_digit digit;             /* Current output digit. */
3551     char *s = retval;           /* Cursor in the output buffer. */
3552     int i;                      /* Index in the output buffer. */
3553     mp_int temp;
3554
3555     /*
3556      * b = bw * 2**b2 * 5**b5
3557      */
3558
3559     TclBNInitBignumFromWideUInt(&b, bw);
3560     MulPow5(&b, b5, &b);
3561     mp_mul_2d(&b, b2, &b);
3562
3563     /*
3564      * Adjust if the logarithm was guessed wrong.
3565      */
3566
3567     if (b.used <= sd) {
3568         mp_mul_d(&b, 10, &b);
3569         ilim = ilim1;
3570         --k;
3571     }
3572     mp_init(&temp);
3573
3574     /*
3575      * Loop through the digits. Do division and mod by s == 2**(sd*MP_DIGIT_BIT)
3576      * by mp_digit extraction.
3577      */
3578
3579     i = 1;
3580     for (;;) {
3581         if (b.used <= sd) {
3582             digit = 0;
3583         } else {
3584             digit = b.dp[sd];
3585             if (b.used > sd+1 || digit >= 10) {
3586                 Tcl_Panic("wrong digit!");
3587             }
3588             --b.used;
3589             mp_clamp(&b);
3590         }
3591
3592         /*
3593          * Have we converted all the requested digits?
3594          */
3595
3596         *s++ = '0' + digit;
3597         if (i == ilim) {
3598             if (ShouldBankerRoundUpPowD(&b, sd, digit&1)) {
3599                 s = BumpUp(s, retval, &k);
3600             }
3601             while (*--s == '0') {
3602                 /* do nothing */
3603             }
3604             ++s;
3605             break;
3606         }
3607
3608         /*
3609          * Advance to the next digit.
3610          */
3611
3612         mp_mul_d(&b, 10, &b);
3613         ++i;
3614     }
3615
3616     /*
3617      * Endgame - store the location of the decimal point and the end of the
3618      * string.
3619      */
3620
3621     mp_clear_multi(&b, &temp, NULL);
3622     *s = '\0';
3623     *decpt = k;
3624     if (endPtr) {
3625         *endPtr = s;
3626     }
3627     return retval;
3628 }
3629 \f
3630 /*
3631  *----------------------------------------------------------------------
3632  *
3633  * ShouldBankerRoundUp --
3634  *
3635  *      Tests whether a digit should be rounded up or down when finishing
3636  *      bignum-based floating point conversion.
3637  *
3638  * Results:
3639  *      Returns 1 if the number needs to be rounded up, 0 otherwise.
3640  *
3641  *----------------------------------------------------------------------
3642  */
3643
3644 static inline int
3645 ShouldBankerRoundUp(
3646     mp_int *twor,               /* 2x the remainder from thd division that
3647                                  * produced the last digit. */
3648     mp_int *S,                  /* Denominator. */
3649     int isodd)                  /* Flag == 1 if the last digit is odd. */
3650 {
3651     int r = mp_cmp_mag(twor, S);
3652
3653     switch (r) {
3654     case MP_LT:
3655         return 0;
3656     case MP_EQ:
3657         return isodd;
3658     case MP_GT:
3659         return 1;
3660     }
3661     Tcl_Panic("in ShouldBankerRoundUp, trichotomy fails!");
3662     return 0;
3663 }
3664 \f
3665 /*
3666  *----------------------------------------------------------------------
3667  *
3668  * ShouldBankerRoundUpToNext --
3669  *
3670  *      Tests whether the remainder is great enough to force rounding to the
3671  *      next higher digit.
3672  *
3673  * Results:
3674  *      Returns 1 if the number should be rounded up, 0 otherwise.
3675  *
3676  *----------------------------------------------------------------------
3677  */
3678
3679 static inline int
3680 ShouldBankerRoundUpToNext(
3681     mp_int *b,                  /* Remainder from the division that produced
3682                                  * the last digit. */
3683     mp_int *m,                  /* Numerator of the rounding tolerance. */
3684     mp_int *S,                  /* Denominator. */
3685     int convType,               /* Conversion type: STEELE0 defeats
3686                                  * round-to-even. (Not sure why one would want
3687                                  * this; I coped it from Gay). FIXME */
3688     int isodd,                  /* 1 if the integer significand is odd. */
3689     mp_int *temp)               /* Work area needed for the calculation. */
3690 {
3691     int r;
3692
3693     /*
3694      * Compare b and S-m: this is the same as comparing B+m and S.
3695      */
3696
3697     mp_add(b, m, temp);
3698     r = mp_cmp_mag(temp, S);
3699     switch(r) {
3700     case MP_LT:
3701         return 0;
3702     case MP_EQ:
3703         if (convType == TCL_DD_STEELE0) {
3704             return 0;
3705         } else {
3706             return isodd;
3707         }
3708     case MP_GT:
3709         return 1;
3710     }
3711     Tcl_Panic("in ShouldBankerRoundUpToNext, trichotomy fails!");
3712     return 0;
3713 }
3714 \f
3715 /*
3716  *----------------------------------------------------------------------
3717  *
3718  * ShorteningBignumConversion --
3719  *
3720  *      Convert a floating point number to a variable-length digit string
3721  *      using the multiprecision method.
3722  *
3723  * Results:
3724  *      Returns the string of digits.
3725  *
3726  * Side effects:
3727  *      Stores the position of the decimal point in *decpt.  Stores a pointer
3728  *      to the end of the number in *endPtr.
3729  *
3730  *----------------------------------------------------------------------
3731  */
3732
3733 static inline char *
3734 ShorteningBignumConversion(
3735     Double *dPtr,               /* Original number being converted. */
3736     int convType,               /* Conversion type. */
3737     Tcl_WideUInt bw,            /* Integer significand and exponent. */
3738     int b2,                     /* Scale factor for the significand. */
3739     int m2plus, int m2minus,    /* Scale factors for 1/2 ulp in numerator. */
3740     int s2, int s5,             /* Scale factors for denominator. */
3741     int k,                      /* Guessed position of the decimal point. */
3742     int len,                    /* Size of the digit buffer to allocate. */
3743     int ilim,                   /* Number of digits to convert if b >= s */
3744     int ilim1,                  /* Number of digits to convert if b < s */
3745     int *decpt,                 /* OUTPUT: Position of the decimal point. */
3746     char **endPtr)              /* OUTPUT: Pointer to the end of the number */
3747 {
3748     char *retval = ckalloc(len+1);
3749                                 /* Buffer of digits to return. */
3750     char *s = retval;           /* Cursor in the return value. */
3751     mp_int b;                   /* Numerator of the result. */
3752     mp_int mminus;              /* 1/2 ulp below the result. */
3753     mp_int mplus;               /* 1/2 ulp above the result. */
3754     mp_int S;                   /* Denominator of the result. */
3755     mp_int dig;                 /* Current digit of the result. */
3756     int digit;                  /* Current digit of the result. */
3757     mp_int temp;                /* Work area. */
3758     int minit = 1;              /* Fudge factor for when we misguess k. */
3759     int i;
3760     int r1;
3761
3762     /*
3763      * b = bw * 2**b2 * 5**b5
3764      * S = 2**s2 * 5*s5
3765      */
3766
3767     TclBNInitBignumFromWideUInt(&b, bw);
3768     mp_mul_2d(&b, b2, &b);
3769     mp_init_set(&S, 1);
3770     MulPow5(&S, s5, &S); mp_mul_2d(&S, s2, &S);
3771
3772     /*
3773      * Handle the case where we guess the position of the decimal point wrong.
3774      */
3775
3776     if (mp_cmp_mag(&b, &S) == MP_LT) {
3777         mp_mul_d(&b, 10, &b);
3778         minit = 10;
3779         ilim =ilim1;
3780         --k;
3781     }
3782
3783     /*
3784      * mminus = 2**m2minus * 5**m5
3785      */
3786
3787     mp_init_set(&mminus, minit);
3788     mp_mul_2d(&mminus, m2minus, &mminus);
3789     if (m2plus > m2minus) {
3790         mp_init_copy(&mplus, &mminus);
3791         mp_mul_2d(&mplus, m2plus-m2minus, &mplus);
3792     }
3793     mp_init(&temp);
3794
3795     /*
3796      * Loop through the digits.
3797      */
3798
3799     mp_init(&dig);
3800     i = 1;
3801     for (;;) {
3802         mp_div(&b, &S, &dig, &b);
3803         if (dig.used > 1 || dig.dp[0] >= 10) {
3804             Tcl_Panic("wrong digit!");
3805         }
3806         digit = dig.dp[0];
3807
3808         /*
3809          * Does the current digit leave us with a remainder small enough to
3810          * round to it?
3811          */
3812
3813         r1 = mp_cmp_mag(&b, (m2plus > m2minus)? &mplus : &mminus);
3814         if (r1 == MP_LT || (r1 == MP_EQ
3815                 && convType != TCL_DD_STEELE0 && (dPtr->w.word1 & 1) == 0)) {
3816             mp_mul_2d(&b, 1, &b);
3817             if (ShouldBankerRoundUp(&b, &S, digit&1)) {
3818                 ++digit;
3819                 if (digit == 10) {
3820                     *s++ = '9';
3821                     s = BumpUp(s, retval, &k);
3822                     break;
3823                 }
3824             }
3825             *s++ = '0' + digit;
3826             break;
3827         }
3828
3829         /*
3830          * Does the current digit leave us with a remainder large enough to
3831          * commit to rounding up to the next higher digit?
3832          */
3833
3834         if (ShouldBankerRoundUpToNext(&b, &mminus, &S, convType,
3835                 dPtr->w.word1 & 1, &temp)) {
3836             ++digit;
3837             if (digit == 10) {
3838                 *s++ = '9';
3839                 s = BumpUp(s, retval, &k);
3840                 break;
3841             }
3842             *s++ = '0' + digit;
3843             break;
3844         }
3845
3846         /*
3847          * Have we converted all the requested digits?
3848          */
3849
3850         *s++ = '0' + digit;
3851         if (i == ilim) {
3852             mp_mul_2d(&b, 1, &b);
3853             if (ShouldBankerRoundUp(&b, &S, digit&1)) {
3854                 s = BumpUp(s, retval, &k);
3855             }
3856             break;
3857         }
3858
3859         /*
3860          * Advance to the next digit.
3861          */
3862
3863         if (s5 > 0) {
3864             /*
3865              * Can possibly shorten the denominator.
3866              */
3867
3868             mp_mul_2d(&b, 1, &b);
3869             mp_mul_2d(&mminus, 1, &mminus);
3870             if (m2plus > m2minus) {
3871                 mp_mul_2d(&mplus, 1, &mplus);
3872             }
3873             mp_div_d(&S, 5, &S, NULL);
3874             --s5;
3875
3876             /*
3877              * IDEA: It might possibly be a win to fall back to int64_t
3878              *       arithmetic here if S < 2**64/10. But it's a win only for
3879              *       a fairly narrow range of magnitudes so perhaps not worth
3880              *       bothering.  We already know that we shorten the
3881              *       denominator by at least 1 mp_digit, perhaps 2, as we do
3882              *       the conversion for 17 digits of significance.
3883              * Possible savings:
3884              * 10**26   1 trip through loop before fallback possible
3885              * 10**27   1 trip
3886              * 10**28   2 trips
3887              * 10**29   3 trips
3888              * 10**30   4 trips
3889              * 10**31   5 trips
3890              * 10**32   6 trips
3891              * 10**33   7 trips
3892              * 10**34   8 trips
3893              * 10**35   9 trips
3894              * 10**36  10 trips
3895              * 10**37  11 trips
3896              * 10**38  12 trips
3897              * 10**39  13 trips
3898              * 10**40  14 trips
3899              * 10**41  15 trips
3900              * 10**42  16 trips
3901              * thereafter no gain.
3902              */
3903         } else {
3904             mp_mul_d(&b, 10, &b);
3905             mp_mul_d(&mminus, 10, &mminus);
3906             if (m2plus > m2minus) {
3907                 mp_mul_2d(&mplus, 10, &mplus);
3908             }
3909         }
3910
3911         ++i;
3912     }
3913
3914     /*
3915      * Endgame - store the location of the decimal point and the end of the
3916      * string.
3917      */
3918
3919     if (m2plus > m2minus) {
3920         mp_clear(&mplus);
3921     }
3922     mp_clear_multi(&b, &mminus, &temp, &dig, &S, NULL);
3923     *s = '\0';
3924     *decpt = k;
3925     if (endPtr) {
3926         *endPtr = s;
3927     }
3928     return retval;
3929 }
3930 \f
3931 /*
3932  *----------------------------------------------------------------------
3933  *
3934  * StrictBignumConversion --
3935  *
3936  *      Convert a floating point number to a fixed-length digit string using
3937  *      the multiprecision method.
3938  *
3939  * Results:
3940  *      Returns the string of digits.
3941  *
3942  * Side effects:
3943  *      Stores the position of the decimal point in *decpt.  Stores a pointer
3944  *      to the end of the number in *endPtr.
3945  *
3946  *----------------------------------------------------------------------
3947  */
3948
3949 static inline char *
3950 StrictBignumConversion(
3951     Double *dPtr,               /* Original number being converted. */
3952     int convType,               /* Conversion type. */
3953     Tcl_WideUInt bw,            /* Integer significand and exponent. */
3954     int b2,                     /* Scale factor for the significand. */
3955     int s2, int s5,             /* Scale factors for denominator. */
3956     int k,                      /* Guessed position of the decimal point. */
3957     int len,                    /* Size of the digit buffer to allocate. */
3958     int ilim,                   /* Number of digits to convert if b >= s */
3959     int ilim1,                  /* Number of digits to convert if b < s */
3960     int *decpt,                 /* OUTPUT: Position of the decimal point. */
3961     char **endPtr)              /* OUTPUT: Pointer to the end of the number */
3962 {
3963     char *retval = ckalloc(len+1);
3964                                 /* Buffer of digits to return. */
3965     char *s = retval;           /* Cursor in the return value. */
3966     mp_int b;                   /* Numerator of the result. */
3967     mp_int S;                   /* Denominator of the result. */
3968     mp_int dig;                 /* Current digit of the result. */
3969     int digit;                  /* Current digit of the result. */
3970     mp_int temp;                /* Work area. */
3971     int g;                      /* Size of the current digit ground. */
3972     int i, j;
3973
3974     /*
3975      * b = bw * 2**b2 * 5**b5
3976      * S = 2**s2 * 5*s5
3977      */
3978
3979     mp_init_multi(&temp, &dig, NULL);
3980     TclBNInitBignumFromWideUInt(&b, bw);
3981     mp_mul_2d(&b, b2, &b);
3982     mp_init_set(&S, 1);
3983     MulPow5(&S, s5, &S); mp_mul_2d(&S, s2, &S);
3984
3985     /*
3986      * Handle the case where we guess the position of the decimal point wrong.
3987      */
3988
3989     if (mp_cmp_mag(&b, &S) == MP_LT) {
3990         mp_mul_d(&b, 10, &b);
3991         ilim =ilim1;
3992         --k;
3993     }
3994
3995     /*
3996      * Convert the leading digit.
3997      */
3998
3999     i = 0;
4000     mp_div(&b, &S, &dig, &b);
4001     if (dig.used > 1 || dig.dp[0] >= 10) {
4002         Tcl_Panic("wrong digit!");
4003     }
4004     digit = dig.dp[0];
4005
4006     /*
4007      * Is a single digit all that was requested?
4008      */
4009
4010     *s++ = '0' + digit;
4011     if (++i >= ilim) {
4012         mp_mul_2d(&b, 1, &b);
4013         if (ShouldBankerRoundUp(&b, &S, digit&1)) {
4014             s = BumpUp(s, retval, &k);
4015         }
4016     } else {
4017         for (;;) {
4018             /*
4019              * Shift by a group of digits.
4020              */
4021
4022             g = ilim - i;
4023             if (g > DIGIT_GROUP) {
4024                 g = DIGIT_GROUP;
4025             }
4026             if (s5 >= g) {
4027                 mp_div_d(&S, dpow5[g], &S, NULL);
4028                 s5 -= g;
4029             } else if (s5 > 0) {
4030                 mp_div_d(&S, dpow5[s5], &S, NULL);
4031                 mp_mul_d(&b, dpow5[g - s5], &b);
4032                 s5 = 0;
4033             } else {
4034                 mp_mul_d(&b, dpow5[g], &b);
4035             }
4036             mp_mul_2d(&b, g, &b);
4037
4038             /*
4039              * As with the shortening bignum conversion, it's possible at this
4040              * point that we will have reduced the denominator to less than
4041              * 2**64/10, at which point it would be possible to fall back to
4042              * to int64_t arithmetic. But the potential payoff is tremendously
4043              * less - unless we're working in F format - because we know that
4044              * three groups of digits will always suffice for %#.17e, the
4045              * longest format that doesn't introduce empty precision.
4046              *
4047              * Extract the next group of digits.
4048              */
4049
4050             mp_div(&b, &S, &dig, &b);
4051             if (dig.used > 1) {
4052                 Tcl_Panic("wrong digit!");
4053             }
4054             digit = dig.dp[0];
4055             for (j = g-1; j >= 0; --j) {
4056                 int t = itens[j];
4057
4058                 *s++ = digit / t + '0';
4059                 digit %= t;
4060             }
4061             i += g;
4062
4063             /*
4064              * Have we converted all the requested digits?
4065              */
4066
4067             if (i == ilim) {
4068                 mp_mul_2d(&b, 1, &b);
4069                 if (ShouldBankerRoundUp(&b, &S, digit&1)) {
4070                     s = BumpUp(s, retval, &k);
4071                 }
4072                 break;
4073             }
4074         }
4075     }
4076     while (*--s == '0') {
4077         /* do nothing */
4078     }
4079     ++s;
4080
4081     /*
4082      * Endgame - store the location of the decimal point and the end of the
4083      * string.
4084      */
4085
4086     mp_clear_multi(&b, &S, &temp, &dig, NULL);
4087     *s = '\0';
4088     *decpt = k;
4089     if (endPtr) {
4090         *endPtr = s;
4091     }
4092     return retval;
4093 }
4094 \f
4095 /*
4096  *----------------------------------------------------------------------
4097  *
4098  * TclDoubleDigits --
4099  *
4100  *      Core of Tcl's conversion of double-precision floating point numbers to
4101  *      decimal.
4102  *
4103  * Results:
4104  *      Returns a newly-allocated string of digits.
4105  *
4106  * Side effects:
4107  *      Sets *decpt to the index of the character in the string before the
4108  *      place that the decimal point should go. If 'endPtr' is not NULL, sets
4109  *      endPtr to point to the terminating '\0' byte of the string. Sets *sign
4110  *      to 1 if a minus sign should be printed with the number, or 0 if a plus
4111  *      sign (or no sign) should appear.
4112  *
4113  * This function is a service routine that produces the string of digits for
4114  * floating-point-to-decimal conversion. It can do a number of things
4115  * according to the 'flags' argument. Valid values for 'flags' include:
4116  *      TCL_DD_SHORTEST - This is the default for floating point conversion if
4117  *              ::tcl_precision is 0. It constructs the shortest string of
4118  *              digits that will reconvert to the given number when scanned.
4119  *              For floating point numbers that are exactly between two
4120  *              decimal numbers, it resolves using the 'round to even' rule.
4121  *              With this value, the 'ndigits' parameter is ignored.
4122  *      TCL_DD_STEELE - This value is not recommended and may be removed in
4123  *              the future. It follows the conversion algorithm outlined in
4124  *              "How to Print Floating-Point Numbers Accurately" by Guy
4125  *              L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90,
4126  *              pp. 112-126]. This rule has the effect of rendering 1e23 as
4127  *              9.9999999999999999e22 - which is a 'better' approximation in
4128  *              the sense that it will reconvert correctly even if a
4129  *              subsequent input conversion is 'round up' or 'round down'
4130  *              rather than 'round to nearest', but is surprising otherwise.
4131  *      TCL_DD_E_FORMAT - This value is used to prepare numbers for %e format
4132  *              conversion (or for default floating->string if tcl_precision
4133  *              is not 0). It constructs a string of at most 'ndigits' digits,
4134  *              choosing the one that is closest to the given number (and
4135  *              resolving ties with 'round to even').  It is allowed to return
4136  *              fewer than 'ndigits' if the number converts exactly; if the
4137  *              TCL_DD_E_FORMAT|TCL_DD_SHORTEN_FLAG is supplied instead, it
4138  *              also returns fewer digits if the shorter string will still
4139  *              reconvert without loss to the given input number. In any case,
4140  *              strings of trailing zeroes are suppressed.
4141  *      TCL_DD_F_FORMAT - This value is used to prepare numbers for %f format
4142  *              conversion. It requests that conversion proceed until
4143  *              'ndigits' digits after the decimal point have been converted.
4144  *              It is possible for this format to result in a zero-length
4145  *              string if the number is sufficiently small. Again, it is
4146  *              permissible for TCL_DD_F_FORMAT to return fewer digits for a
4147  *              number that converts exactly, and changing the argument to
4148  *              TCL_DD_F_FORMAT|TCL_DD_SHORTEN_FLAG will allow the routine
4149  *              also to return fewer digits if the shorter string will still
4150  *              reconvert without loss to the given input number. Strings of
4151  *              trailing zeroes are suppressed.
4152  *
4153  *      To any of these flags may be OR'ed TCL_DD_NO_QUICK; this flag requires
4154  *      all calculations to be done in exact arithmetic. Normally, E and F
4155  *      format with fewer than about 14 digits will be done with a quick
4156  *      floating point approximation and fall back on the exact arithmetic
4157  *      only if the input number is close enough to the midpoint between two
4158  *      decimal strings that more precision is needed to resolve which string
4159  *      is correct.
4160  *
4161  * The value stored in the 'decpt' argument on return may be negative
4162  * (indicating that the decimal point falls to the left of the string) or
4163  * greater than the length of the string. In addition, the value -9999 is used
4164  * as a sentinel to indicate that the string is one of the special values
4165  * "Infinity" and "NaN", and that no decimal point should be inserted.
4166  *
4167  *----------------------------------------------------------------------
4168  */
4169
4170 char *
4171 TclDoubleDigits(
4172     double dv,                  /* Number to convert. */
4173     int ndigits,                /* Number of digits requested. */
4174     int flags,                  /* Conversion flags. */
4175     int *decpt,                 /* OUTPUT: Position of the decimal point. */
4176     int *sign,                  /* OUTPUT: 1 if the result is negative. */
4177     char **endPtr)              /* OUTPUT: If not NULL, receives a pointer to
4178                                  *         one character beyond the end of the
4179                                  *         returned string. */
4180 {
4181     int convType = (flags & TCL_DD_CONVERSION_TYPE_MASK);
4182                                 /* Type of conversion being performed:
4183                                  * TCL_DD_SHORTEST0, TCL_DD_STEELE0,
4184                                  * TCL_DD_E_FORMAT, or TCL_DD_F_FORMAT. */
4185     Double d;                   /* Union for deconstructing doubles. */
4186     Tcl_WideUInt bw;            /* Integer significand. */
4187     int be;                     /* Power of 2 by which b must be multiplied */
4188     int bbits;                  /* Number of bits needed to represent b. */
4189     int denorm;                 /* Flag == 1 iff the input number was
4190                                  * denormalized. */
4191     int k;                      /* Estimate of floor(log10(d)). */
4192     int k_check;                /* Flag == 1 if d is near enough to a power of
4193                                  * ten that k must be checked. */
4194     int b2, b5, s2, s5;         /* Powers of 2 and 5 in the numerator and
4195                                  * denominator of intermediate results. */
4196     int ilim = -1, ilim1 = -1;  /* Number of digits to convert, and number to
4197                                  * convert if log10(d) has been
4198                                  * overestimated. */
4199     char *retval;               /* Return value from this function. */
4200     int i = -1;
4201
4202     /*
4203      * Put the input number into a union for bit-whacking.
4204      */
4205
4206     d.d = dv;
4207
4208     /*
4209      * Handle the cases of negative numbers (by taking the absolute value:
4210      * this includes -Inf and -NaN!), infinity, Not a Number, and zero.
4211      */
4212
4213     TakeAbsoluteValue(&d, sign);
4214     if ((d.w.word0 & EXP_MASK) == EXP_MASK) {
4215         return FormatInfAndNaN(&d, decpt, endPtr);
4216     }
4217     if (d.d == 0.0) {
4218         return FormatZero(decpt, endPtr);
4219     }
4220
4221     /*
4222      * Unpack the floating point into a wide integer and an exponent.
4223      * Determine the number of bits that the big integer requires, and compute
4224      * a quick approximation (which may be one too high) of ceil(log10(d.d)).
4225      */
4226
4227     denorm = ((d.w.word0 & EXP_MASK) == 0);
4228     DoubleToExpAndSig(d.d, &bw, &be, &bbits);
4229     k = ApproximateLog10(bw, be, bbits);
4230     k = BetterLog10(d.d, k, &k_check);
4231
4232     /* At this point, we have:
4233      *    d is the number to convert.
4234      *    bw are significand and exponent: d == bw*2**be,
4235      *    bbits is the length of bw: 2**bbits-1 <= bw < 2**bbits
4236      *    k is either ceil(log10(d)) or ceil(log10(d))+1. k_check is 0 if we
4237      *      know that k is exactly ceil(log10(d)) and 1 if we need to check.
4238      *    We want a rational number
4239      *      r = b * 10**(1-k) = bw * 2**b2 * 5**b5 / (2**s2 / 5**s5),
4240      *    with b2, b5, s2, s5 >= 0.  Note that the most significant decimal
4241      *    digit is floor(r) and that successive digits can be obtained by
4242      *    setting r <- 10*floor(r) (or b <= 10 * (b % S)).  Find appropriate
4243      *    b2, b5, s2, s5.
4244      */
4245
4246     ComputeScale(be, k, &b2, &b5, &s2, &s5);
4247
4248     /*
4249      * Correct an incorrect caller-supplied 'ndigits'.  Also determine:
4250      *  i = The maximum number of decimal digits that will be returned in the
4251      *      formatted string.  This is k + 1 + ndigits for F format, 18 for
4252      *      shortest and Steele, and ndigits for E format.
4253      *  ilim = The number of significant digits to convert if k has been
4254      *         guessed correctly. This is -1 for shortest and Steele (which
4255      *         stop when all significance has been lost), 'ndigits' for E
4256      *         format, and 'k + 1 + ndigits' for F format.
4257      *  ilim1 = The minimum number of significant digits to convert if k has
4258      *          been guessed 1 too high. This, too, is -1 for shortest and
4259      *          Steele, and 'ndigits' for E format, but it's 'ndigits-1' for F
4260      *          format.
4261      */
4262
4263     SetPrecisionLimits(convType, k, &ndigits, &i, &ilim, &ilim1);
4264
4265     /*
4266      * Try to do low-precision conversion in floating point rather than
4267      * resorting to expensive multiprecision arithmetic.
4268      */
4269
4270     if (ilim >= 0 && ilim <= QUICK_MAX && !(flags & TCL_DD_NO_QUICK)) {
4271         retval = QuickConversion(d.d, k, k_check, flags, i, ilim, ilim1,
4272                 decpt, endPtr);
4273         if (retval != NULL) {
4274             return retval;
4275         }
4276     }
4277
4278     /*
4279      * For shortening conversions, determine the upper and lower bounds for
4280      * the remainder at which we can stop.
4281      *   m+ = (2**m2plus * 5**m5) / (2**s2 * 5**s5) is the limit on the high
4282      *        side, and
4283      *   m- = (2**m2minus * 5**m5) / (2**s2 * 5**s5) is the limit on the low
4284      *        side.
4285      * We may need to increase s2 to put m2plus, m2minus, b2 over a common
4286      * denominator.
4287      */
4288
4289     if (flags & TCL_DD_SHORTEN_FLAG) {
4290         int m2minus = b2;
4291         int m2plus;
4292         int m5 = b5;
4293         int len = i;
4294
4295         /*
4296          * Find the quantity i so that (2**i*5**b5)/(2**s2*5**s5) is 1/2 unit
4297          * in the least significant place of the floating point number.
4298          */
4299
4300         if (denorm) {
4301             i = be + EXPONENT_BIAS + (FP_PRECISION-1);
4302         } else {
4303             i = 1 + FP_PRECISION - bbits;
4304         }
4305         b2 += i;
4306         s2 += i;
4307
4308         /*
4309          * Reduce the fractions to lowest terms, since the above calculation
4310          * may have left excess powers of 2 in numerator and denominator.
4311          */
4312
4313         CastOutPowersOf2(&b2, &m2minus, &s2);
4314
4315         /*
4316          * In the special case where bw==1, the nearest floating point number
4317          * to it on the low side is 1/4 ulp below it. Adjust accordingly.
4318          */
4319
4320         m2plus = m2minus;
4321         if (!denorm && bw == 1) {
4322             ++b2;
4323             ++s2;
4324             ++m2plus;
4325         }
4326
4327         if (s5+1 < N_LOG2POW5 && s2+1 + log2pow5[s5+1] <= 64) {
4328             /*
4329              * If 10*2**s2*5**s5 == 2**(s2+1)+5**(s5+1) fits in a 64-bit word,
4330              * then all our intermediate calculations can be done using exact
4331              * 64-bit arithmetic with no need for expensive multiprecision
4332              * operations. (This will be true for all numbers in the range
4333              * [1.0e-3 .. 1.0e+24]).
4334              */
4335
4336             return ShorteningInt64Conversion(&d, convType, bw, b2, b5, m2plus,
4337                     m2minus, m5, s2, s5, k, len, ilim, ilim1, decpt, endPtr);
4338         } else if (s5 == 0) {
4339             /*
4340              * The denominator is a power of 2, so we can replace division by
4341              * digit shifts. First we round up s2 to a multiple of MP_DIGIT_BIT,
4342              * and adjust m2 and b2 accordingly. Then we launch into a version
4343              * of the comparison that's specialized for the 'power of mp_digit
4344              * in the denominator' case.
4345              */
4346
4347             if (s2 % MP_DIGIT_BIT != 0) {
4348                 int delta = MP_DIGIT_BIT - (s2 % MP_DIGIT_BIT);
4349
4350                 b2 += delta;
4351                 m2plus += delta;
4352                 m2minus += delta;
4353                 s2 += delta;
4354             }
4355             return ShorteningBignumConversionPowD(&d, convType, bw, b2, b5,
4356                     m2plus, m2minus, m5, s2/MP_DIGIT_BIT, k, len, ilim, ilim1,
4357                     decpt, endPtr);
4358         } else {
4359             /*
4360              * Alas, there's no helpful special case; use full-up bignum
4361              * arithmetic for the conversion.
4362              */
4363
4364             return ShorteningBignumConversion(&d, convType, bw, b2, m2plus,
4365                     m2minus, s2, s5, k, len, ilim, ilim1, decpt, endPtr);
4366         }
4367     } else {
4368         /*
4369          * Non-shortening conversion.
4370          */
4371
4372         int len = i;
4373
4374         /*
4375          * Reduce numerator and denominator to lowest terms.
4376          */
4377
4378         if (b2 >= s2 && s2 > 0) {
4379             b2 -= s2; s2 = 0;
4380         } else if (s2 >= b2 && b2 > 0) {
4381             s2 -= b2; b2 = 0;
4382         }
4383
4384         if (s5+1 < N_LOG2POW5 && s2+1 + log2pow5[s5+1] <= 64) {
4385             /*
4386              * If 10*2**s2*5**s5 == 2**(s2+1)+5**(s5+1) fits in a 64-bit word,
4387              * then all our intermediate calculations can be done using exact
4388              * 64-bit arithmetic with no need for expensive multiprecision
4389              * operations.
4390              */
4391
4392             return StrictInt64Conversion(&d, convType, bw, b2, b5, s2, s5, k,
4393                     len, ilim, ilim1, decpt, endPtr);
4394         } else if (s5 == 0) {
4395             /*
4396              * The denominator is a power of 2, so we can replace division by
4397              * digit shifts. First we round up s2 to a multiple of MP_DIGIT_BIT,
4398              * and adjust m2 and b2 accordingly. Then we launch into a version
4399              * of the comparison that's specialized for the 'power of mp_digit
4400              * in the denominator' case.
4401              */
4402
4403             if (s2 % MP_DIGIT_BIT != 0) {
4404                 int delta = MP_DIGIT_BIT - (s2 % MP_DIGIT_BIT);
4405
4406                 b2 += delta;
4407                 s2 += delta;
4408             }
4409             return StrictBignumConversionPowD(&d, convType, bw, b2, b5,
4410                     s2/MP_DIGIT_BIT, k, len, ilim, ilim1, decpt, endPtr);
4411         } else {
4412             /*
4413              * There are no helpful special cases, but at least we know in
4414              * advance how many digits we will convert. We can run the
4415              * conversion in steps of DIGIT_GROUP digits, so as to have many
4416              * fewer mp_int divisions.
4417              */
4418
4419             return StrictBignumConversion(&d, convType, bw, b2, s2, s5, k,
4420                     len, ilim, ilim1, decpt, endPtr);
4421         }
4422     }
4423 }
4424 \f
4425 /*
4426  *----------------------------------------------------------------------
4427  *
4428  * TclInitDoubleConversion --
4429  *
4430  *      Initializes constants that are needed for conversions to and from
4431  *      'double'
4432  *
4433  * Results:
4434  *      None.
4435  *
4436  * Side effects:
4437  *      The log base 2 of the floating point radix, the number of bits in a
4438  *      double mantissa, and a table of the powers of five and ten are
4439  *      computed and stored.
4440  *
4441  *----------------------------------------------------------------------
4442  */
4443
4444 void
4445 TclInitDoubleConversion(void)
4446 {
4447     int i;
4448     int x;
4449     Tcl_WideUInt u;
4450     double d;
4451 #ifdef IEEE_FLOATING_POINT
4452     union {
4453         double dv;
4454         Tcl_WideUInt iv;
4455     } bitwhack;
4456 #endif
4457 #if defined(__sgi) && defined(_COMPILER_VERSION)
4458     union fpc_csr mipsCR;
4459
4460     mipsCR.fc_word = get_fpc_csr();
4461     mipsCR.fc_struct.flush = 0;
4462     set_fpc_csr(mipsCR.fc_word);
4463 #endif
4464
4465     /*
4466      * Initialize table of powers of 10 expressed as wide integers.
4467      */
4468
4469     maxpow10_wide = (int)
4470             floor(sizeof(Tcl_WideUInt) * CHAR_BIT * log(2.) / log(10.));
4471     pow10_wide = (Tcl_WideUInt *)
4472             ckalloc((maxpow10_wide + 1) * sizeof(Tcl_WideUInt));
4473     u = 1;
4474     for (i = 0; i < maxpow10_wide; ++i) {
4475         pow10_wide[i] = u;
4476         u *= 10;
4477     }
4478     pow10_wide[i] = u;
4479
4480     /*
4481      * Determine how many bits of precision a double has, and how many decimal
4482      * digits that represents.
4483      */
4484
4485     if (frexp((double) FLT_RADIX, &log2FLT_RADIX) != 0.5) {
4486         Tcl_Panic("This code doesn't work on a decimal machine!");
4487     }
4488     log2FLT_RADIX--;
4489     mantBits = DBL_MANT_DIG * log2FLT_RADIX;
4490     d = 1.0;
4491
4492     /*
4493      * Initialize a table of powers of ten that can be exactly represented in
4494      * a double.
4495      */
4496
4497     x = (int) (DBL_MANT_DIG * log((double) FLT_RADIX) / log(5.0));
4498     if (x < MAXPOW) {
4499         mmaxpow = x;
4500     } else {
4501         mmaxpow = MAXPOW;
4502     }
4503     for (i=0 ; i<=mmaxpow ; ++i) {
4504         pow10vals[i] = d;
4505         d *= 10.0;
4506     }
4507
4508     /*
4509      * Initialize a table of large powers of five.
4510      */
4511
4512     for (i=0; i<9; ++i) {
4513         mp_init(pow5 + i);
4514     }
4515     mp_set(pow5, 5);
4516     for (i=0; i<8; ++i) {
4517         mp_sqr(pow5+i, pow5+i+1);
4518     }
4519     mp_init_set_int(pow5_13, 1220703125);
4520     for (i = 1; i < 5; ++i) {
4521         mp_init(pow5_13 + i);
4522         mp_sqr(pow5_13 + i - 1, pow5_13 + i);
4523     }
4524
4525     /*
4526      * Determine the number of decimal digits to the left and right of the
4527      * decimal point in the largest and smallest double, the smallest double
4528      * that differs from zero, and the number of mp_digits needed to represent
4529      * the significand of a double.
4530      */
4531
4532     maxDigits = (int) ((DBL_MAX_EXP * log((double) FLT_RADIX)
4533             + 0.5 * log(10.)) / log(10.));
4534     minDigits = (int) floor((DBL_MIN_EXP - DBL_MANT_DIG)
4535             * log((double) FLT_RADIX) / log(10.));
4536     log10_DIGIT_MAX = (int) floor(MP_DIGIT_BIT * log(2.) / log(10.));
4537
4538     /*
4539      * Nokia 770's software-emulated floating point is "middle endian": the
4540      * bytes within a 32-bit word are little-endian (like the native
4541      * integers), but the two words of a 'double' are presented most
4542      * significant word first.
4543      */
4544
4545 #ifdef IEEE_FLOATING_POINT
4546     bitwhack.dv = 1.000000238418579;
4547                                 /* 3ff0 0000 4000 0000 */
4548     if ((bitwhack.iv >> 32) == 0x3FF00000) {
4549         n770_fp = 0;
4550     } else if ((bitwhack.iv & 0xFFFFFFFF) == 0x3FF00000) {
4551         n770_fp = 1;
4552     } else {
4553         Tcl_Panic("unknown floating point word order on this machine");
4554     }
4555 #endif
4556 }
4557 \f
4558 /*
4559  *----------------------------------------------------------------------
4560  *
4561  * TclFinalizeDoubleConversion --
4562  *
4563  *      Cleans up this file on exit.
4564  *
4565  * Results:
4566  *      None
4567  *
4568  * Side effects:
4569  *      Memory allocated by TclInitDoubleConversion is freed.
4570  *
4571  *----------------------------------------------------------------------
4572  */
4573
4574 void
4575 TclFinalizeDoubleConversion(void)
4576 {
4577     int i;
4578
4579     ckfree(pow10_wide);
4580     for (i=0; i<9; ++i) {
4581         mp_clear(pow5 + i);
4582     }
4583     for (i=0; i < 5; ++i) {
4584         mp_clear(pow5_13 + i);
4585     }
4586 }
4587 \f
4588 /*
4589  *----------------------------------------------------------------------
4590  *
4591  * Tcl_InitBignumFromDouble --
4592  *
4593  *      Extracts the integer part of a double and converts it to an arbitrary
4594  *      precision integer.
4595  *
4596  * Results:
4597  *      None.
4598  *
4599  * Side effects:
4600  *      Initializes the bignum supplied, and stores the converted number in
4601  *      it.
4602  *
4603  *----------------------------------------------------------------------
4604  */
4605
4606 int
4607 Tcl_InitBignumFromDouble(
4608     Tcl_Interp *interp,         /* For error message. */
4609     double d,                   /* Number to convert. */
4610     mp_int *b)                  /* Place to store the result. */
4611 {
4612     double fract;
4613     int expt;
4614
4615     /*
4616      * Infinite values can't convert to bignum.
4617      */
4618
4619     if (TclIsInfinite(d)) {
4620         if (interp != NULL) {
4621             const char *s = "integer value too large to represent";
4622
4623             Tcl_SetObjResult(interp, Tcl_NewStringObj(s, -1));
4624             Tcl_SetErrorCode(interp, "ARITH", "IOVERFLOW", s, NULL);
4625         }
4626         return TCL_ERROR;
4627     }
4628
4629     fract = frexp(d,&expt);
4630     if (expt <= 0) {
4631         mp_init(b);
4632         mp_zero(b);
4633     } else {
4634         Tcl_WideInt w = (Tcl_WideInt) ldexp(fract, mantBits);
4635         int shift = expt - mantBits;
4636
4637         TclBNInitBignumFromWideInt(b, w);
4638         if (shift < 0) {
4639             mp_div_2d(b, -shift, b, NULL);
4640         } else if (shift > 0) {
4641             mp_mul_2d(b, shift, b);
4642         }
4643     }
4644     return TCL_OK;
4645 }
4646 \f
4647 /*
4648  *----------------------------------------------------------------------
4649  *
4650  * TclBignumToDouble --
4651  *
4652  *      Convert an arbitrary-precision integer to a native floating point
4653  *      number.
4654  *
4655  * Results:
4656  *      Returns the converted number. Sets errno to ERANGE if the number is
4657  *      too large to convert.
4658  *
4659  *----------------------------------------------------------------------
4660  */
4661
4662 double
4663 TclBignumToDouble(
4664     const mp_int *a)                    /* Integer to convert. */
4665 {
4666     mp_int b;
4667     int bits, shift, i, lsb;
4668     double r;
4669
4670
4671     /*
4672      * We need a 'mantBits'-bit significand.  Determine what shift will
4673      * give us that.
4674      */
4675
4676     bits = mp_count_bits(a);
4677     if (bits > DBL_MAX_EXP*log2FLT_RADIX) {
4678         errno = ERANGE;
4679         if (mp_isneg(a)) {
4680             return -HUGE_VAL;
4681         } else {
4682             return HUGE_VAL;
4683         }
4684     }
4685     shift = mantBits - bits;
4686
4687     /*
4688      * If shift > 0, shift the significand left by the requisite number of
4689      * bits.  If shift == 0, the significand is already exactly 'mantBits'
4690      * in length.  If shift < 0, we will need to shift the significand right
4691      * by the requisite number of bits, and round it. If the '1-shift'
4692      * least significant bits are 0, but the 'shift'th bit is nonzero,
4693      * then the significand lies exactly between two values and must be
4694      * 'rounded to even'.
4695      */
4696
4697     mp_init(&b);
4698     if (shift == 0) {
4699         mp_copy(a, &b);
4700     } else if (shift > 0) {
4701         mp_mul_2d(a, shift, &b);
4702     } else if (shift < 0) {
4703         lsb = mp_cnt_lsb(a);
4704         if (lsb == -1-shift) {
4705
4706             /*
4707              * Round to even
4708              */
4709
4710             mp_div_2d(a, -shift, &b, NULL);
4711             if (mp_isodd(&b)) {
4712                 if (mp_isneg(&b)) {
4713                     mp_sub_d(&b, 1, &b);
4714                 } else {
4715                     mp_add_d(&b, 1, &b);
4716                 }
4717             }
4718         } else {
4719
4720             /*
4721              * Ordinary rounding
4722              */
4723
4724             mp_div_2d(a, -1-shift, &b, NULL);
4725             if (mp_isneg(&b)) {
4726                 mp_sub_d(&b, 1, &b);
4727             } else {
4728                 mp_add_d(&b, 1, &b);
4729             }
4730             mp_div_2d(&b, 1, &b, NULL);
4731         }
4732     }
4733
4734     /*
4735      * Accumulate the result, one mp_digit at a time.
4736      */
4737
4738     r = 0.0;
4739     for (i=b.used-1 ; i>=0 ; --i) {
4740         r = ldexp(r, MP_DIGIT_BIT) + b.dp[i];
4741     }
4742     mp_clear(&b);
4743
4744     /*
4745      * Scale the result to the correct number of bits.
4746      */
4747
4748     r = ldexp(r, bits - mantBits);
4749
4750     /*
4751      * Return the result with the appropriate sign.
4752      */
4753
4754     if (mp_isneg(a)) {
4755         return -r;
4756     } else {
4757         return r;
4758     }
4759 }
4760 \f
4761 /*
4762  *----------------------------------------------------------------------
4763  *
4764  * TclCeil --
4765  *
4766  *      Computes the smallest floating point number that is at least the
4767  *      mp_int argument.
4768  *
4769  * Results:
4770  *      Returns the floating point number.
4771  *
4772  *----------------------------------------------------------------------
4773  */
4774
4775 double
4776 TclCeil(
4777     const mp_int *a)                    /* Integer to convert. */
4778 {
4779     double r = 0.0;
4780     mp_int b;
4781
4782     mp_init(&b);
4783     if (mp_cmp_d(a, 0) == MP_LT) {
4784         mp_neg(a, &b);
4785         r = -TclFloor(&b);
4786     } else {
4787         int bits = mp_count_bits(a);
4788
4789         if (bits > DBL_MAX_EXP*log2FLT_RADIX) {
4790             r = HUGE_VAL;
4791         } else {
4792             int i, exact = 1, shift = mantBits - bits;
4793
4794             if (shift > 0) {
4795                 mp_mul_2d(a, shift, &b);
4796             } else if (shift < 0) {
4797                 mp_int d;
4798                 mp_init(&d);
4799                 mp_div_2d(a, -shift, &b, &d);
4800                 exact = mp_iszero(&d);
4801                 mp_clear(&d);
4802             } else {
4803                 mp_copy(a, &b);
4804             }
4805             if (!exact) {
4806                 mp_add_d(&b, 1, &b);
4807             }
4808             for (i=b.used-1 ; i>=0 ; --i) {
4809                 r = ldexp(r, MP_DIGIT_BIT) + b.dp[i];
4810             }
4811             r = ldexp(r, bits - mantBits);
4812         }
4813     }
4814     mp_clear(&b);
4815     return r;
4816 }
4817 \f
4818 /*
4819  *----------------------------------------------------------------------
4820  *
4821  * TclFloor --
4822  *
4823  *      Computes the largest floating point number less than or equal to the
4824  *      mp_int argument.
4825  *
4826  * Results:
4827  *      Returns the floating point value.
4828  *
4829  *----------------------------------------------------------------------
4830  */
4831
4832 double
4833 TclFloor(
4834     const mp_int *a)                    /* Integer to convert. */
4835 {
4836     double r = 0.0;
4837     mp_int b;
4838
4839     mp_init(&b);
4840     if (mp_cmp_d(a, 0) == MP_LT) {
4841         mp_neg(a, &b);
4842         r = -TclCeil(&b);
4843     } else {
4844         int bits = mp_count_bits(a);
4845
4846         if (bits > DBL_MAX_EXP*log2FLT_RADIX) {
4847             r = DBL_MAX;
4848         } else {
4849             int i, shift = mantBits - bits;
4850
4851             if (shift > 0) {
4852                 mp_mul_2d(a, shift, &b);
4853             } else if (shift < 0) {
4854                 mp_div_2d(a, -shift, &b, NULL);
4855             } else {
4856                 mp_copy(a, &b);
4857             }
4858             for (i=b.used-1 ; i>=0 ; --i) {
4859                 r = ldexp(r, MP_DIGIT_BIT) + b.dp[i];
4860             }
4861             r = ldexp(r, bits - mantBits);
4862         }
4863     }
4864     mp_clear(&b);
4865     return r;
4866 }
4867 \f
4868 /*
4869  *----------------------------------------------------------------------
4870  *
4871  * BignumToBiasedFrExp --
4872  *
4873  *      Convert an arbitrary-precision integer to a native floating point
4874  *      number in the range [0.5,1) times a power of two. NOTE: Intentionally
4875  *      converts to a number that's a few ulp too small, so that
4876  *      RefineApproximation will not overflow near the high end of the
4877  *      machine's arithmetic range.
4878  *
4879  * Results:
4880  *      Returns the converted number.
4881  *
4882  * Side effects:
4883  *      Stores the exponent of two in 'machexp'.
4884  *
4885  *----------------------------------------------------------------------
4886  */
4887
4888 static double
4889 BignumToBiasedFrExp(
4890     const mp_int *a,            /* Integer to convert. */
4891     int *machexp)               /* Power of two. */
4892 {
4893     mp_int b;
4894     int bits;
4895     int shift;
4896     int i;
4897     double r;
4898
4899     /*
4900      * Determine how many bits we need, and extract that many from the input.
4901      * Round to nearest unit in the last place.
4902      */
4903
4904     bits = mp_count_bits(a);
4905     shift = mantBits - 2 - bits;
4906     mp_init(&b);
4907     if (shift > 0) {
4908         mp_mul_2d(a, shift, &b);
4909     } else if (shift < 0) {
4910         mp_div_2d(a, -shift, &b, NULL);
4911     } else {
4912         mp_copy(a, &b);
4913     }
4914
4915     /*
4916      * Accumulate the result, one mp_digit at a time.
4917      */
4918
4919     r = 0.0;
4920     for (i=b.used-1; i>=0; --i) {
4921         r = ldexp(r, MP_DIGIT_BIT) + b.dp[i];
4922     }
4923     mp_clear(&b);
4924
4925     /*
4926      * Return the result with the appropriate sign.
4927      */
4928
4929     *machexp = bits - mantBits + 2;
4930     return (mp_isneg(a) ? -r : r);
4931 }
4932 \f
4933 /*
4934  *----------------------------------------------------------------------
4935  *
4936  * Pow10TimesFrExp --
4937  *
4938  *      Multiply a power of ten by a number expressed as fraction and
4939  *      exponent.
4940  *
4941  * Results:
4942  *      Returns the significand of the result.
4943  *
4944  * Side effects:
4945  *      Overwrites the 'machexp' parameter with the exponent of the result.
4946  *
4947  * Assumes that 'exponent' is such that 10**exponent would be a double, even
4948  * though 'fraction*10**(machexp+exponent)' might overflow.
4949  *
4950  *----------------------------------------------------------------------
4951  */
4952
4953 static double
4954 Pow10TimesFrExp(
4955     int exponent,               /* Power of 10 to multiply by. */
4956     double fraction,            /* Significand of multiplicand. */
4957     int *machexp)               /* On input, exponent of multiplicand. On
4958                                  * output, exponent of result. */
4959 {
4960     int i, j;
4961     int expt = *machexp;
4962     double retval = fraction;
4963
4964     if (exponent > 0) {
4965         /*
4966          * Multiply by 10**exponent.
4967          */
4968
4969         retval = frexp(retval * pow10vals[exponent&0xF], &j);
4970         expt += j;
4971         for (i=4; i<9; ++i) {
4972             if (exponent & (1<<i)) {
4973                 retval = frexp(retval * pow_10_2_n[i], &j);
4974                 expt += j;
4975             }
4976         }
4977     } else if (exponent < 0) {
4978         /*
4979          * Divide by 10**-exponent.
4980          */
4981
4982         retval = frexp(retval / pow10vals[(-exponent) & 0xF], &j);
4983         expt += j;
4984         for (i=4; i<9; ++i) {
4985             if ((-exponent) & (1<<i)) {
4986                 retval = frexp(retval / pow_10_2_n[i], &j);
4987                 expt += j;
4988             }
4989         }
4990     }
4991
4992     *machexp = expt;
4993     return retval;
4994 }
4995 \f
4996 /*
4997  *----------------------------------------------------------------------
4998  *
4999  * SafeLdExp --
5000  *
5001  *      Do an 'ldexp' operation, but handle denormals gracefully.
5002  *
5003  * Results:
5004  *      Returns the appropriately scaled value.
5005  *
5006  *      On some platforms, 'ldexp' fails when presented with a number too
5007  *      small to represent as a normalized double. This routine does 'ldexp'
5008  *      in two steps for those numbers, to return correctly denormalized
5009  *      values.
5010  *
5011  *----------------------------------------------------------------------
5012  */
5013
5014 static double
5015 SafeLdExp(
5016     double fract,
5017     int expt)
5018 {
5019     int minexpt = DBL_MIN_EXP * log2FLT_RADIX;
5020     volatile double a, b, retval;
5021
5022     if (expt < minexpt) {
5023         a = ldexp(fract, expt - mantBits - minexpt);
5024         b = ldexp(1.0, mantBits + minexpt);
5025         retval = a * b;
5026     } else {
5027         retval = ldexp(fract, expt);
5028     }
5029     return retval;
5030 }
5031 \f
5032 /*
5033  *----------------------------------------------------------------------
5034  *
5035  * TclFormatNaN --
5036  *
5037  *      Makes the string representation of a "Not a Number"
5038  *
5039  * Results:
5040  *      None.
5041  *
5042  * Side effects:
5043  *      Stores the string representation in the supplied buffer, which must be
5044  *      at least TCL_DOUBLE_SPACE characters.
5045  *
5046  *----------------------------------------------------------------------
5047  */
5048
5049 void
5050 TclFormatNaN(
5051     double value,               /* The Not-a-Number to format. */
5052     char *buffer)               /* String representation. */
5053 {
5054 #ifndef IEEE_FLOATING_POINT
5055     strcpy(buffer, "NaN");
5056     return;
5057 #else
5058     union {
5059         double dv;
5060         Tcl_WideUInt iv;
5061     } bitwhack;
5062
5063     bitwhack.dv = value;
5064     if (n770_fp) {
5065         bitwhack.iv = Nokia770Twiddle(bitwhack.iv);
5066     }
5067     if (bitwhack.iv & ((Tcl_WideUInt) 1 << 63)) {
5068         bitwhack.iv &= ~ ((Tcl_WideUInt) 1 << 63);
5069         *buffer++ = '-';
5070     }
5071     *buffer++ = 'N';
5072     *buffer++ = 'a';
5073     *buffer++ = 'N';
5074     bitwhack.iv &= (((Tcl_WideUInt) 1) << 51) - 1;
5075     if (bitwhack.iv != 0) {
5076         sprintf(buffer, "(%" TCL_LL_MODIFIER "x)", bitwhack.iv);
5077     } else {
5078         *buffer = '\0';
5079     }
5080 #endif /* IEEE_FLOATING_POINT */
5081 }
5082 \f
5083 /*
5084  *----------------------------------------------------------------------
5085  *
5086  * Nokia770Twiddle --
5087  *
5088  *      Transpose the two words of a number for Nokia 770 floating point
5089  *      handling.
5090  *
5091  *----------------------------------------------------------------------
5092  */
5093 #ifdef IEEE_FLOATING_POINT
5094 static Tcl_WideUInt
5095 Nokia770Twiddle(
5096     Tcl_WideUInt w)             /* Number to transpose. */
5097 {
5098     return (((w >> 32) & 0xFFFFFFFF) | (w << 32));
5099 }
5100 #endif
5101 \f
5102 /*
5103  *----------------------------------------------------------------------
5104  *
5105  * TclNokia770Doubles --
5106  *
5107  *      Transpose the two words of a number for Nokia 770 floating point
5108  *      handling.
5109  *
5110  *----------------------------------------------------------------------
5111  */
5112
5113 int
5114 TclNokia770Doubles(void)
5115 {
5116     return n770_fp;
5117 }
5118 \f
5119 /*
5120  * Local Variables:
5121  * mode: c
5122  * c-basic-offset: 4
5123  * fill-column: 78
5124  * End:
5125  */