Skip to main content

flow_value/
render.rs

1//! The text form of a data value: what `${...}` inserts.
2//!
3//! `types.md` owns the form of records, enums, tuples and `Unit`, and
4//! `data.md` the form of each built-in type. In short:
5//!
6//! | Value | Text |
7//! | --- | --- |
8//! | `Int`, `Decimal` | plain decimal digits: `-42`, `1.5`, `2` |
9//! | `Bool` | `true`, `false` |
10//! | `Text` | itself when interpolated; a one-line text literal inside another value: `"a\"b"` |
11//! | `Bytes` | standard base64 with padding |
12//! | `Duration`, `Instant` | ISO 8601: `PT0.25S`, `2026-03-21T09:30:00Z` |
13//! | `List`, `Set` | `[a, b]`, `[]` |
14//! | `Dict` | `[k: v, k2: v2]`, `[:]` |
15//! | `Unit`, tuple | `()`, `(a, b)` |
16//! | record | `Name { field: v, other: w }`, `Name {}` |
17//! | enum | `Name`, `Name(a, b)`, `Name { field: v }` |
18//!
19//! Records and enums print their type's declared name without a module or
20//! type arguments, every field in declaration order — private ones too, since
21//! visibility is not confidentiality — and nothing else.
22
23use std::fmt::Write as _;
24
25use crate::error::DataError;
26use crate::shape::Payload;
27use crate::text::Text;
28use crate::value::Value;
29
30/// Returns what interpolating `value` inserts: a `Text` value's own code
31/// points, and any other data value's text form.
32pub fn interpolate(value: &Value) -> Result<Text, DataError> {
33    match value {
34        Value::Text(text) => Ok(text.clone()),
35        other => text_form(other).map(Text::from),
36    }
37}
38
39/// Returns `value`'s text form, with a `Text` written as a literal.
40///
41/// Reaching a value that is not data is [`DataError::NotData`].
42pub fn text_form(value: &Value) -> Result<String, DataError> {
43    Ok(text_form_within(value, usize::MAX)?.expect("no text is longer than usize::MAX bytes"))
44}
45
46/// Returns `value`'s text form when its UTF-8 takes at most `max_bytes`
47/// bytes, and `None` otherwise.
48///
49/// Writing stops soon after the text passes `max_bytes`, so a value whose
50/// text would be far longer costs no more than the bound and the one part
51/// that crossed it. The walk keeps what is still to write on a stack on the
52/// heap, so a value nested deeper than the native stack is written too.
53pub fn text_form_within(value: &Value, max_bytes: usize) -> Result<Option<String>, DataError> {
54    let mut out = String::new();
55    let mut pending = vec![Piece::Value(value)];
56    while let Some(piece) = pending.pop() {
57        match piece {
58            Piece::Str(text) => out.push_str(text),
59            // A number's text can be far longer than the number: one with a
60            // vast exponent is measured, and refused before it is written.
61            Piece::Value(Value::Decimal(number))
62                if number.text_len() > (max_bytes - out.len()) as u128 =>
63            {
64                return Ok(None);
65            }
66            Piece::Value(value) => write_value(&mut out, value, &mut pending)?,
67        }
68        if out.len() > max_bytes {
69            return Ok(None);
70        }
71    }
72    Ok(Some(out))
73}
74
75/// What is still to write: fixed text, or a value's text form.
76enum Piece<'a> {
77    Str(&'a str),
78    Value(&'a Value),
79}
80
81/// Writes a scalar `value`, or pushes an aggregate's pieces onto `pending`,
82/// last first, so that they pop in order.
83fn write_value<'a>(
84    out: &mut String,
85    value: &'a Value,
86    pending: &mut Vec<Piece<'a>>,
87) -> Result<(), DataError> {
88    let mut pieces: Vec<Piece<'a>> = Vec::new();
89    match value {
90        Value::Unit => out.push_str("()"),
91        Value::Bool(flag) => out.push_str(if *flag { "true" } else { "false" }),
92        Value::Int(number) => write!(out, "{number}").expect("writing to a String"),
93        Value::Decimal(number) => write!(out, "{number}").expect("writing to a String"),
94        Value::Text(text) => write_literal(out, text.as_str()),
95        Value::Bytes(bytes) => out.push_str(&bytes.to_base64()),
96        Value::Duration(span) => write!(out, "{span}").expect("writing to a String"),
97        Value::Instant(at) => write!(out, "{at}").expect("writing to a String"),
98        Value::List(items) => all(&mut pieces, "[", items.iter(), "]"),
99        Value::Set(items) => all(&mut pieces, "[", items.iter(), "]"),
100        Value::Tuple(tuple) => all(&mut pieces, "(", tuple.parts().iter(), ")"),
101        Value::Dict(entries) if entries.is_empty() => out.push_str("[:]"),
102        Value::Dict(entries) => {
103            pieces.push(Piece::Str("["));
104            for (at, (key, item)) in entries.iter().enumerate() {
105                if at > 0 {
106                    pieces.push(Piece::Str(", "));
107                }
108                pieces.extend([Piece::Value(key), Piece::Str(": "), Piece::Value(item)]);
109            }
110            pieces.push(Piece::Str("]"));
111        }
112        Value::Record(record) => {
113            pieces.push(Piece::Str(record.shape().name()));
114            named(&mut pieces, record.shape().fields(), record.fields());
115        }
116        Value::Variant(variant) => {
117            let constructor = variant.constructor();
118            pieces.push(Piece::Str(constructor.name()));
119            match constructor.payload() {
120                Payload::None => {}
121                Payload::Positional(_) => all(&mut pieces, "(", variant.payload().iter(), ")"),
122                Payload::Named(fields) => {
123                    named(
124                        &mut pieces,
125                        fields.iter().map(|field| &**field),
126                        variant.payload(),
127                    );
128                }
129            }
130        }
131        Value::Native(_) | Value::Task(_) | Value::Host(_) => return Err(DataError::NotData),
132    }
133    pending.extend(pieces.into_iter().rev());
134    Ok(())
135}
136
137/// `open`, the items separated by `, `, and `close`.
138fn all<'a>(
139    pieces: &mut Vec<Piece<'a>>,
140    open: &'a str,
141    items: impl Iterator<Item = &'a Value>,
142    close: &'a str,
143) {
144    pieces.push(Piece::Str(open));
145    for (at, item) in items.enumerate() {
146        if at > 0 {
147            pieces.push(Piece::Str(", "));
148        }
149        pieces.push(Piece::Value(item));
150    }
151    pieces.push(Piece::Str(close));
152}
153
154/// ` { name: value, ... }`, or ` {}` for no fields.
155fn named<'a>(
156    pieces: &mut Vec<Piece<'a>>,
157    names: impl Iterator<Item = &'a str>,
158    values: &'a [Value],
159) {
160    if values.is_empty() {
161        pieces.push(Piece::Str(" {}"));
162        return;
163    }
164    pieces.push(Piece::Str(" { "));
165    for (at, (name, item)) in names.zip(values).enumerate() {
166        if at > 0 {
167            pieces.push(Piece::Str(", "));
168        }
169        pieces.extend([Piece::Str(name), Piece::Str(": "), Piece::Value(item)]);
170    }
171    pieces.push(Piece::Str(" }"));
172}
173
174/// Writes `text` as the one-line text literal that denotes it.
175///
176/// `\`, `"`, line feed and tab use their own escapes, `${` is written `\${`
177/// so that it starts no interpolation, every other code point below U+0020
178/// and U+007F use `\u{...}` in uppercase hexadecimal, and every other code
179/// point is written as itself.
180fn write_literal(out: &mut String, text: &str) {
181    out.push('"');
182    let mut code_points = text.chars().peekable();
183    while let Some(code_point) = code_points.next() {
184        match code_point {
185            '\\' => out.push_str("\\\\"),
186            '"' => out.push_str("\\\""),
187            '\n' => out.push_str("\\n"),
188            '\t' => out.push_str("\\t"),
189            '$' if code_points.peek() == Some(&'{') => out.push_str("\\$"),
190            '\u{0}'..='\u{1f}' | '\u{7f}' => {
191                write!(out, "\\u{{{:X}}}", u32::from(code_point)).expect("writing to a String");
192            }
193            other => out.push(other),
194        }
195    }
196    out.push('"');
197}