module scheme import lexer import math import math.big import math.bits as bitops import strconv import strings fn number_io_call(p Primitive, args []Value, name string) !Value { check_arity(name, args.len, 1, 2)! mut radix := 10 if args.len == 2 { if args[1].tag != .integer || args[1].whole() !in [i64(2), i64(8), i64(10), i64(16)] { return failure('radix must be an exact integer: 2, 8, 10, or 16') } radix = int(args[1].whole()) } if p == .number_to_string { text := number_notation(args[0], radix)! return owned_string(text, text.len) } if args[0].tag != .string { return failure('string->number needs a string') } return read_number_text(args[0].text(), radix) or { boolean(false) } } fn read_number_text(text string, radix int) !Value { if nonfinite_spelling(text) { return read_nonfinite(text, radix) } if complex_nonfinite_spelling(text) { return read_nonfinite_complex(text, radix) } // Scanner spans validate exactly one full numeric spelling without building // a datum arena or collecting/copied token spellings. A supplied radix is a // default; either order of an explicit radix/exactness prefix overrides it. mut explicit := false mut offset := 0 for offset + 1 < text.len && text[offset] == `#` && offset < 4 { prefix := text[offset + 1] | 0x20 if prefix in [`b`, `o`, `d`, `x`] { explicit = true } offset += 2 } input := if radix == 10 || explicit { text } else { match radix { 2 { '#b' + text } 8 { '#o' + text } else { '#x' + text } } } mut scanner := lexer.new_scanner(input)! token := scanner.next()! if token.kind != .number || token.start != 0 || token.end != input.len { return failure('invalid numeric notation') } if scanner.next()!.kind != .eof { return failure('invalid numeric notation') } return parse_number_radix(input, radix) } fn number_notation(value Value, radix int) !string { match value.tag { .exact_complex, .inexact_complex { return complex_notation(value, radix) } .integer { return integer_notation(value.whole(), radix) } .big_integer { return value.big_integer_pointer().value.radix_str(u32(radix)) } .big_rational { r := value.big_rational_pointer() n := r.numerator.radix_str(u32(radix)) d := r.denominator.radix_str(u32(radix)) if n.len > max_int - d.len - 1 { return failure('numeric output exceeds supported size') } mut out := strings.new_buffer(n.len + d.len + 1) out.write_string(n) out.write_u8(`/`) out.write_string(d) return out.take_string() } .rational { fraction := value.rational_pointer() mut numerator := [66]u8{} mut denominator := [66]u8{} n := integer_digits(fraction.numerator, radix, mut numerator) d := integer_digits(fraction.denominator, radix, mut denominator) mut out := strings.new_buffer(131 - n - d) out.write_string(unsafe { tos(&numerator[n], 65 - n) }) out.write_u8(`/`) out.write_string(unsafe { tos(&denominator[d], 65 - d) }) return out.take_string() } .real { x := value.floating() if math.is_nan(x) || math.is_inf(x, 0) { if radix != 10 { return failure('nonfinite numbers require decimal radix') } return nonfinite_notation(x).clone() } if radix == 10 { return real_notation(x) } return binary_real_notation(x, radix) } else { return failure('number->string needs a number') } } } fn integer_notation(value i64, radix int) string { mut scratch := [66]u8{} index := integer_digits(value, radix, mut scratch) return unsafe { tos(&scratch[index], 65 - index).clone() } } fn integer_digits(value i64, radix int, mut scratch [66]u8) int { // Leave a terminator after the at-most-65-byte signed binary spelling. mut index := 65 mut remaining := magnitude(value) if radix == 10 { for { index-- scratch[index] = `0` + u8(remaining % 10) remaining /= 10 if remaining == 0 { break } } } else { group := match radix { 2 { 1 } 8 { 3 } else { 4 } } mask := u64(radix - 1) for { index-- scratch[index] = '0123456789abcdef'[remaining & mask] remaining >>= group if remaining == 0 { break } } } if value < 0 { index-- scratch[index] = `-` } return index } fn real_notation(value f64) string { // f64.str uses the stdlib's shortest-roundtrip decimal conversion. Ensure // a point even for integral floats and one-digit scientific mantissas. text := value.str() if value == 0 { return text.clone() } if text.contains('.') { return text } position := text.index('e') or { return text + '.0' } mut out := strings.new_buffer(text.len + 2) out.write_string(text_view(text, 0, position)) out.write_string('.0') out.write_string(text_view(text, position, text.len)) return out.take_string() } fn binary_real_notation(value f64, radix int) string { bits := math.f64_bits(value) field := int((bits >> 52) & 0x7ff) mut mantissa := bits & u64(0x000fffffffffffff) mut shift := if field == 0 { -1074 } else { field - 1075 } if field != 0 { mantissa |= u64(1) << 52 } if mantissa != 0 { trailing := bitops.trailing_zeros_64(mantissa) mantissa >>= trailing shift += trailing } else { shift = 0 } group := match radix { 2 { 1 } 8 { 3 } else { 4 } } width := if mantissa == 0 { 1 } else { 64 - bitops.leading_zeros_64(mantissa) } numerator_digits := (width + if shift > 0 { shift } else { 0 } + group - 1) / group denominator_digits := if shift < 0 { (1 - shift + group - 1) / group } else { 0 } capacity := 2 + if bits >> 63 != 0 { 1 } else { 0 } + numerator_digits + if shift < 0 { 1 + denominator_digits } else { 0 } mut out := strings.new_buffer(capacity) out.write_string('#i') if bits >> 63 != 0 { out.write_u8(`-`) } write_shifted_notation(mut out, mantissa, if shift > 0 { shift } else { 0 }, group) if shift < 0 { out.write_u8(`/`) write_shifted_notation(mut out, 1, -shift, group) } return out.take_string() } fn write_shifted_notation(mut out strings.Buffer, mantissa u64, shift int, group int) { width := if mantissa == 0 { 1 } else { 64 - bitops.leading_zeros_64(mantissa) } // These are decoded float significands (at most 53 bits), so the residual // shift by at most three bits fits u64. Emit whole zero groups in blocks. residual := shift % group significand := mantissa << residual count := (width + residual + group - 1) / group mask := (u64(1) << group) - 1 for digit := count - 1; digit >= 0; digit-- { out.write_u8('0123456789abcdef'[(significand >> (digit * group)) & mask]) } zeroes := '0000000000000000000000000000000000000000000000000000000000000000' mut remaining := shift / group for remaining >= zeroes.len { out.write_string(zeroes) remaining -= zeroes.len } if remaining > 0 { out.write_string(text_view(zeroes, 0, remaining)) } } fn number_view(text string, start int, end int) string { // Parsers below are length-aware. Their result owns only numeric scalars or // rational components; no view of source bytes escapes numeric conversion. return unsafe { tos(text.str + start, end - start) } } @[inline] fn exact_component(text string, radix int) !i64 { // parse_int clamps out-of-range input in this V checkout. Numeric reading // needs an actual range error before choosing an exact or inexact fallback. return strconv.common_parse_int(text, radix, 64, true, true) } fn parse_number_radix(spelling string, default_radix int) !Value { if nonfinite_spelling(spelling) { return read_nonfinite(spelling, default_radix) } base, exactness, start := numeric_prefix(spelling, default_radix)! body := number_view(spelling, start, spelling.len) if body.contains('@') || body.ends_with('i') || body.ends_with('I') { return parse_complex_body(body, base, exactness) } return parse_real_body(body, base, exactness) } fn parse_real_body(text string, base int, requested_exactness int) !Value { mut exactness := requested_exactness mut body := text if nonfinite_spelling(body) { if exactness == 1 { return failure('nonfinite number has no exact representation') } return read_nonfinite(body, base) } if body.contains('#') { body = body.replace('#', '0') if exactness == 0 { exactness = -1 } } negative_zero := body.len > 0 && body[0] == `-` if slash := body.index('/') { numerator := number_view(body, 0, slash) denominator := number_view(body, slash + 1, body.len) n := exact_component(numerator, base) or { return large_fraction(numerator, denominator, base, exactness != -1, negative_zero) } d := exact_component(denominator, base) or { return large_fraction(numerator, denominator, base, exactness != -1, negative_zero) } if exactness != -1 { return rational(n, d) } if d == 0 { return failure('division by zero') } return real(if n == 0 { signed_zero(negative_zero) } else { rational_real(n, d) }) } if base == 10 && (body.contains('.') || body.contains_any('eEsSfFdDlL')) { return parse_decimal_number(body, exactness == 1) } n := exact_component(body, base) or { if exactness != -1 { return owned_big_integer(big.integer_from_radix(body, u32(base))!) } return large_fraction(body, '1', base, exactness != -1, negative_zero) } return if exactness == -1 { real(if n == 0 { signed_zero(negative_zero) } else { f64(n) }) } else { integer(n) } } fn signed_zero(negative bool) f64 { return math.f64_from_bits(if negative { u64(1) << 63 } else { u64(0) }) } fn parse_decimal_exponent(text string, limit int) int { mut negative := false mut start := 0 if text.len > 0 && text[0] in [`+`, `-`] { negative = text[0] == `-` start++ } mut value := 0 for i in start .. text.len { digit := int(text[i] - `0`) value = if value > (limit - digit) / 10 { limit } else { value * 10 + digit } } return if negative { -value } else { value } } fn parse_decimal_number(body string, exact bool) !Value { negative := body[0] == `-` mut end := body.len mut dot := body.len mut first := -1 mut last := -1 mut significant := 0 mut trailing := 0 for i, digit in body { if digit in [`+`, `-`] && i == 0 { continue } if digit == `.` { dot = i continue } if (digit | 0x20) in [`e`, `s`, `f`, `d`, `l`] { end = i break } if digit != `0` { if first < 0 { first = i } last = i trailing = 0 } else { trailing++ } if first >= 0 { significant++ } } if first < 0 { return if exact { integer(0) } else { real(signed_zero(negative)) } } exponent := if end < body.len { if exact { int(exact_component(number_view(body, end + 1, body.len), 10) or { return failure('exact decimal exponent exceeds supported scale') }) } else { parse_decimal_exponent(number_view(body, end + 1, body.len), if body.len > max_int - 4096 { max_int } else { body.len + 4096 }) } } else { 0 } fractional := if dot < end { end - dot - 1 } else { 0 } if !exact { combined := checked_add(i64(significant - 1), i64(exponent)) or { exact_max } order := checked_subtract(combined, i64(fractional)) or { exact_min } if order > 308 { return failure('inexact numeric literal exceeds supported range') } if order < -324 { return real(signed_zero(negative)) } if significant <= 18 { canonical := if end < body.len && (body[end] | 0x20) != `e` { mut out := strings.new_buffer(body.len) out.write_string(number_view(body, 0, end)) out.write_u8(`e`) out.write_string(number_view(body, end + 1, body.len)) out.take_string() } else { body } return real(strconv.atof64(canonical, strconv.AtoF64Param{}) or { return failure('inexact numeric literal exceeds supported range') }) } } if last - first > max_int - 2 { return failure('numeric literal exceeds supported size') } mut out := strings.new_buffer(last - first + 2) if negative { out.write_u8(`-`) } for i in first .. last + 1 { if body[i] != `.` { out.write_u8(body[i]) } } digits := out.take_string() scale := checked_subtract(i64(fractional - trailing), i64(exponent)) or { return failure('numeric literal exceeds supported conversion scale') } if exact && scale >= -18 && scale <= 18 { if n := exact_component(digits, 10) { if scale >= 0 { return rational(n, power_ten(int(scale))!) } if result := small_multiply(n, power_ten(int(-scale))!) { return integer(result) } } } mut numerator := big.integer_from_string(digits)! mut denominator := big.one_int if scale < -4294967295 || scale > 4294967295 { return failure('numeric literal exceeds supported conversion scale') } power := big.integer_from_int(10).pow(u32(if scale < 0 { -scale } else { scale })) if scale > 0 { denominator = power } else { numerator = numerator * power } return big_fraction_value(numerator, denominator, exact, negative) } fn large_fraction(numerator string, denominator string, radix int, exact bool, negative_zero bool) !Value { n := big.integer_from_radix(numerator, u32(radix))! d := big.integer_from_radix(denominator, u32(radix))! return big_fraction_value(n, d, exact, negative_zero) } fn big_magnitude(value big.Integer) !u64 { if value.bit_len() > 64 { return failure('integer exceeds unsigned-64-bit range') } if value.signum < 0 { return big_magnitude(big_abs_view(value)) } mut result := u64(0) for bit in 0 .. value.bit_len() { if value.get_bit(u32(bit)) { result |= u64(1) << bit } } return result } fn big_fraction_value(n big.Integer, d big.Integer, exact bool, negative_zero bool) !Value { if d.signum == 0 { return failure('division by zero') } if n.signum == 0 { return if exact { integer(0) } else { real(signed_zero(negative_zero)) } } if !exact { return real(big_fraction_real(n, d)!) } return normalize_big_rational(n, d, false) } fn big_fraction_real(n big.Integer, d big.Integer) !f64 { negative := n.signum != d.signum numerator := big_abs_view(n) denominator := big_abs_view(d) mut exponent := numerator.bit_len() - denominator.bit_len() if exponent > 1024 { return failure('inexact result exceeds supported range') } if exponent < -1075 { return signed_zero(negative) } if exponent == 0 { if numerator < denominator { exponent-- } } else if exponent > 0 { if numerator < denominator.left_shift(u32(exponent)) { exponent-- } } else if numerator.left_shift(u32(-exponent)) < denominator { exponent-- } if exponent > 1023 { return failure('inexact result exceeds supported range') } if exponent < -1075 { return signed_zero(negative) } subnormal := exponent < -1022 shift := if subnormal { 1074 } else { 52 - exponent } scaled_n := if shift > 0 { numerator.left_shift(u32(shift)) } else { numerator } scaled_d := if shift < 0 { denominator.left_shift(u32(-shift)) } else { denominator } quotient, remainder := scaled_n.div_mod_checked(scaled_d)! mut significand := big_magnitude(quotient)! comparison := remainder.abs_cmp(scaled_d - remainder) if comparison > 0 || (comparison == 0 && significand & 1 != 0) { significand++ } mut bits := significand if !subnormal { if significand == u64(1) << 53 { significand >>= 1 exponent++ } if exponent > 1023 { return failure('inexact result exceeds supported range') } bits = (u64(exponent + 1023) << 52) | (significand & u64(0x000fffffffffffff)) } if negative { bits |= u64(1) << 63 } return math.f64_from_bits(bits) }