ocaml: phase 6 Printf width specifiers %5d/%-5d/%05d/%4s (+5 tests, 538 total)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s

The Printf walker now parses optional flags + width digits between
'%' and the spec letter:

  -  left-align (default is right-align)
  0  zero-pad (default is space-pad; only honoured when not left-aligned)
  Nd... decimal width digits (any number)

After formatting the argument into a base string with the existing
spec dispatch (%d/%i/%u/%s/%f/%c/%b/%x/%X/%o), the result is padded
to the requested width.

Workaround: width and spec_pos are returned packed as
  width * 1000000 + spec_pos
because the parser does not yet support tuple destructuring in let
('let (a, b) = expr in body' fails with 'expected ident'). TODO: lift
that limitation; for now the encoding round-trips losslessly for any
practical width.

  Printf.sprintf '%5d'  42      = '   42'
  Printf.sprintf '%-5d|' 42     = '42   |'
  Printf.sprintf '%05d' 42      = '00042'
  Printf.sprintf '%4s' 'hi'     = '  hi'
  Printf.sprintf 'hi=%-3d, hex=%04x' 9 15 = 'hi=9  , hex=000f'
This commit is contained in:
2026-05-09 03:25:50 +00:00
parent cb14a07413
commit 7e64695a74
3 changed files with 108 additions and 25 deletions

View File

@@ -1330,6 +1330,18 @@ cat > "$TMPFILE" << 'EPOCHS'
(epoch 5074)
(eval "(ocaml-run \"Printf.sprintf \\\"%x %X %o\\\" 255 4096 8\")")
;; ── Printf width specifiers ─────────────────────────────────
(epoch 5080)
(eval "(ocaml-run \"Printf.sprintf \\\"%5d\\\" 42\")")
(epoch 5081)
(eval "(ocaml-run \"Printf.sprintf \\\"%-5d|\\\" 42\")")
(epoch 5082)
(eval "(ocaml-run \"Printf.sprintf \\\"%05d\\\" 42\")")
(epoch 5083)
(eval "(ocaml-run \"Printf.sprintf \\\"%4s\\\" \\\"hi\\\"\")")
(epoch 5084)
(eval "(ocaml-run \"Printf.sprintf \\\"hi=%-3d, hex=%04x\\\" 9 15\")")
EPOCHS
OUTPUT=$(timeout 360 "$SX_SERVER" < "$TMPFILE" 2>/dev/null)
@@ -2113,6 +2125,13 @@ check 5072 "%X 4096" '"1000"'
check 5073 "%o 8" '"10"'
check 5074 "%x %X %o multi" '"ff 1000 10"'
# ── Printf width specifiers ─────────────────────────────────────
check 5080 "%5d 42 right-pad" '" 42"'
check 5081 "%-5d| 42 left-pad" '"42 |"'
check 5082 "%05d 42 zero-pad" '"00042"'
check 5083 "%4s hi" '" hi"'
check 5084 "%-3d %04x mixed" '"hi=9 , hex=000f"'
TOTAL=$((PASS + FAIL))
if [ $FAIL -eq 0 ]; then
echo "ok $PASS/$TOTAL OCaml-on-SX tests passed"