Debian Codegraph @

rpython/rlib/rdtoa.py

raw symbols SCIP
1 from __future__ import with_statement
2 from rpython.rlib import rfloat
3 from rpython.translator.tool.cbuild import ExternalCompilationInfo
4 from rpython.translator import cdir
5 from rpython.rtyper.lltypesystem import lltype, rffi
6 from rpython.rlib import jit, objectmodel
7 from rpython.rlib.rstring import StringBuilder
8 import py, sys
9
10 cdir = py.path.local(cdir)
11 include_dirs = [cdir]
12
13 # set the word endianness based on the host's endianness
14 # and the C double's endianness (which should be equal)
15 if hasattr(float, '__getformat__'):
16 assert float.__getformat__('double') == 'IEEE, %s-endian' % sys.byteorder
17 if sys.byteorder == 'little':
18 source_file = ['#define DOUBLE_IS_LITTLE_ENDIAN_IEEE754']
19 elif sys.byteorder == 'big':
20 source_file = ['#define WORDS_BIGENDIAN',
21 '#define DOUBLE_IS_BIG_ENDIAN_IEEE754']
22 else:
23 raise AssertionError(sys.byteorder)
24
25 source_file.append('#include "src/dtoa.c"')
26 source_file = '\n\n'.join(source_file)
27
28 # ____________________________________________________________
29
30 eci = ExternalCompilationInfo(
31 include_dirs = [cdir],
32 includes = ['src/dtoa.h'],
33 libraries = [],
34 separate_module_sources = [source_file],
35 )
36
37 # dtoa.c is limited to 'int', so we refuse to pass it
38 # strings or integer arguments bigger than ~2GB
39 _INT_LIMIT = 0x7ffff000
40
41 dg_strtod = rffi.llexternal(
42 '_PyPy_dg_strtod', [rffi.CONST_CCHARP, rffi.CCHARPP], rffi.DOUBLE,
43 compilation_info=eci, sandboxsafe=True)
44
45 dg_dtoa = rffi.llexternal(
46 '_PyPy_dg_dtoa', [rffi.DOUBLE, rffi.INT, rffi.INT,
47 rffi.INT_realP, rffi.INT_realP, rffi.CCHARPP], rffi.CCHARP,
48 compilation_info=eci, sandboxsafe=True)
49
50 dg_freedtoa = rffi.llexternal(
51 '_PyPy_dg_freedtoa', [rffi.CCHARP], lltype.Void,
52 compilation_info=eci, sandboxsafe=True)
53
54 def strtod(input):
55 if len(input) > _INT_LIMIT:
56 raise MemoryError
57 if objectmodel.revdb_flag_io_disabled():
58 return _revdb_strtod(input)
59 end_ptr = lltype.malloc(rffi.CCHARPP.TO, 1, flavor='raw')
60 try:
61 # note: don't use the class scoped_view_charp here, it
62 # break some tests because this function is used by the GC
63 ll_input, llobj, flag = rffi.get_nonmovingbuffer_ll_final_null(input)
64 try:
65 result = dg_strtod(rffi.cast(rffi.CONST_CCHARP, ll_input), end_ptr)
66
67 endpos = (rffi.cast(lltype.Signed, end_ptr[0]) -
68 rffi.cast(lltype.Signed, ll_input))
69 finally:
70 rffi.free_nonmovingbuffer_ll(ll_input, llobj, flag)
71 finally:
72 lltype.free(end_ptr, flavor='raw')
73
74 if endpos == 0 or endpos < len(input):
75 raise ValueError("invalid input at position %d" % (endpos,))
76
77 return result
78
79 lower_special_strings = ['inf', '+inf', '-inf', 'nan']
80 upper_special_strings = ['INF', '+INF', '-INF', 'NAN']
81
82 def format_nonfinite(digits, sign, flags, special_strings):
83 "Format dtoa's output for nonfinite numbers"
84 if digits[0] == 'i' or digits[0] == 'I':
85 if sign == 1:
86 return special_strings[2]
87 elif flags & rfloat.DTSF_SIGN:
88 return special_strings[1]
89 else:
90 return special_strings[0]
91 elif digits[0] == 'n' or digits[0] == 'N':
92 return special_strings[3]
93 else:
94 # shouldn't get here
95 raise ValueError
96
97 @jit.dont_look_inside
98 def format_number(digits, buflen, sign, decpt, code, precision, flags, upper):
99 # We got digits back, format them. We may need to pad 'digits'
100 # either on the left or right (or both) with extra zeros, so in
101 # general the resulting string has the form
102 #
103 # [<sign>]<zeros><digits><zeros>[<exponent>]
104 #
105 # where either of the <zeros> pieces could be empty, and there's a
106 # decimal point that could appear either in <digits> or in the
107 # leading or trailing <zeros>.
108 #
109 # Imagine an infinite 'virtual' string vdigits, consisting of the
110 # string 'digits' (starting at index 0) padded on both the left
111 # and right with infinite strings of zeros. We want to output a
112 # slice
113 #
114 # vdigits[vdigits_start : vdigits_end]
115 #
116 # of this virtual string. Thus if vdigits_start < 0 then we'll
117 # end up producing some leading zeros; if vdigits_end > digits_len
118 # there will be trailing zeros in the output. The next section of
119 # code determines whether to use an exponent or not, figures out
120 # the position 'decpt' of the decimal point, and computes
121 # 'vdigits_start' and 'vdigits_end'.
122 builder = StringBuilder(20)
123
124 use_exp = False
125 vdigits_end = buflen
126 if code == 'e':
127 use_exp = True
128 vdigits_end = precision
129 elif code == 'f':
130 vdigits_end = decpt + precision
131 elif code == 'g':
132 if decpt <= -4:
133 use_exp = True
134 elif decpt > precision:
135 use_exp = True
136 elif flags & rfloat.DTSF_ADD_DOT_0 and decpt == precision:
137 use_exp = True
138 if flags & rfloat.DTSF_ALT:
139 vdigits_end = precision
140 elif code == 'r':
141 # convert to exponential format at 1e16. We used to convert
142 # at 1e17, but that gives odd-looking results for some values
143 # when a 16-digit 'shortest' repr is padded with bogus zeros.
144 # For example, repr(2e16+8) would give 20000000000000010.0;
145 # the true value is 20000000000000008.0.
146 if decpt <= -4 or decpt > 16:
147 use_exp = True
148 else:
149 raise ValueError
150
151 # if using an exponent, reset decimal point position to 1 and
152 # adjust exponent accordingly.
153 if use_exp:
154 exp = decpt - 1
155 decpt = 1
156 else:
157 exp = 0
158
159 # ensure vdigits_start < decpt <= vdigits_end, or vdigits_start <
160 # decpt < vdigits_end if add_dot_0_if_integer and no exponent
161 if decpt <= 0:
162 vdigits_start = decpt-1
163 else:
164 vdigits_start = 0
165 if vdigits_end <= decpt:
166 if not use_exp and flags & rfloat.DTSF_ADD_DOT_0:
167 vdigits_end = decpt + 1
168 else:
169 vdigits_end = decpt
170
171 # double check inequalities
172 assert vdigits_start <= 0
173 assert 0 <= buflen <= vdigits_end
174 # decimal point should be in (vdigits_start, vdigits_end]
175 assert vdigits_start < decpt <= vdigits_end
176
177 if sign == 1:
178 builder.append('-')
179 elif flags & rfloat.DTSF_SIGN:
180 builder.append('+')
181
182 # note that exactly one of the three 'if' conditions is true, so
183 # we include exactly one decimal point
184 # 1. Zero padding on left of digit string
185 if decpt <= 0:
186 builder.append_multiple_char('0', decpt - vdigits_start)
187 builder.append('.')
188 builder.append_multiple_char('0', 0 - decpt)
189 else:
190 builder.append_multiple_char('0', 0 - vdigits_start)
191
192 # 2. Digits, with included decimal point
193 if 0 < decpt <= buflen:
194 builder.append_charpsize(digits, decpt - 0)
195 builder.append('.')
196 ptr = rffi.ptradd(digits, decpt)
197 builder.append_charpsize(ptr, buflen - decpt)
198 else:
199 builder.append_charpsize(digits, buflen)
200
201 # 3. And zeros on the right
202 if buflen < decpt:
203 builder.append_multiple_char('0', decpt - buflen)
204 builder.append('.')
205 builder.append_multiple_char('0', vdigits_end - decpt)
206 else:
207 builder.append_multiple_char('0', vdigits_end - buflen)
208
209 s = builder.build()
210
211 # Delete a trailing decimal pt unless using alternative formatting.
212 if not flags & rfloat.DTSF_ALT:
213 last = len(s) - 1
214 if last >= 0 and s[last] == '.':
215 s = s[:last]
216
217 # remove the - for negative zeros if DTSF_NO_NEG_0 is given
218 if flags & rfloat.DTSF_NO_NEG_0 and s and s[0] == '-':
219 for index in range(1, len(s)):
220 c = s[index]
221 if c != '.' and c != '0':
222 break
223 else:
224 s = s[1:]
225
226 # Now that we've done zero padding, add an exponent if needed.
227 if use_exp:
228 if upper:
229 e = 'E'
230 else:
231 e = 'e'
232
233 if exp >= 0:
234 exp_str = str(exp)
235 if len(exp_str) < 2 and not (flags & rfloat.DTSF_CUT_EXP_0):
236 s += e + '+0' + exp_str
237 else:
238 s += e + '+' + exp_str
239 else:
240 exp_str = str(-exp)
241 if len(exp_str) < 2 and not (flags & rfloat.DTSF_CUT_EXP_0):
242 s += e + '-0' + exp_str
243 else:
244 s += e + '-' + exp_str
245
246 return s
247
248 @jit.elidable
249 def dtoa(value, code='r', mode=0, precision=0, flags=0,
250 special_strings=lower_special_strings, upper=False):
251 if precision > _INT_LIMIT:
252 raise MemoryError
253 if objectmodel.revdb_flag_io_disabled():
254 return _revdb_dtoa(value)
255 decpt_ptr = lltype.malloc(rffi.INT_realP.TO, 1, flavor='raw')
256 try:
257 sign_ptr = lltype.malloc(rffi.INT_realP.TO, 1, flavor='raw')
258 try:
259 end_ptr = lltype.malloc(rffi.CCHARPP.TO, 1, flavor='raw')
260 try:
261 digits = dg_dtoa(value, mode, precision,
262 decpt_ptr, sign_ptr, end_ptr)
263 if not digits:
264 # The only failure mode is no memory
265 raise MemoryError
266 try:
267 buflen = (rffi.cast(lltype.Signed, end_ptr[0]) -
268 rffi.cast(lltype.Signed, digits))
269 sign = rffi.cast(lltype.Signed, sign_ptr[0])
270
271 # Handle nan and inf
272 if buflen and not digits[0].isdigit():
273 return format_nonfinite(digits, sign, flags,
274 special_strings)
275
276 decpt = rffi.cast(lltype.Signed, decpt_ptr[0])
277
278 return format_number(digits, buflen, sign, decpt,
279 code, precision, flags, upper)
280
281 finally:
282 dg_freedtoa(digits)
283 finally:
284 lltype.free(end_ptr, flavor='raw')
285 finally:
286 lltype.free(sign_ptr, flavor='raw')
287 finally:
288 lltype.free(decpt_ptr, flavor='raw')
289
290 def dtoa_formatd(value, code, precision, flags):
291 if code in 'EFG':
292 code = code.lower()
293 special_strings = upper_special_strings
294 upper = True
295 else:
296 special_strings = lower_special_strings
297 upper = False
298
299 if code == 'e':
300 mode = 2
301 precision += 1
302 elif code == 'f':
303 mode = 3
304 elif code == 'g':
305 mode = 2
306 # precision 0 makes no sense for 'g' format; interpret as 1
307 if precision == 0:
308 precision = 1
309 elif code == 'r':
310 # repr format
311 mode = 0
312 assert precision == 0
313 else:
314 raise ValueError('Invalid mode')
315
316 return dtoa(value, code, mode=mode, precision=precision, flags=flags,
317 special_strings=special_strings, upper=upper)
318
319 def _revdb_strtod(input):
320 # moved in its own function for the import statement
321 from rpython.rlib import revdb
322 return revdb.emulate_strtod(input)
323
324 def _revdb_dtoa(value):
325 # moved in its own function for the import statement
326 from rpython.rlib import revdb
327 return revdb.emulate_dtoa(value)