ocaml: phase 6 Printf %i/%u/%x/%X/%o + int_to_hex/octal host primitives (+5 tests, 533 total)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 41s

Three new host primitives in eval.sx:
  _int_to_hex_lower n  -> string of hex digits (lowercase)
  _int_to_hex_upper n  -> string of hex digits (uppercase)
  _int_to_octal    n   -> string of octal digits

Each builds the digit string by repeated floor(n / base) + mod,
prepending the digit at each step. Negative numbers prefix '-' so the
output round-trips through int_of_string with a sign.

Printf walker now fans out:
  %d, %i, %u  -> _string_of_int
  %f          -> _string_of_float
  %x          -> _int_to_hex_lower
  %X          -> _int_to_hex_upper
  %o          -> _int_to_octal
  %s, %c, %b  -> existing handling

  Printf.sprintf '%x' 255          = 'ff'
  Printf.sprintf '%X' 4096         = '1000'
  Printf.sprintf '%o' 8            = '10'
  Printf.sprintf '%x %X %o' 255 4096 8 = 'ff 1000 10'
This commit is contained in:
2026-05-09 03:12:28 +00:00
parent 8188a82a58
commit cb14a07413
4 changed files with 90 additions and 3 deletions

View File

@@ -70,6 +70,61 @@
(list "_int_of_string" (fn (s) (parse-number s)))
(list "_string_of_int" (fn (i) (str i)))
(list "_string_of_float" (fn (f) (str f)))
;; Integer formatting helpers used by Printf %x/%X/%o.
(list "_int_to_hex_lower"
(fn (n)
(cond
((= n 0) "0")
(else
(let ((digits "0123456789abcdef")
(m (if (< n 0) (- 0 n) n))
(out ""))
(begin
(define loop
(fn ()
(when (> m 0)
(begin
(set! out (str (nth digits (mod m 16)) out))
(set! m (floor (/ m 16)))
(loop)))))
(loop)
(if (< n 0) (str "-" out) out)))))))
(list "_int_to_hex_upper"
(fn (n)
(cond
((= n 0) "0")
(else
(let ((digits "0123456789ABCDEF")
(m (if (< n 0) (- 0 n) n))
(out ""))
(begin
(define loop
(fn ()
(when (> m 0)
(begin
(set! out (str (nth digits (mod m 16)) out))
(set! m (floor (/ m 16)))
(loop)))))
(loop)
(if (< n 0) (str "-" out) out)))))))
(list "_int_to_octal"
(fn (n)
(cond
((= n 0) "0")
(else
(let ((digits "01234567")
(m (if (< n 0) (- 0 n) n))
(out ""))
(begin
(define loop
(fn ()
(when (> m 0)
(begin
(set! out (str (nth digits (mod m 8)) out))
(set! m (floor (/ m 8)))
(loop)))))
(loop)
(if (< n 0) (str "-" out) out)))))))
(list "_char_code" (fn (c) (char-code c)))
(list "_char_chr" (fn (n) (char-from-code n)))
;; Print: route to host SX `display` (no automatic newline).