init::format
init/src/format.mo
fmt! — efficient, Lean-style format strings, built entirely here in
Monad on top of the meta! intrinsic (init/meta.mo's value types plus
rust/core/src/eval/macro_expand.rs). No new compiler intrinsic exists
for formatting: fmt! is an ordinary defmacro whose body is one
meta! call, and everything format-specific is pure Monad code that
runs at EXPANSION time, not at run time.
Calling convention: in-string variable references only
Like Lean's s!"..."/format!, the interpolation holes name variables
that must ALREADY be in scope at the call site — fmt! takes exactly
ONE argument (the format string):
def greet (name : String) (n : I64) : String :=
fmt! "hi {name}, you are {n:>4}"
expands to roughly
String.concat_list ["hi ", FmtDisplay.fmt_display name, ", you are ",
Format.apply_align (FormatAlign.right 4)
(FmtDisplay.fmt_display n)]
— one allocation, direct FmtDisplay calls, and no runtime parsing of
the template. The expansion introduces NO binders: each hole is the
call site's own variable, and the surrounding def/fn that already
binds it is the only binder involved. That is why an out-of-scope hole
is an ordinary unbound-variable error at the call site, and why the
macro has nothing to capture with.
The pieces
FormatPiece— the parsed template: literal text, or one hole with its own spec.Format.parse— one left-to-right byte pass over the template.Format.emit— theExprthat builds the result string.fmt_meta— their composition,String -> Expr, called bymeta!.
Hygiene
Format.emit builds a CORE Expr (init/meta.mo), so each hole's
e_var names the call site's own binder directly. Since the expansion
introduces NO binders at all, a call site that already binds name
keeps ITS binding — there is no new scope to capture anything in.
Format.emit's own helper binders never reach the output.
Scope
{name}, {name:>N}, {name:^N} and {{/}} escapes. A hole must
NAME a variable: {}/{:>N} have nothing to refer to
(there is no positional argument to fall back on) and are rejected at
expansion time. Fill characters, {:x}/{:o}/{:b}/{:?} and
precision are deliberately out: each needs a per-type instance or a
second class, and none has a caller yet. An unsupported :spec is a
COMPILE error, not a silent pass-through — see Format.parse.
pub type FormatAlign {
left,
right (width : I64),
centre (width : I64)
}One hole's alignment, with the width it pads to. width counts the
display string's own BYTES (String.length is byte-oriented), so
{n:>4} on "ab" yields " ab"; a multi-byte character counts once
per byte, not once per column.
pub type FormatPiece {
literal (text : String),
hole (name : String) (align : FormatAlign),
}One piece of a parsed format template: literal text, or one interpolation hole carrying the variable's name and its alignment.
pub class FmtDisplay A {
def fmt_display (a : A) : String
}How one value is rendered by a fmt! hole.
A separate class from ToString rather than reusing it, because a
format hole is allowed to render differently from to_string (padding,
later specifiers, Debug-style quoting) and a type may reasonably want
one without the other. The blanket instance below makes every ToString
type work in a hole with no extra declaration; a type that wants its own
hole rendering declares FmtDisplay alone.
pub instance [ToString A] FmtDisplay A {
def fmt_display (a : A) : String := ToString.to_string a
}Every ToString type is displayable in a hole. This is what lets
"{}" <n>" work for I64/U64/F64/String and every existing
ToString instance without touching them.
pub instance ToString Bool {
def to_string (b : Bool) : String :=
if b then "true" else "false"
}Bool has no ToString instance (its only rendering used to be
Debug's), so the blanket instance above cannot reach it. Declared here
rather than in init/number.mo/string.mo because formatting is what
needs it: fmt! "{flag}" on a Bool must not be "no instance" error.
pub def Format.pad_left (s : String) (width : I64) : StringPad s to width characters with spaces on the left
(Format.pad_left "ab" 4 is " ab"). A string already at or beyond
width is returned unchanged — a format width is a MINIMUM, never a
truncation.
pub def Format.pad_right (s : String) (width : I64) : StringPad s to width with spaces on the right. See Format.pad_left.
pub def Format.pad_centre (s : String) (width : I64) : StringPad s to width with spaces split between both sides, the extra one
(an odd count) on the right. See Format.pad_left.
pub def Format.spaces (n : I64) : Stringn spaces; "" for n <= 0.
pub def Format.apply_align (align : FormatAlign) (s : String) : StringApply one hole's alignment to an already-rendered value.
pub def Format.emit_piece (piece : FormatPiece) : ExprThe Expr for one piece: literal text becomes e_str, a hole becomes
its display call (padded only when it has a width) — the class method
applied directly to the call site's own variable, with no intermediate
to_string call and no runtime template walking.
pub def Format.emit_pieces (pieces : List FormatPiece) : List ExprEvery piece's Expr, in template order.
pub def Format.emit_list (items : List Expr) : ExprFold a list of Exprs into one List-building Expr — the emitted
code's [...] argument to String.concat_list. Built as List.cons
cells because init/meta.mo's Expr has no list literal.
pub def Format.emit (pieces : List FormatPiece) : ExprFormat.emit — the whole template as ONE Expr
(String.concat_list <pieces>), which the macro emits once per call.
pub def Format.parse_spec (spec : String) : Result String FormatAlignOne hole's alignment from its :spec text (the part after :).
Total by construction: left (no spec at all), >N/^N with a
positive width, and everything else is an err carrying the offending
spec so the author sees it. Being total is what lets fmt_meta promise
a compile-time error instead of emitting code that fails later.
pub def Format.parse_hole (body : String) : Result String FormatPieceSplit one hole's inside text (body, the text between { and }, at
most brace bytes) into its name and alignment.
pub def Format.parse (template : String) : Result String (List FormatPiece)Format.parse -- split a template into its pieces.
{name}/{name:>N}/{name:^N} are holes — every hole
must name a variable; {{ and }} are the literal brace characters.
An unterminated hole, an unnamed hole, an unknown spec or an unclosed
escape is an err carrying the reason (the offending spec, or the byte
offset for a brace error), so the expansion fails with a message naming
the author's own text rather than emitting broken code.
pub def fmt_meta (template : String) : Exprfmt_meta — the meta function fmt! hands its template to: String -> Expr, the signature meta!'s subject/function pair requires. Both
parsing and emitting happen at EXPANSION time, so the call site pays
nothing for either: no template survives into the emitted code and no
piece count is walked at run time.
A malformed template reifies as e_error, which fails the expansion
with the message Format.parse produced — the author reads it at the
call site, and nothing is spliced in.