docs

#2.10. fmt - Formatting traits

On this page

The core::fmt module defines the family of traits that convert values to human-readable strings. Every format spec in an f-string (f"{x}", f"{x:?}", f"{n:08b}", and so on) dispatches to the traits in this chapter.

The lexical decomposition in refs-lang 1.7.4 f-string format spec and the trait dispatch in this chapter together determine the meaning of an f-string.

#2.10.1. Dispatch

An f-string hole {expr[:spec]} calls Debug::fmt if the spec's type is ?, and Display::fmt otherwise. The rest of the spec (fill / align / sign / # / 0 / width / precision and b o x X e E f) is carried by the Formatter.

  • Numbers (all integers, floating-point types, int, float) apply the spec directly to their own output (2.10.5, 2.10.6).
  • The Display::fmt of any other value sees the spec's precision, sign, #, grouping and type letter, not the width (f.width() is none): a wrapper of numbers hands them to them, so f"{z:.2}" of a Complex is 1.23+2.50i, f"{z:.1e}" is 1.2e0+2.5e0i, and f.pad(s) cuts text to the precision. A number's type letter (e, x, %, ...) is therefore accepted for such a value, statically and in a dynamic spec. The Formatter then applies fill / align / width to what the value wrote. A str and a Debug::fmt ({x:.3?}) see no spec; their text is cut by the precision.

d / s are other names for the default notation; g is the general format of numbers (1.23e+03). The meaning of each symbol and flag is defined in refs-lang 1.7.3. An f-string does not build an intermediate string per hole; it writes each hole in turn into the buffer of a single Formatter.

#2.10.2. Formatter

A formatter made by from_sink holds at most about one chunk (4 KiB) of text: once it holds that much after a write_str or pad, it passes the text to sink and starts a new chunk, and flush passes the rest. When sink returns false the write fails with FmtError, so the Display writing into it stops. io::Write::write_display (2.23.3) is built on it.

FormatSpec is a parsed spec value. A static spec is parsed at compile time; a dynamic spec (one containing {..} / ${..}) is parsed once at runtime.

nabi
struct FormatSpec {
    fill: char; align: Alignment | none; sign: Sign | none; alt: bool; zero: bool;
    width: usize | none; precision: usize | none; ty: char;
}
impl FormatSpec {
    fn new() -> FormatSpec;                   // empty spec
    fn parse(text: str) throws (ValueError) -> FormatSpec;
    fn fill(self) -> char;                    // ' ' when none is given
    fn align(self) -> Alignment | none;
    fn sign(self) -> Sign | none;
    fn alternate(self) -> bool;               // #
    fn zero_pad(self) -> bool;                // 0
    fn width(self) -> usize | none;
    fn precision(self) -> usize | none;
    fn ty(self) -> char;                      // '\0' for none or `s d`
}

parse throws a ValueError naming what is wrong. The fields are private: read a spec with the getters, which Formatter has under the same names. Formatter::with_spec caps the precision at 500: a larger one acts as 500. A new field then never breaks code that uses a spec.

#2.10.3. Display

nabi
#[lang("display_trait")]
trait Display {
    fn fmt(self, ref f: Formatter) throws (FmtError);
}

This is the default dispatch for f"{x}". The fmt of a primitive number applies the spec and writes in a single runtime call.

nabi
impl Display for str {
    fn fmt(self, ref f: Formatter) throws (FmtError) { try f.pad(self) }
}

struct Point { x: f64; y: f64; }

impl Display for Point {
    fn fmt(self, ref f: Formatter) throws (FmtError) {
        try f.write_str("(");
        try Display::fmt(self.x, ref f);
        try f.write_str(", ");
        try Display::fmt(self.y, ref f);
        try f.write_str(")");
    }
}

f"{Point { x: 1.5, y: 2.5 }}";       //→ "(1.5, 2.5)"
f"{Point { x: 1.5, y: 2.5 }:>12}";   //→ "  (1.5, 2.5)"   (f.width() inside Point::fmt is none)
  • The call site requires ref (Display::fmt(x, ref f)). The form x.fmt(f) is ambiguous for a type that implements both Display and Debug, so the call is written as a path.
  • Display is not derived. The type's designer decides its representation.

#2.10.4. Debug

nabi
#[lang("debug_trait")]
trait Debug {
    fn fmt(self, ref f: Formatter) throws (FmtError);
}

impl Debug for str { .. }    // a valid nabi string literal
impl Debug for char { .. }   // a valid nabi character literal

This is the dispatch for f"{x:?}"; it aims for a representation that can be read back. A floating-point value shows it is one: a whole number gets .0 ({1.0:?} is 1.0, {[1.0, 2.5]:?} is [1.0, 2.5]). The Debug output of str / char is a Nabi literal. Quotes, \\, \n / \r / \t, and so on are escaped; other control characters and bidi characters (U+202A..U+202E, U+2066..U+2069, etc.) are written as \u{..}.

#Display vs Debug

The two traits serve different purposes, summarized in the following table.

AspectDisplayDebug
Audienceend userdeveloper
Accuracyreadability firstno information loss (aims to round-trip)
Quotesstring as is (no quotes)string wrapped in "..." (with escapes)
Containersusually not definedautomatic for every collection
derivenot allowed (manual impl)allowed (#[derive(Debug)])
nabi
let s = "hello\nworld";
let d1 = f"{s}";        //→ hello
                        //   world          (Display: as is)
let d2 = f"{s:?}";      //→ "hello\nworld"  (Debug: escaped)

#User-defined / derive

nabi
#[derive(Debug)]
struct Point { x: f64; y: f64; }

let p = Point { x: 1.5, y: 2.5 };
let s = f"{p:?}";              //→ "Point { x: 1.5, y: 2.5 }"

Debug can be derived automatically by composing the Debug output of every field.

#Pretty printing, {:#?}

# reaches the value's Debug (f.alternate()). Derived Debug, the collections, arrays and tuples then write one entry a line, indented four spaces, each ending in ,:

nabi
f"{p:#?}";       //→ Point {
                 //       x: 1.5,
                 //       y: 2.5,
                 //   }
f"{[1, 2]:#?}";  //→ [
                 //       1,
                 //       2,
                 //   ]

An empty collection stays [] / {}.

#2.10.5. Integer spec

typeInteger
(none), d, sdecimal
ggeneral format ({1234567:g} → 1.23457e+06)
ffixed point ({5:.2f} → 5.00)
b o x Xbinary / octal / hex (0b / 0o / 0x with #)
e Eexponent notation

Giving b o x X to a floating-point value is a compile error (static spec) or a panic (dynamic spec). A negative fixed-width integer prints as the two's complement at that type's width ({-1i8:x} is "ff"). int is written as sign and magnitude (the int value -255 with {n:x} is "-ff").

nabi
let n: u32 = 0xCAFE;
f"{n:b}";        //→ "1100101011111110"
f"{n:#x}";       //→ "0xcafe"
f"{n:X}";        //→ "CAFE"
f"{42:08b}";     //→ "00101010"
f"{42:e}";       //→ "4.2e1"

#2.10.6. Floating-point output

  • {} writes the shortest digit string that reads back to the same value, and does not use exponent notation. 1.0 is 1, 0.1 is 0.1, NaN is NaN, infinity is inf / -inf.
  • {:e} writes the same digits in exponent notation (0.15 is 1.5e-1). {:E} uses E.
  • With a precision, the value is rounded to that many digits ({x:.3e}, {x:.2}).
  • {:g} is the general format (refs-lang 1.7.3): {x:.3g} of 1234.5678 is 1.23e+03, {1e20:g} is 1e+20.
  • {:?} is {} with .0 on a whole number (1.0, -0.0); without a precision only.
  • A promoted float (exponent outside f64 range) is written in exponent notation even with {} (1.5e400).
nabi
let x: f64 = 12345.678;
f"{x}";          //→ "12345.678"
f"{x:e}";        //→ "1.2345678e4"
f"{x:.3e}";      //→ "1.235e4"
f"{1.0}";        //→ "1"
f"{1.0:?}";      //→ "1.0"
f"{x:.3g}";     //→ "1.23e+04"

#2.10.7. Full f-string format spec grammar

The authority is refs-lang 1.7.3; this is a summary.

spec      = [fill][align][sign][#][0][width][grouping][.precision][type]
grouping  = "," | "_"
align     = "<" | ">" | "^" | "="
sign      = "+" | "-" | " "
type      = "" | "s" | "d" | "g" | "f" | "?" | "b" | "o" | "x" | "X" | "e" | "E" | "%"
width     = unsigned-int | hole
precision = unsigned-int | hole
hole      = "{" expr "}" | "${" expr "}"      // nested hole, no spec of its own
fill      = any single char (default: space)

Grouping. , puts a comma between groups of three digits of a decimal number's integer part, _ an underscore (four digits in b o x X): f"{1234567:,}" is 1,234,567, f"{x:_x}" groups hex digits. Grouping applies to numbers only, and , to decimal forms only; anything else is an error. Padding with 0 does not insert separators.

Percent. % writes the number times 100 in the f form (6 places unless a precision is given) and a %: f"{0.1234:.1%}" is 12.3%.

Echo. {expr=} writes the hole's source text up to and including = (spaces kept), then the value's Debug form; with a spec, {expr=:spec} writes the value with that spec instead (Python's f"{x=}"): f"{x=}" is x=5, f"{x = :.2}" is x = 5.00.

#Dynamic spec

nabi
let s1 = f"{x:.{prec}}";               //→ "3.1416"        (dynamic precision)
let s2 = f"{x:>${width}.${prec}}";     //→ "    3.1416"    (dynamic width + precision)
let s3 = f"{x:{full_spec}}";           //→ ...             (entire spec dynamic)

$$ inside a spec is a single $. A $ in the body text is literal (f"cost: $100"). A static spec is checked at compile time; if a dynamic spec expands to an invalid result, it panics at runtime. The lexer's tokenization follows "Lexical processing" in refs-lang 1.7.3.

#2.10.8. align / fill / width / precision

Formatter::pad handles the spec's align, fill and width automatically, so a user impl only produces the content.

Without an explicit align, numbers (integers, floating-point) are right-aligned and all other types are left-aligned. When < / > / ^ (and fill) are given, any type follows that alignment. ? (Debug) also accepts width / align.

nabi
let n: i32 = 42;

f"{n}";              //→ "42"            (default)
f"{n:5}";            //→ "   42"         (width 5, numbers right-aligned by default)
f"{n:<5}";           //→ "42   "         (left)
f"{n:>5}";           //→ "   42"         (right)
f"{n:^5}";           //→ " 42  "         (center)
f"{n:0>5}";          //→ "00042"         (fill 0)
f"{n:*^7}";          //→ "**42***"       (fill *, center, width 7)
f"{n:=+5}";          //→ "+  42"         (= : pad between sign and digits, + : sign on positives)
f"{n:+=5}";          //→ "+++42"         (fill '+', align '=')
f"{-42:=6}";         //→ "-   42"
f"{-42:06}";         //→ "-00042"        (0 : pad with 0, = alignment)
f"{n:+}";            //→ "+42"           (+ : sign on positives too)
f"{"ab":5}";         //→ "ab   "         (strings left-aligned by default)

precision is applied the same way.

nabi
let x: f64 = 3.141592653589793;
f"{x:.2}";           //→ "3.14"          (2 digits after the point)
f"{x:.0}";           //→ "3"
f"{x:10.4}";         //→ "    3.1416"    (width 10, precision 4, numbers right-aligned by default)
f"{x:<10.4}";        //→ "3.1416    "    (left alignment requires explicit <)

Precision on a string is interpreted as truncation to a maximum length; precision on an integer is ignored.

nabi
let s = "hello world";
f"{s:.5}";           //→ "hello"
f"{n:.3}";           //→ "42"

#2.10.9. Module mapping

The following table lists which traits each type implements.

TypeDisplayDebug
integers, int, floating-point, float✓✓
bool, char, str✓✓
List<T>, Set<T>✗✓ (T: Debug)
Dict<K, V>✗✓ (K, V: Debug)
(A, B, ..)✗✓ (all Debug)
T | none✗✓ (T: Debug)
Result<T, E>✗✓ (T, E: Debug)

Display exists only for scalars, strings and user types that implement it by hand; containers do not have it. Debug exists for almost every type and is produced by derive.

#2.10.10. #[derive(Debug)]

nabi
#[derive(Debug)]
struct User { id: u64; name: str; }

let u = User { id: 1, name: "Alice" };
let s = f"{u:?}";          //→ User { id: 1, name: "Alice" }

The derive works as follows. A struct prints as TypeName { field1: <field1:?>, field2: <field2:?>, ... }, and a tuple struct prints as TypeName(<f1:?>, <f2:?>, ...). An enum prints as VariantName or VariantName(...) / VariantName { ... }. The derive requires every field to implement Debug (recursively).

There is no #[derive(Display)]. Deciding the representation is the user's responsibility.

#2.10.11. REPL / print / automatic output

The REPL section of refs-lang 9.7 JIT cell execution flow defines the following.

nabi
>>> let x = 42;
>>> x
42

>>> 1 + 2
3

>>> "hello"
hello

>>> "hello"?
"hello"

When the REPL automatically prints the last expression, it uses Display, else Debug; a trailing ? prints the Debug form and :type prints the type. A value without either (Debug for a trailing ?) prints only its type name (refs-lang 9.7.7, 2.12.4).

A direct call of print, println, eprint or eprintln takes any number of values and the named arguments sep: and end::

nabi
println("total:", n, xs);          // total: 3 [1, 2, 3]
println(a, b, sep: ", ");
print("no newline", end: "");
println();                         // a blank line

Each value is written with Display; a value whose type has no Display but has Debug is written with Debug (so a List prints as [1, 2, 3]), as the REPL does. The values are joined by sep (default " ") and followed by end (default "\n" for println / eprintln, nothing for print / eprint); sep and end are evaluated after the values, and the whole text is written in one call, so lines from different threads never interleave. Other named arguments are an error. An f-string remains the formatter: holes take specs and never fall back to Debug (2.10.4). There is no positional format-string form such as print("{}", x).

Used as a value (xs.for_each(println)), each is the function

nabi
pub fn println<T: Display>(v: T = "");   // likewise print / eprint / eprintln

dbg. dbg(e) writes [file:line:col] <e's source text> = <e:?> and a newline to stderr and returns e's value (Rust's dbg!): let y = dbg(x * 2) + 1;. Used as a value it is fn dbg<T: Debug>(value: T) -> T, writing only the Debug form.

RichDisplay and display. A value a notebook can show as more than text implements

nabi
pub trait RichDisplay {
    /// MIME type to content: `image/svg+xml`, `text/html`, `text/markdown`,
    /// `text/latex`, `application/json` as text; `image/png` and other
    /// binary types base64-encoded; `text/plain` for other front ends.
    fn mime_bundle(self) -> Dict<str, str>;
}

pub fn display<T: RichDisplay>(x: T);

In a nabi jupyter notebook a cell whose value has RichDisplay shows its bundle as display_data, and display(x) shows one mid-cell (refs-lang 9.8.2). Elsewhere (a program, the terminal REPL) display(x) writes the bundle's text/plain and a newline to stdout, and nothing without one; the terminal REPL shows a cell's value as above. A plotting library's figure gives image/svg+xml, a table text/html.

to_str. Every Display type has x.to_str() -> str, its Display text (Python's str(x)), through the blanket impl<T: Display> ToStr for T of core::fmt. A type's own to_str wins.

#2.10.12. FmtError

nabi
struct FmtError;
impl FmtError {
    fn message(self) -> str;     // "an error occurred when formatting"
}
// + Display, Debug, Error, PartialEq, Eq, Clone

The error for a failed write to a stream. It does not occur when writing to memory (f-strings, Formatter::new, etc.); a from_sink formatter raises it when its sink refuses a chunk. Every fmt method is throws (FmtError), so calls are marked with try to propagate.

#2.10.13. Comparison with other languages

The following table shows where Nabi's fmt design sits relative to Rust and Python.

AspectRust Display/DebugPython __str__/__repr__Nabi
Human / debug split✓ separate traits✓ separate methods✓ separate traits
Debug derive#[derive(Debug)]automatic default#[derive(Debug)]
Display derivenot allowednot allowed (manual)not allowed
Radix / exponent6 traitsformat specFormatter carrying the spec
Dynamic specpositional args ({0:.*})f-string {:.{prec}}${...} expression ($-sigil)
Spec syntaxPython-likePEP 3101Python-like + ${...}

Nabi's most distinctive choice is to separate dynamic spec insertion visually with ${...}, avoiding the nested-brace ambiguity of Python's {:.{prec}}. The notation is also isomorphic to the $ sigil of JS, Kotlin and Scala.

#2.10.14. Derive policy summary

Among the fmt traits, only Debug can be derived. Display is not a derive target: the user-facing surface is decided differently in each domain, so automatic derivation does not fit, and there is no meaningful default form for Display. The type's author writes the text, either as an impl Display or, for text an f-string can say, with #[display("..")].

##[display("..")]

On a struct, #[display("text")] implements Display by writing f"text" with self in scope: #[display("line {self.line}: {self.reason}")]. Its fields are read through self; a bare field name ({line}) is an error whose help writes {self.line}. On an enum it applies to every variant; otherwise each variant carries its own, which also sees the variant's named fields by name and its tuple fields as _0, _1, ...; with one on any variant, every variant needs one. A generic type's parameters get a Display bound in the impl. The argument is a string literal; holes and specs are an f-string's.

nabi
#[derive(Debug, Error)]
#[display("no key {self.key}")]
struct NotFound { key: str; }

#[derive(Debug, Error)]
enum ParseError {
    #[display("line {line}: {reason}")]
    Bad { line: i32; reason: str; },
    #[display("empty input")]
    Empty,
}

#2.10.15. Arguments: an f-string formatted later

nabi
struct Arguments { .. }                       // Display + Debug
impl Formatter { fn write_fmt(ref self, args: Arguments) throws (FmtError); }
trait io::Write { fn write_fmt(ref self, args: fmt::Arguments) throws (IoError); }   // 2.23.3

An f-string is a str (1.7.3), except in a slot of type fmt::Arguments: a parameter, a let with that annotation, a field. There it is an Arguments. Its holes and dynamic specs are evaluated where it stands, left to right, as for a str; its text is made only when the value is formatted, piece by piece into the formatter that formats it, and never as one str.

  • A hole with no spec, {x} or {x:?}, goes through Display::fmt / Debug::fmt straight into the formatter, with no spec of the caller's: a large value reaches a from_sink formatter (and so a writer) in chunks.
  • A hole with a spec is made into its own text first, then written; padding and precision need the whole of it.
  • The checks are a str f-string's: a hole whose type has no Display (Debug for :?) is an error at the hole.
nabi
fn log(args: fmt::Arguments) { eprintln(f"[log] {args}"); }

impl Display for Point {
    fn fmt(self, ref f: Formatter) throws (FmtError) { try f.write_fmt(f"({self.x}, {self.y})"); }
}

try out.write_fmt(f"{name}: {table}\n");    // table streams through its Display
log(f"{n} rows");                           // n is read here; the text is made in log

Arguments implements Display (its text) and Debug (its text quoted, as a str). A generic slot (fn f<T: Display>(x: T)) is not an Arguments slot: f(f"..") passes a str.

Found a mistake? Edit this page on GitHub. Last updated