vile / scheme / number_io.v
425 lines · 405 sloc · 14.79 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import lexer
4import math
5import math.big
6import math.bits as bitops
7import strconv
8import strings
9
10fn number_io_call(p Primitive, args []Value, name string) !Value {
11 check_arity(name, args.len, 1, 2)!
12 mut radix := 10
13 if args.len == 2 {
14 if args[1].tag != .integer || args[1].whole() !in [i64(2), i64(8), i64(10), i64(16)] {
15 return failure('radix must be an exact integer: 2, 8, 10, or 16')
16 }
17 radix = int(args[1].whole())
18 }
19 if p == .number_to_string {
20 text := number_notation(args[0], radix)!
21 return owned_string(text, text.len)
22 }
23 if args[0].tag != .string { return failure('string->number needs a string') }
24 return read_number_text(args[0].text(), radix) or { boolean(false) }
25}
26
27fn read_number_text(text string, radix int) !Value {
28 if nonfinite_spelling(text) { return read_nonfinite(text, radix) }
29 if complex_nonfinite_spelling(text) { return read_nonfinite_complex(text, radix) }
30 // Scanner spans validate exactly one full numeric spelling without building
31 // a datum arena or collecting/copied token spellings. A supplied radix is a
32 // default; either order of an explicit radix/exactness prefix overrides it.
33 mut explicit := false
34 mut offset := 0
35 for offset + 1 < text.len && text[offset] == `#` && offset < 4 {
36 prefix := text[offset + 1] | 0x20
37 if prefix in [`b`, `o`, `d`, `x`] { explicit = true }
38 offset += 2
39 }
40 input := if radix == 10 || explicit {
41 text
42 } else {
43 match radix {
44 2 { '#b' + text }
45 8 { '#o' + text }
46 else { '#x' + text }
47 }
48 }
49 mut scanner := lexer.new_scanner(input)!
50 token := scanner.next()!
51 if token.kind != .number || token.start != 0 || token.end != input.len {
52 return failure('invalid numeric notation')
53 }
54 if scanner.next()!.kind != .eof { return failure('invalid numeric notation') }
55 return parse_number_radix(input, radix)
56}
57
58fn number_notation(value Value, radix int) !string {
59 match value.tag {
60 .exact_complex, .inexact_complex { return complex_notation(value, radix) }
61 .integer { return integer_notation(value.whole(), radix) }
62 .big_integer { return value.big_integer_pointer().value.radix_str(u32(radix)) }
63 .big_rational {
64 r := value.big_rational_pointer()
65 n := r.numerator.radix_str(u32(radix))
66 d := r.denominator.radix_str(u32(radix))
67 if n.len > max_int - d.len - 1 {
68 return failure('numeric output exceeds supported size')
69 }
70 mut out := strings.new_buffer(n.len + d.len + 1)
71 out.write_string(n)
72 out.write_u8(`/`)
73 out.write_string(d)
74 return out.take_string()
75 }
76 .rational {
77 fraction := value.rational_pointer()
78 mut numerator := [66]u8{}
79 mut denominator := [66]u8{}
80 n := integer_digits(fraction.numerator, radix, mut numerator)
81 d := integer_digits(fraction.denominator, radix, mut denominator)
82 mut out := strings.new_buffer(131 - n - d)
83 out.write_string(unsafe { tos(&numerator[n], 65 - n) })
84 out.write_u8(`/`)
85 out.write_string(unsafe { tos(&denominator[d], 65 - d) })
86 return out.take_string()
87 }
88 .real {
89 x := value.floating()
90 if math.is_nan(x) || math.is_inf(x, 0) {
91 if radix != 10 { return failure('nonfinite numbers require decimal radix') }
92 return nonfinite_notation(x).clone()
93 }
94 if radix == 10 { return real_notation(x) }
95 return binary_real_notation(x, radix)
96 }
97 else { return failure('number->string needs a number') }
98 }
99}
100
101fn integer_notation(value i64, radix int) string {
102 mut scratch := [66]u8{}
103 index := integer_digits(value, radix, mut scratch)
104 return unsafe { tos(&scratch[index], 65 - index).clone() }
105}
106
107fn integer_digits(value i64, radix int, mut scratch [66]u8) int {
108 // Leave a terminator after the at-most-65-byte signed binary spelling.
109 mut index := 65
110 mut remaining := magnitude(value)
111 if radix == 10 {
112 for {
113 index--
114 scratch[index] = `0` + u8(remaining % 10)
115 remaining /= 10
116 if remaining == 0 { break }
117 }
118 } else {
119 group := match radix {
120 2 { 1 }
121 8 { 3 }
122 else { 4 }
123 }
124 mask := u64(radix - 1)
125 for {
126 index--
127 scratch[index] = '0123456789abcdef'[remaining & mask]
128 remaining >>= group
129 if remaining == 0 { break }
130 }
131 }
132 if value < 0 {
133 index--
134 scratch[index] = `-`
135 }
136 return index
137}
138
139fn real_notation(value f64) string {
140 // f64.str uses the stdlib's shortest-roundtrip decimal conversion. Ensure
141 // a point even for integral floats and one-digit scientific mantissas.
142 text := value.str()
143 if value == 0 { return text.clone() }
144 if text.contains('.') { return text }
145 position := text.index('e') or { return text + '.0' }
146 mut out := strings.new_buffer(text.len + 2)
147 out.write_string(text_view(text, 0, position))
148 out.write_string('.0')
149 out.write_string(text_view(text, position, text.len))
150 return out.take_string()
151}
152
153fn binary_real_notation(value f64, radix int) string {
154 bits := math.f64_bits(value)
155 field := int((bits >> 52) & 0x7ff)
156 mut mantissa := bits & u64(0x000fffffffffffff)
157 mut shift := if field == 0 { -1074 } else { field - 1075 }
158 if field != 0 { mantissa |= u64(1) << 52 }
159 if mantissa != 0 {
160 trailing := bitops.trailing_zeros_64(mantissa)
161 mantissa >>= trailing
162 shift += trailing
163 } else {
164 shift = 0
165 }
166 group := match radix {
167 2 { 1 }
168 8 { 3 }
169 else { 4 }
170 }
171 width := if mantissa == 0 { 1 } else { 64 - bitops.leading_zeros_64(mantissa) }
172 numerator_digits := (width + if shift > 0 { shift } else { 0 } + group - 1) / group
173 denominator_digits := if shift < 0 { (1 - shift + group - 1) / group } else { 0 }
174 capacity := 2 + if bits >> 63 != 0 { 1 } else { 0 } + numerator_digits + if shift < 0 {
175 1 + denominator_digits
176 } else {
177 0
178 }
179 mut out := strings.new_buffer(capacity)
180 out.write_string('#i')
181 if bits >> 63 != 0 { out.write_u8(`-`) }
182 write_shifted_notation(mut out, mantissa, if shift > 0 { shift } else { 0 }, group)
183 if shift < 0 {
184 out.write_u8(`/`)
185 write_shifted_notation(mut out, 1, -shift, group)
186 }
187 return out.take_string()
188}
189
190fn write_shifted_notation(mut out strings.Buffer, mantissa u64, shift int, group int) {
191 width := if mantissa == 0 { 1 } else { 64 - bitops.leading_zeros_64(mantissa) }
192 // These are decoded float significands (at most 53 bits), so the residual
193 // shift by at most three bits fits u64. Emit whole zero groups in blocks.
194 residual := shift % group
195 significand := mantissa << residual
196 count := (width + residual + group - 1) / group
197 mask := (u64(1) << group) - 1
198 for digit := count - 1; digit >= 0; digit-- {
199 out.write_u8('0123456789abcdef'[(significand >> (digit * group)) & mask])
200 }
201 zeroes := '0000000000000000000000000000000000000000000000000000000000000000'
202 mut remaining := shift / group
203 for remaining >= zeroes.len {
204 out.write_string(zeroes)
205 remaining -= zeroes.len
206 }
207 if remaining > 0 { out.write_string(text_view(zeroes, 0, remaining)) }
208}
209
210fn number_view(text string, start int, end int) string {
211 // Parsers below are length-aware. Their result owns only numeric scalars or
212 // rational components; no view of source bytes escapes numeric conversion.
213 return unsafe { tos(text.str + start, end - start) }
214}
215
216@[inline]
217fn exact_component(text string, radix int) !i64 {
218 // parse_int clamps out-of-range input in this V checkout. Numeric reading
219 // needs an actual range error before choosing an exact or inexact fallback.
220 return strconv.common_parse_int(text, radix, 64, true, true)
221}
222
223fn parse_number_radix(spelling string, default_radix int) !Value {
224 if nonfinite_spelling(spelling) { return read_nonfinite(spelling, default_radix) }
225 base, exactness, start := numeric_prefix(spelling, default_radix)!
226 body := number_view(spelling, start, spelling.len)
227 if body.contains('@') || body.ends_with('i') || body.ends_with('I') {
228 return parse_complex_body(body, base, exactness)
229 }
230 return parse_real_body(body, base, exactness)
231}
232
233fn parse_real_body(text string, base int, requested_exactness int) !Value {
234 mut exactness := requested_exactness
235 mut body := text
236 if nonfinite_spelling(body) {
237 if exactness == 1 { return failure('nonfinite number has no exact representation') }
238 return read_nonfinite(body, base)
239 }
240 if body.contains('#') {
241 body = body.replace('#', '0')
242 if exactness == 0 { exactness = -1 }
243 }
244 negative_zero := body.len > 0 && body[0] == `-`
245 if slash := body.index('/') {
246 numerator := number_view(body, 0, slash)
247 denominator := number_view(body, slash + 1, body.len)
248 n := exact_component(numerator, base) or { return large_fraction(numerator, denominator, base, exactness != -1, negative_zero) }
249 d := exact_component(denominator, base) or { return large_fraction(numerator, denominator, base, exactness != -1, negative_zero) }
250 if exactness != -1 { return rational(n, d) }
251 if d == 0 { return failure('division by zero') }
252 return real(if n == 0 { signed_zero(negative_zero) } else { rational_real(n, d) })
253 }
254 if base == 10 && (body.contains('.') || body.contains_any('eEsSfFdDlL')) {
255 return parse_decimal_number(body, exactness == 1)
256 }
257 n := exact_component(body, base) or {
258 if exactness != -1 { return owned_big_integer(big.integer_from_radix(body, u32(base))!) }
259 return large_fraction(body, '1', base, exactness != -1, negative_zero)
260 }
261 return if exactness == -1 {
262 real(if n == 0 { signed_zero(negative_zero) } else { f64(n) })
263 } else {
264 integer(n)
265 }
266}
267
268fn signed_zero(negative bool) f64 {
269 return math.f64_from_bits(if negative { u64(1) << 63 } else { u64(0) })
270}
271
272fn parse_decimal_exponent(text string, limit int) int {
273 mut negative := false
274 mut start := 0
275 if text.len > 0 && text[0] in [`+`, `-`] {
276 negative = text[0] == `-`
277 start++
278 }
279 mut value := 0
280 for i in start .. text.len {
281 digit := int(text[i] - `0`)
282 value = if value > (limit - digit) / 10 { limit } else { value * 10 + digit }
283 }
284 return if negative { -value } else { value }
285}
286
287fn parse_decimal_number(body string, exact bool) !Value {
288 negative := body[0] == `-`
289 mut end := body.len
290 mut dot := body.len
291 mut first := -1
292 mut last := -1
293 mut significant := 0
294 mut trailing := 0
295 for i, digit in body {
296 if digit in [`+`, `-`] && i == 0 { continue }
297 if digit == `.` {
298 dot = i
299 continue
300 }
301 if (digit | 0x20) in [`e`, `s`, `f`, `d`, `l`] {
302 end = i
303 break
304 }
305 if digit != `0` {
306 if first < 0 { first = i }
307 last = i
308 trailing = 0
309 } else {
310 trailing++
311 }
312 if first >= 0 { significant++ }
313 }
314 if first < 0 { return if exact { integer(0) } else { real(signed_zero(negative)) } }
315 exponent := if end < body.len {
316 if exact {
317 int(exact_component(number_view(body, end + 1, body.len), 10) or { return failure('exact decimal exponent exceeds supported scale') })
318 } else {
319 parse_decimal_exponent(number_view(body, end + 1, body.len), if body.len > max_int - 4096 {
320 max_int
321 } else {
322 body.len + 4096
323 })
324 }
325 } else {
326 0
327 }
328 fractional := if dot < end { end - dot - 1 } else { 0 }
329 if !exact {
330 combined := checked_add(i64(significant - 1), i64(exponent)) or { exact_max }
331 order := checked_subtract(combined, i64(fractional)) or { exact_min }
332 if order > 308 { return failure('inexact numeric literal exceeds supported range') }
333 if order < -324 { return real(signed_zero(negative)) }
334 if significant <= 18 {
335 canonical := if end < body.len && (body[end] | 0x20) != `e` {
336 mut out := strings.new_buffer(body.len)
337 out.write_string(number_view(body, 0, end))
338 out.write_u8(`e`)
339 out.write_string(number_view(body, end + 1, body.len))
340 out.take_string()
341 } else {
342 body
343 }
344 return real(strconv.atof64(canonical, strconv.AtoF64Param{}) or { return failure('inexact numeric literal exceeds supported range') })
345 }
346 }
347 if last - first > max_int - 2 { return failure('numeric literal exceeds supported size') }
348 mut out := strings.new_buffer(last - first + 2)
349 if negative { out.write_u8(`-`) }
350 for i in first .. last + 1 { if body[i] != `.` { out.write_u8(body[i]) } }
351 digits := out.take_string()
352 scale := checked_subtract(i64(fractional - trailing), i64(exponent)) or { return failure('numeric literal exceeds supported conversion scale') }
353 if exact && scale >= -18 && scale <= 18 {
354 if n := exact_component(digits, 10) {
355 if scale >= 0 { return rational(n, power_ten(int(scale))!) }
356 if result := small_multiply(n, power_ten(int(-scale))!) { return integer(result) }
357 }
358 }
359 mut numerator := big.integer_from_string(digits)!
360 mut denominator := big.one_int
361 if scale < -4294967295 || scale > 4294967295 {
362 return failure('numeric literal exceeds supported conversion scale')
363 }
364 power := big.integer_from_int(10).pow(u32(if scale < 0 { -scale } else { scale }))
365 if scale > 0 { denominator = power } else { numerator = numerator * power }
366 return big_fraction_value(numerator, denominator, exact, negative)
367}
368
369fn large_fraction(numerator string, denominator string, radix int, exact bool, negative_zero bool) !Value {
370 n := big.integer_from_radix(numerator, u32(radix))!
371 d := big.integer_from_radix(denominator, u32(radix))!
372 return big_fraction_value(n, d, exact, negative_zero)
373}
374
375fn big_magnitude(value big.Integer) !u64 {
376 if value.bit_len() > 64 { return failure('integer exceeds unsigned-64-bit range') }
377 if value.signum < 0 { return big_magnitude(big_abs_view(value)) }
378 mut result := u64(0)
379 for bit in 0 .. value.bit_len() { if value.get_bit(u32(bit)) { result |= u64(1) << bit } }
380 return result
381}
382
383fn big_fraction_value(n big.Integer, d big.Integer, exact bool, negative_zero bool) !Value {
384 if d.signum == 0 { return failure('division by zero') }
385 if n.signum == 0 { return if exact { integer(0) } else { real(signed_zero(negative_zero)) } }
386 if !exact { return real(big_fraction_real(n, d)!) }
387 return normalize_big_rational(n, d, false)
388}
389
390fn big_fraction_real(n big.Integer, d big.Integer) !f64 {
391 negative := n.signum != d.signum
392 numerator := big_abs_view(n)
393 denominator := big_abs_view(d)
394 mut exponent := numerator.bit_len() - denominator.bit_len()
395 if exponent > 1024 { return failure('inexact result exceeds supported range') }
396 if exponent < -1075 { return signed_zero(negative) }
397 if exponent == 0 {
398 if numerator < denominator { exponent-- }
399 } else if exponent > 0 {
400 if numerator < denominator.left_shift(u32(exponent)) { exponent-- }
401 } else if numerator.left_shift(u32(-exponent)) < denominator {
402 exponent--
403 }
404 if exponent > 1023 { return failure('inexact result exceeds supported range') }
405 if exponent < -1075 { return signed_zero(negative) }
406 subnormal := exponent < -1022
407 shift := if subnormal { 1074 } else { 52 - exponent }
408 scaled_n := if shift > 0 { numerator.left_shift(u32(shift)) } else { numerator }
409 scaled_d := if shift < 0 { denominator.left_shift(u32(-shift)) } else { denominator }
410 quotient, remainder := scaled_n.div_mod_checked(scaled_d)!
411 mut significand := big_magnitude(quotient)!
412 comparison := remainder.abs_cmp(scaled_d - remainder)
413 if comparison > 0 || (comparison == 0 && significand & 1 != 0) { significand++ }
414 mut bits := significand
415 if !subnormal {
416 if significand == u64(1) << 53 {
417 significand >>= 1
418 exponent++
419 }
420 if exponent > 1023 { return failure('inexact result exceeds supported range') }
421 bits = (u64(exponent + 1023) << 52) | (significand & u64(0x000fffffffffffff))
422 }
423 if negative { bits |= u64(1) << 63 }
424 return math.f64_from_bits(bits)
425}
426