// Mirrors Hare's strconv:: surface. The *tos functions return a // `const str` view into a module-level buffer that is overwritten on // the next call to the same function; callers must copy the bytes if // they need to outlive the next invocation. See [[strings.dup]] to // duplicate. Matches Hare's strconv::*tos semantics. package strconv; import ascii; import bytes; import os; import strings; // invalid — input wasn't a valid number in the requested format. // Payload is the byte index of the first offending position. // Mirrors Hare's strconv::invalid = !size. export type invalid = !i32; // overflow — input was valid but doesn't fit the target type. // Mirrors Hare's strconv::overflow = !void. export type overflow = !void; // error — any error from a strconv call. Mirrors Hare's strconv::error. export type error = !(invalid | overflow); // base — numeric base for parsing/formatting. Mirrors Hare's // `strconv::base` (Hare uses `enum uint`; we pick `enum i32` since // the underlying parse/format loops index with i32). // // HEX is an alias for HEX_UPPER; HEX_LOWER is a pseudo-base that // produces lowercase a-f digits. export type base = enum i32 { DEFAULT = 0, BIN = 2, OCT = 8, DEC = 10, HEX_UPPER = 16, HEX = 16, HEX_LOWER = 17, }; fn basenum(b: base) i64 = { if (b == base.BIN) { return 2; }; if (b == base.OCT) { return 8; }; if (b == base.HEX) { return 16; }; if (b == base.HEX_UPPER) { return 16; }; if (b == base.HEX_LOWER) { return 16; }; return 10; // DEC and DEFAULT }; // lut_upper / lut_lower — digit→glyph tables. Verbatim port of the // `static const lut_upper`/`lut_lower` rune arrays in // ref/hare/strconv/utos.ha:14-20. Module-level `let` (ww has no module // `const`; never written) following the ftos_data.ww table convention. // Declared [16]rune (faithful to Hare's inferred rune element type); // u64tos casts the indexed glyph to u8 at the store, as Hare does // (utos.ha:35). let lut_upper: [16]rune = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', ]; let lut_lower: [16]rune = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', ]; // u64tos_buf — overwritten on each u64tos call (Hare's `static let buf`, // utos.ha:12). 64 = the widest u64 rendering (binary). `[0...]` kept for // fidelity; the initial value is irrelevant (only the freshly-written // prefix is ever read) but the fill form is exercised (probed: emits // byte-identically cross-stage). let u64tos_buf: [64]u8 = [0...]; // u64tos — convert u to a base-b numeric string. Returns a view into // `u64tos_buf`, overwritten on the next call; copy via strings.dup to // outlive it. Verbatim port of ref/hare/strconv/utos.ha:10-42. // Divergences: // - Hare's `static assert(types::U64_MAX == ...)` dropped (ww has no // static assert; the bound lives in lib/types/types.ww:20). // - Hare selects the LUT via an if-EXPRESSION and reassigns `b` to // HEX_UPPER / DEC inline (utos.ha:21-26). ww has no if-expression // (standing divergence, stof.ww:31), so the glyph case is a `lower` // bool branch and the divisor is basenum(b) — the file's existing // normalize helper, which maps DEFAULT→10 and HEX_LOWER→16 exactly // as Hare's reassignment does. // - Hare's `types::string { data = &buf, ... }` + `*(&s: *str)` // reinterpret (utos.ha:28,41) → strings.frombytes (CLAUDE.md rule 9 // carve-out: ww's lib/types has no `string` struct; frombytes is the // honest ww idiom, cf. ascii/strings). export fn u64tos(u: u64, b: base) str = { let nb: u64 = basenum(b): u64; let lower: bool = (b == base.HEX_LOWER); let length: i32 = 0; let n: u64 = u; if (n == 0u64) { u64tos_buf[length] = lut_upper[0]: u8; length += 1; }; for (n > 0u64) { let d: i64 = (n % nb): i64; if (lower) { u64tos_buf[length] = lut_lower[d]: u8; } else { u64tos_buf[length] = lut_upper[d]: u8; }; length += 1; n = n / nb; }; bytes.reverse(u64tos_buf[0:length]); return strings.frombytes(u64tos_buf[0:length]); }; // i64tos_buf — independent from u64tos_buf so i64tos's own u64tos call // (the magnitude) doesn't clobber the in-flight result. 65 = 64 digits // plus the leading '-'. Hare's `static let buf: [65]u8` (itos.ha:18). let i64tos_buf: [65]u8 = [0...]; // i64tos — convert i to a base-b numeric string. Returns a view into // `i64tos_buf`. Verbatim port of ref/hare/strconv/itos.ha:10-32. // Divergences: // - `static assert` dropped (see u64tos); the DEFAULT→DEC normalize // rides basenum(b) inside the u64tos call (itos.ha:12-14). // - Hare's slice-assign `buf[1..len(u)+1] = u[..]` + the bounds assert // (itos.ha:26-28) → explicit copy loop (existing-file convention; // the [65] buffer holds the 64-digit max + sign exactly, so the // bound is structural). // - `*(&s: *str)` → strings.frombytes (see u64tos). export fn i64tos(i: i64, b: base) str = { if (i >= 0) { return u64tos(i: u64, b); }; i64tos_buf[0] = '-'; // `(-i): u64`: for I64_MIN, -i wraps (two's complement) back to the // I64_MIN bit pattern; reinterpreting to u64 yields the true // magnitude 9223372036854775808. ref/hare/strconv/itos.ha:25. Probed // on both stages (NEG then i64→u64 reinterpret byte-identical); // closes the i64tos-on-I64_MIN bug noted at cgen.ww #144. let u: str = u64tos((-i): u64, b); let k: i32 = 0; for (k < u.len) { i64tos_buf[k + 1] = u[k]; k += 1; }; return strings.frombytes(i64tos_buf[0 : u.len + 1]); }; export fn i32tos(v: i32, b: base) str = { return i64tos(v: i64, b); }; export fn i16tos(v: i16, b: base) str = { return i64tos(v: i64, b); }; export fn i8tos(v: i8, b: base) str = { return i64tos(v: i64, b); }; // itos — int (ww machine-word, 8B → i64-width) → string. // ref/hare/strconv/itos.ha:52. export fn itos(i: int, b: base) str = { return i64tos(i: i64, b); }; export fn u32tos(v: u32, b: base) str = { return u64tos(v: u64, b); }; export fn u16tos(v: u16, b: base) str = { return u64tos(v: u64, b); }; export fn u8tos(v: u8, b: base) str = { return u64tos(v: u64, b); }; // utos — uint (8B → u64-width) → string. ref/hare/strconv/utos.ha:62. export fn utos(u: uint, b: base) str = { return u64tos(u: u64, b); }; // ztos — size (8B → u64-width) → string. ref/hare/strconv/utos.ha:67. export fn ztos(u: size, b: base) str = { return u64tos(u: u64, b); }; // uptrtos — uintptr → string. ref/hare/strconv/utos.ha:72 (param `uptr` // cast `uptr: u64`). export fn uptrtos(uptr: uintptr, b: base) str = { return u64tos(uptr: u64, b); }; // rune_to_integer — digit value of r (0-9 → 0-9; a-z/A-Z → 10-35), // or void if r is not alphanumeric. Verbatim port of // ref/hare/strconv/stou.ha:8-15 (ww yields the void variant with a // bare `return;`, per lib/bytes/bytes.ww:65). fn rune_to_integer(r: rune) (u64 | void) = { if (ascii.isdigit(r)) { return (r: u32 - '0'): u64; } else if (ascii.isalpha(r) && ascii.islower(r)) { return (r: u32 - 'a'): u64 + 10; } else if (ascii.isalpha(r) && ascii.isupper(r)) { return (r: u32 - 'A'): u64 + 10; }; return; }; // parseint — shared sign+digit+overflow core for stoi64/stou64. // Verbatim port of ref/hare/strconv/stou.ha:17-65. Divergences: // - param `base` → `b` (ww: avoid the type/value name collision; the // file already names the enum arg `b`). // - Hare's DEFAULT→DEC / HEX_LOWER→HEX base reassignment + the // base-validity assert collapse into basenum(b), which already maps // every base to its numeric value {2,8,10,16} (default 10). HEX_LOWER // thus parses case-insensitively, matching Hare's normalize-then-parse. // - str is byte-indexable, so Hare's `buf = strings::toutf8(s)` is // elided (existing file convention, cf. the old stoi64/stou64). // - n *= base / n += digit spelled as plain assignment (sibling-fn // convention). fn parseint(s: str, b: base) ((bool, u64) | invalid | overflow) = { let nb: u64 = basenum(b): u64; if (s.len == 0) { return 0: invalid; }; let i: i32 = 0; let sign: bool = s[i] == '-'; if (sign || s[i] == '+') { i += 1; }; // Require at least one digit. if (i == s.len) { return i: invalid; }; let n: u64 = 0u64; // Hare's `for (i < len(buf); i += 1)` (stou.ha:43) → condition-only // for + tail increment (ww has no 2-clause for; sort.ww:25). Early // returns exit before the increment, so it's never skipped. for (i < s.len) { let digit: u64 = match (rune_to_integer(s[i]: rune)) { case void => return i: invalid; case let d: u64 => yield d; }; if (digit >= nb) { return i: invalid; }; let old: u64 = n; n = n * nb; n = n + digit; if (n < old) { return overflow{}; }; i += 1; }; return (sign, n); }; // stoi64 — parse signed base-b number. Verbatim port of // ref/hare/strconv/stoi.ha:9-17. types.I64_MAX is inlined (the const is // package-private — see the mulshift32 note in ftos.ww). export fn stoi64(s: str, b: base) (i64 | invalid | overflow) = { let (sign, u) = parseint(s, b)?; // Two's complement: I64_MIN = -I64_MAX - 1. Hare's two if-expressions // (stoi.ha:12,16) are lowered to statement-if — ww has no // if-expression (standing divergence, see the note in stof.ww:31). let max: u64 = 9223372036854775807u64; if (sign) { max = max + 1u64; }; if (u > max) { return overflow{}; }; let r: i64 = u: i64; if (sign) { r = -r; }; return r; }; // stou64 — parse unsigned base-b number. Verbatim port of // ref/hare/strconv/stou.ha:70-76. export fn stou64(s: str, b: base) (u64 | invalid | overflow) = { let (sign, u) = parseint(s, b)?; if (sign) { return overflow{}; }; return u; }; export fn stoi32(s: str, b: base) (i32 | invalid | overflow) = { let r = stoi64(s, b); match (r) { case let v: i64 => { if (v > 2147483647i64) { return overflow{}; }; if (v < -2147483648i64) { return overflow{}; }; return v: i32; }; case let e: invalid => return e; case let e: overflow => return e; }; return 0: invalid; // unreachable; appeases the path-cov checker }; export fn stoi16(s: str, b: base) (i16 | invalid | overflow) = { let r = stoi64(s, b); match (r) { case let v: i64 => { if (v > 32767i64) { return overflow{}; }; if (v < -32768i64) { return overflow{}; }; return v: i16; }; case let e: invalid => return e; case let e: overflow => return e; }; return 0: invalid; }; export fn stoi8(s: str, b: base) (i8 | invalid | overflow) = { let r = stoi64(s, b); match (r) { case let v: i64 => { if (v > 127i64) { return overflow{}; }; if (v < -128i64) { return overflow{}; }; return v: i8; }; case let e: invalid => return e; case let e: overflow => return e; }; return 0: invalid; }; // stoi — parse signed base-b number into an int. Mirrors Hare's // strconv::stoi (ref/hare/strconv/stoi.ha:53), which clamps to // types::INT_MIN/INT_MAX via stoiminmax. ww's int is a machine word // (8B → i64-width, so INT_MIN/INT_MAX == I64_MIN/I64_MAX per // lib/types/types.ww:30-31), so stoi64's result always fits and the // clamp is a no-op — omitted, not inlined (the bound consts are // package-private; see the inline note at mulshift32 in ftos.ww). export fn stoi(s: str, b: base) (int | invalid | overflow) = { let r = stoi64(s, b); match (r) { case let v: i64 => return v: int; case let e: invalid => return e; case let e: overflow => return e; }; return 0: invalid; }; export fn stou32(s: str, b: base) (u32 | invalid | overflow) = { let r = stou64(s, b); match (r) { case let v: u64 => { if (v > 4294967295u64) { return overflow{}; }; return v: u32; }; case let e: invalid => return e; case let e: overflow => return e; }; return 0: invalid; }; export fn stou16(s: str, b: base) (u16 | invalid | overflow) = { let r = stou64(s, b); match (r) { case let v: u64 => { if (v > 65535u64) { return overflow{}; }; return v: u16; }; case let e: invalid => return e; case let e: overflow => return e; }; return 0: invalid; }; export fn stou8(s: str, b: base) (u8 | invalid | overflow) = { let r = stou64(s, b); match (r) { case let v: u64 => { if (v > 255u64) { return overflow{}; }; return v: u8; }; case let e: invalid => return e; case let e: overflow => return e; }; return 0: invalid; }; // stou — parse unsigned base-b number into a uint. Mirrors Hare's // strconv::stou (ref/hare/strconv/stou.ha:107), which clamps to // types::UINT_MAX via stoumax. ww's uint is a machine word (8B → // u64-width, so UINT_MAX == U64_MAX per lib/types/types.ww:33), so // stou64's result always fits and the clamp is a no-op. export fn stou(s: str, b: base) (uint | invalid | overflow) = { let r = stou64(s, b); match (r) { case let v: u64 => return v: uint; case let e: invalid => return e; case let e: overflow => return e; }; return 0: invalid; }; // stoz — parse unsigned base-b number into a size. Mirrors Hare's // strconv::stoz (ref/hare/strconv/stou.ha:113). ww's size is u64-width // (SIZE_MAX == U64_MAX per lib/types/types.ww:37), so the clamp is a no-op. export fn stoz(s: str, b: base) (size | invalid | overflow) = { let r = stou64(s, b); match (r) { case let v: u64 => return v: size; case let e: invalid => return e; case let e: overflow => return e; }; return 0: invalid; }; // f64tos — graduated to the Ryū shortest-round-trippable implementation // in ftos.ww (strconv #106 fold-5). The old lossy fixed-point version // (6 fractional digits, "huge" fallback ≥9e18, no NaN/Inf) was deleted // here per the lib-note graduation rule ("replace in one go, don't keep // both"); ftos.ww's f64tos is the live one. f32tos follows in fold-5b // (task #67, gated on the #143 f32-arg-push cgen fix). // strerror — convert an strconv error to a user-readable string. // Returns owned str; release via os.free. Mirrors Hare's // strconv::strerror. export fn strerror(e: error) str = { match (e) { case let v: invalid => return strings.dup("input is not a valid number"); case let v: overflow => return strings.dup("input number doesn't fit target type"); }; return strings.dup(""); };