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, quoted inside another value |
12//! | `Duration`, `Instant` | ISO 8601, quoted inside another value: `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//!
23//! The walk that writes the text form is generic over a [`Spelling`]: what
24//! it knows of each value beyond the value. The text form knows nothing
25//! more; the value notation, `flow-notation`'s, knows each value's type and
26//! adds a newtype's constructor and a whole `Decimal`'s point with the same
27//! walk.
28
29use std::fmt::Write as _;
30
31use crate::decimal::Decimal;
32use crate::error::DataError;
33use crate::text::Text;
34use crate::value::Value;
35use flow_types::Payload;
36
37/// Returns what interpolating `value` inserts: a `Text` value's own code
38/// points, a `Bytes`, `Duration` or `Instant` value's text unquoted, and any
39/// other data value's text form.
40///
41/// # Errors
42///
43/// [`DataError::NotData`] on reaching a value that is not data.
44///
45/// # Panics
46///
47/// As [`text_form`] does.
48pub fn interpolate(value: &Value) -> Result<Text, DataError> {
49    Ok(interpolate_within(value, usize::MAX)?.expect("no text is longer than usize::MAX bytes"))
50}
51
52/// Returns what interpolating `value` inserts, as [`interpolate`] does, when
53/// its UTF-8 takes at most `max_bytes` bytes, and `None` otherwise.
54///
55/// # Errors
56///
57/// [`DataError::NotData`] on reaching a value that is not data.
58pub fn interpolate_within(value: &Value, max_bytes: usize) -> Result<Option<Text>, DataError> {
59    let unquoted = |text: String| text[1..text.len() - 1].to_owned();
60    match value {
61        Value::Text(text) => Ok((text.byte_len() <= max_bytes).then(|| text.clone())),
62        Value::Bytes(_) | Value::Duration(_) | Value::Instant(_) => {
63            Ok(text_form_within(value, max_bytes.saturating_add(2))?
64                .map(|text| Text::from(unquoted(text))))
65        }
66        other => Ok(text_form_within(other, max_bytes)?.map(Text::from)),
67    }
68}
69
70/// Returns `value`'s text form, with a `Text`, `Bytes`, `Duration` or
71/// `Instant` written as a quoted literal.
72///
73/// Reaching a value that is not data is [`DataError::NotData`].
74///
75/// # Errors
76///
77/// [`DataError::NotData`] on reaching a value that is not data.
78///
79/// # Panics
80///
81/// When the text cannot be held in memory, as that of a number with an
82/// exponent near `i64::MAX` cannot: a value from outside the program is
83/// written with [`text_form_within`] instead.
84pub fn text_form(value: &Value) -> Result<String, DataError> {
85    Ok(text_form_within(value, usize::MAX)?.expect("no text is longer than usize::MAX bytes"))
86}
87
88/// Returns `value`'s text form when its UTF-8 takes at most `max_bytes`
89/// bytes, and `None` otherwise.
90///
91/// # Errors
92///
93/// [`DataError::NotData`] on reaching a value that is not data.
94pub fn text_form_within(value: &Value, max_bytes: usize) -> Result<Option<String>, DataError> {
95    spell_within(&TextForm, (), value, max_bytes)
96}
97
98/// What a walk that writes a value knows of each value beyond the value
99/// itself: nothing, for the text form, or its type, for the value notation,
100/// which writes a newtype's constructor and a whole `Decimal`'s point.
101/// Every spelling shares the walk and the spelling of every other part.
102pub trait Spelling<'a> {
103    /// What the spelling knows of the value it is at.
104    type At;
105
106    /// The newtype constructor a value at `at` is written inside, and what
107    /// is known of the base inside it; `None` for a value written bare.
108    fn newtype(&self, at: &Self::At) -> Option<(&'a str, Self::At)>;
109
110    /// What is known of `part` of a value at `at`.
111    fn part(&self, at: &Self::At, part: Part) -> Self::At;
112
113    /// Writes the `Decimal` `number`.
114    fn decimal(&self, out: &mut String, number: &Decimal);
115}
116
117/// A part of an aggregate value, as a [`Spelling`] is asked about it.
118#[derive(Clone, Copy, PartialEq, Eq, Debug)]
119pub enum Part {
120    /// An item of a list or a set.
121    Item,
122    /// A key of a dictionary.
123    Key,
124    /// A value of a dictionary.
125    Entry,
126    /// The tuple part at this position.
127    Tuple(usize),
128    /// The record field at this position, in declaration order.
129    Field(usize),
130    /// The payload part `part` of the constructor numbered `constructor`.
131    Payload {
132        /// The constructor's number, in declaration order.
133        constructor: usize,
134        /// The part's position in its payload.
135        part: usize,
136    },
137}
138
139/// The text form's spelling, which knows nothing of a value but the value.
140struct TextForm;
141
142impl<'a> Spelling<'a> for TextForm {
143    type At = ();
144
145    fn newtype(&self, (): &()) -> Option<(&'a str, ())> {
146        None
147    }
148
149    fn part(&self, (): &(), _: Part) {}
150
151    fn decimal(&self, out: &mut String, number: &Decimal) {
152        write!(out, "{number}").expect("writing to a String");
153    }
154}
155
156/// Writes `value`, known to `spelling` as `at`, when its UTF-8 takes at most
157/// `max_bytes` bytes, and returns `None` otherwise.
158///
159/// Writing stops soon after the text passes `max_bytes`, so a value whose
160/// text would be far longer costs no more than the bound and the one part
161/// that crossed it. The walk keeps what is still to write on a stack on the
162/// heap, so a value nested deeper than the native stack is written too.
163///
164/// # Errors
165///
166/// [`DataError::NotData`] on reaching a value that is not data.
167pub fn spell_within<'a, S: Spelling<'a>>(
168    spelling: &S,
169    at: S::At,
170    value: &'a Value,
171    max_bytes: usize,
172) -> Result<Option<String>, DataError> {
173    let mut out = String::new();
174    let mut pending = vec![Piece::Value(value, at)];
175    while let Some(piece) = pending.pop() {
176        match piece {
177            Piece::Str(text) => out.push_str(text),
178            // A number's text can be far longer than the number: one with a
179            // vast exponent is measured, and refused before it is written.
180            // So is a duration's or an instant's, which is a number of
181            // seconds.
182            Piece::Value(value, _) if at_least_len(value) > room(max_bytes, out.len()) => {
183                return Ok(None);
184            }
185            Piece::Value(value, at) => write_value(spelling, &mut out, value, &at, &mut pending)?,
186        }
187        if out.len() > max_bytes {
188            return Ok(None);
189        }
190    }
191    Ok(Some(out))
192}
193
194/// The bytes left before `written` passes `max_bytes`.
195fn room(max_bytes: usize, written: usize) -> u128 {
196    u128::try_from(max_bytes - written).expect("a usize fits 128 bits")
197}
198
199/// A lower bound on the bytes of `value`'s text form, without writing it,
200/// for a scalar that is written whole at once: a text or bytes, which may be
201/// long, and a number, a duration or an instant, whose text may be far longer
202/// than the value when its exponent is vast. Any other value answers 0.
203fn at_least_len(value: &Value) -> u128 {
204    let widen = |n: usize| u128::try_from(n).expect("a usize fits 128 bits");
205    match value {
206        // The quotes around the UTF-8, which escaping only lengthens.
207        Value::Text(text) => widen(text.byte_len()) + 2,
208        // The quotes around padded base64.
209        Value::Bytes(bytes) => widen(bytes.len().div_ceil(3)) * 4 + 2,
210        Value::Decimal(number) => number.text_len(),
211        // `PT`, the seconds, `S`.
212        Value::Duration(span) => span.seconds().text_len() + 3,
213        // The seconds' fraction is written in full after the second of the
214        // minute, and the year has at least as many digits as the whole
215        // seconds less the eight a year of seconds takes: so the instant's
216        // text is never shorter than the seconds' text less sixteen bytes.
217        Value::Instant(at) => at.unix_seconds().text_len().saturating_sub(16),
218        _ => 0,
219    }
220}
221
222/// What is still to write: fixed text, or a value and what the spelling
223/// knows of it.
224enum Piece<'a, A> {
225    Str(&'a str),
226    Value(&'a Value, A),
227}
228
229/// Writes a scalar `value`, or pushes an aggregate's pieces, or a newtype's
230/// constructor around its base, onto `pending`, last first, so that they pop
231/// in order.
232fn write_value<'a, S: Spelling<'a>>(
233    spelling: &S,
234    out: &mut String,
235    value: &'a Value,
236    at: &S::At,
237    pending: &mut Vec<Piece<'a, S::At>>,
238) -> Result<(), DataError> {
239    let mut pieces: Vec<Piece<'a, S::At>> = Vec::new();
240    if let Some((name, base)) = spelling.newtype(at) {
241        pieces.extend([
242            Piece::Str(name),
243            Piece::Str("("),
244            Piece::Value(value, base),
245            Piece::Str(")"),
246        ]);
247        pending.extend(pieces.into_iter().rev());
248        return Ok(());
249    }
250    let part = |part: Part| spelling.part(at, part);
251    match value {
252        Value::Unit => out.push_str("()"),
253        Value::Bool(flag) => out.push_str(if *flag { "true" } else { "false" }),
254        Value::Int(number) => write!(out, "{number}").expect("writing to a String"),
255        Value::Decimal(number) => spelling.decimal(out, number),
256        Value::Text(text) => write_literal(out, text.as_str()),
257        Value::Bytes(bytes) => {
258            write!(out, "\"{}\"", bytes.to_base64()).expect("writing to a String");
259        }
260        Value::Duration(span) => write!(out, "\"{span}\"").expect("writing to a String"),
261        Value::Instant(at) => write!(out, "\"{at}\"").expect("writing to a String"),
262        Value::List(items) => all(
263            &mut pieces,
264            "[",
265            items.iter().map(|item| (item, part(Part::Item))),
266            "]",
267        ),
268        Value::Set(items) => all(
269            &mut pieces,
270            "[",
271            items.iter().map(|item| (item, part(Part::Item))),
272            "]",
273        ),
274        Value::Tuple(tuple) => all(
275            &mut pieces,
276            "(",
277            tuple
278                .parts()
279                .iter()
280                .enumerate()
281                .map(|(at, item)| (item, part(Part::Tuple(at)))),
282            ")",
283        ),
284        Value::Dict(entries) if entries.is_empty() => out.push_str("[:]"),
285        Value::Dict(entries) => {
286            pieces.push(Piece::Str("["));
287            for (at, (key, item)) in entries.iter().enumerate() {
288                if at > 0 {
289                    pieces.push(Piece::Str(", "));
290                }
291                pieces.extend([
292                    Piece::Value(key, part(Part::Key)),
293                    Piece::Str(": "),
294                    Piece::Value(item, part(Part::Entry)),
295                ]);
296            }
297            pieces.push(Piece::Str("]"));
298        }
299        Value::Record(record) => {
300            pieces.push(Piece::Str(record.shape().name()));
301            named(
302                &mut pieces,
303                record.shape().fields(),
304                record
305                    .fields()
306                    .iter()
307                    .enumerate()
308                    .map(|(at, field)| (field, part(Part::Field(at)))),
309            );
310        }
311        Value::Variant(variant) => {
312            let constructor = variant.constructor();
313            let payload = variant.payload().iter().enumerate().map(|(at, item)| {
314                let at = Part::Payload {
315                    constructor: variant.index(),
316                    part: at,
317                };
318                (item, part(at))
319            });
320            pieces.push(Piece::Str(constructor.name()));
321            match constructor.payload() {
322                Payload::None => {}
323                Payload::Positional(_) => all(&mut pieces, "(", payload, ")"),
324                Payload::Named(fields) => {
325                    named(&mut pieces, fields.iter().map(|field| &**field), payload);
326                }
327            }
328        }
329        Value::Native(_) | Value::Task(_) | Value::Host(_) => return Err(DataError::NotData),
330    }
331    pending.extend(pieces.into_iter().rev());
332    Ok(())
333}
334
335/// `open`, the items separated by `, `, and `close`.
336fn all<'a, A>(
337    pieces: &mut Vec<Piece<'a, A>>,
338    open: &'a str,
339    items: impl Iterator<Item = (&'a Value, A)>,
340    close: &'a str,
341) {
342    pieces.push(Piece::Str(open));
343    for (at, (item, known)) in items.enumerate() {
344        if at > 0 {
345            pieces.push(Piece::Str(", "));
346        }
347        pieces.push(Piece::Value(item, known));
348    }
349    pieces.push(Piece::Str(close));
350}
351
352/// ` { name: value, ... }`, or ` {}` for no fields.
353fn named<'a, A>(
354    pieces: &mut Vec<Piece<'a, A>>,
355    names: impl Iterator<Item = &'a str>,
356    values: impl ExactSizeIterator<Item = (&'a Value, A)>,
357) {
358    if values.len() == 0 {
359        pieces.push(Piece::Str(" {}"));
360        return;
361    }
362    pieces.push(Piece::Str(" { "));
363    for (at, (name, (item, known))) in names.zip(values).enumerate() {
364        if at > 0 {
365            pieces.push(Piece::Str(", "));
366        }
367        pieces.extend([
368            Piece::Str(name),
369            Piece::Str(": "),
370            Piece::Value(item, known),
371        ]);
372    }
373    pieces.push(Piece::Str(" }"));
374}
375
376/// Writes `text` as the one-line text literal that denotes it.
377///
378/// `\`, `"`, line feed and tab use their own escapes, `${` is written `\${`
379/// so that it starts no interpolation, every other code point below U+0020
380/// and U+007F use `\u{...}` in uppercase hexadecimal, and every other code
381/// point is written as itself.
382fn write_literal(out: &mut String, text: &str) {
383    out.push('"');
384    let mut code_points = text.chars().peekable();
385    while let Some(code_point) = code_points.next() {
386        match code_point {
387            '\\' => out.push_str("\\\\"),
388            '"' => out.push_str("\\\""),
389            '\n' => out.push_str("\\n"),
390            '\t' => out.push_str("\\t"),
391            '$' if code_points.peek() == Some(&'{') => out.push_str("\\$"),
392            '\u{0}'..='\u{1f}' | '\u{7f}' => {
393                write!(out, "\\u{{{:X}}}", u32::from(code_point)).expect("writing to a String");
394            }
395            other => out.push(other),
396        }
397    }
398    out.push('"');
399}