flow-lang-value 0.1.0-rc.5

The Flow runtime value model: data values, their equality, order and text, and the operations std's built-in types declare.
Documentation
//! The text form of a data value: what `${...}` inserts.
//!
//! `types.md` owns the form of records, enums, tuples and `Unit`, and
//! `data.md` the form of each built-in type. In short:
//!
//! | Value | Text |
//! | --- | --- |
//! | `Int`, `Decimal` | plain decimal digits: `-42`, `1.5`, `2` |
//! | `Bool` | `true`, `false` |
//! | `Text` | itself when interpolated; a one-line text literal inside another value: `"a\"b"` |
//! | `Bytes` | standard base64 with padding, quoted inside another value |
//! | `Duration`, `Instant` | ISO 8601, quoted inside another value: `PT0.25S`, `["2026-03-21T09:30:00Z"]` |
//! | `List`, `Set` | `[a, b]`, `[]` |
//! | `Dict` | `[k: v, k2: v2]`, `[:]` |
//! | `Unit`, tuple | `()`, `(a, b)` |
//! | record | `Name { field: v, other: w }`, `Name {}` |
//! | enum | `Name`, `Name(a, b)`, `Name { field: v }` |
//!
//! Records and enums print their type's declared name without a module or
//! type arguments, every field in declaration order — private ones too, since
//! visibility is not confidentiality — and nothing else.
//!
//! The walk that writes the text form is generic over a [`Spelling`]: what
//! it knows of each value beyond the value. The text form knows nothing
//! more; the value notation, `flow-notation`'s, knows each value's type and
//! adds a newtype's constructor and a whole `Decimal`'s point with the same
//! walk.

use std::fmt::Write as _;

use crate::decimal::Decimal;
use crate::error::DataError;
use crate::text::Text;
use crate::value::Value;
use flow_types::Payload;

/// Returns what interpolating `value` inserts: a `Text` value's own code
/// points, a `Bytes`, `Duration` or `Instant` value's text unquoted, and any
/// other data value's text form.
///
/// # Errors
///
/// [`DataError::NotData`] on reaching a value that is not data.
///
/// # Panics
///
/// As [`text_form`] does.
pub fn interpolate(value: &Value) -> Result<Text, DataError> {
    Ok(interpolate_within(value, usize::MAX)?.expect("no text is longer than usize::MAX bytes"))
}

/// Returns what interpolating `value` inserts, as [`interpolate`] does, when
/// its UTF-8 takes at most `max_bytes` bytes, and `None` otherwise.
///
/// # Errors
///
/// [`DataError::NotData`] on reaching a value that is not data.
pub fn interpolate_within(value: &Value, max_bytes: usize) -> Result<Option<Text>, DataError> {
    let unquoted = |text: String| text[1..text.len() - 1].to_owned();
    match value {
        Value::Text(text) => Ok((text.byte_len() <= max_bytes).then(|| text.clone())),
        Value::Bytes(_) | Value::Duration(_) | Value::Instant(_) => {
            Ok(text_form_within(value, max_bytes.saturating_add(2))?
                .map(|text| Text::from(unquoted(text))))
        }
        other => Ok(text_form_within(other, max_bytes)?.map(Text::from)),
    }
}

/// Returns `value`'s text form, with a `Text`, `Bytes`, `Duration` or
/// `Instant` written as a quoted literal.
///
/// Reaching a value that is not data is [`DataError::NotData`].
///
/// # Errors
///
/// [`DataError::NotData`] on reaching a value that is not data.
///
/// # Panics
///
/// When the text cannot be held in memory, as that of a number with an
/// exponent near `i64::MAX` cannot: a value from outside the program is
/// written with [`text_form_within`] instead.
pub fn text_form(value: &Value) -> Result<String, DataError> {
    Ok(text_form_within(value, usize::MAX)?.expect("no text is longer than usize::MAX bytes"))
}

/// Returns `value`'s text form when its UTF-8 takes at most `max_bytes`
/// bytes, and `None` otherwise.
///
/// # Errors
///
/// [`DataError::NotData`] on reaching a value that is not data.
pub fn text_form_within(value: &Value, max_bytes: usize) -> Result<Option<String>, DataError> {
    spell_within(&TextForm, (), value, max_bytes)
}

/// What a walk that writes a value knows of each value beyond the value
/// itself: nothing, for the text form, or its type, for the value notation,
/// which writes a newtype's constructor and a whole `Decimal`'s point.
/// Every spelling shares the walk and the spelling of every other part.
pub trait Spelling<'a> {
    /// What the spelling knows of the value it is at.
    type At;

    /// The newtype constructor a value at `at` is written inside, and what
    /// is known of the base inside it; `None` for a value written bare.
    fn newtype(&self, at: &Self::At) -> Option<(&'a str, Self::At)>;

    /// What is known of `part` of a value at `at`.
    fn part(&self, at: &Self::At, part: Part) -> Self::At;

    /// Writes the `Decimal` `number`.
    fn decimal(&self, out: &mut String, number: &Decimal);
}

/// A part of an aggregate value, as a [`Spelling`] is asked about it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Part {
    /// An item of a list or a set.
    Item,
    /// A key of a dictionary.
    Key,
    /// A value of a dictionary.
    Entry,
    /// The tuple part at this position.
    Tuple(usize),
    /// The record field at this position, in declaration order.
    Field(usize),
    /// The payload part `part` of the constructor numbered `constructor`.
    Payload {
        /// The constructor's number, in declaration order.
        constructor: usize,
        /// The part's position in its payload.
        part: usize,
    },
}

/// The text form's spelling, which knows nothing of a value but the value.
struct TextForm;

impl<'a> Spelling<'a> for TextForm {
    type At = ();

    fn newtype(&self, (): &()) -> Option<(&'a str, ())> {
        None
    }

    fn part(&self, (): &(), _: Part) {}

    fn decimal(&self, out: &mut String, number: &Decimal) {
        write!(out, "{number}").expect("writing to a String");
    }
}

/// Writes `value`, known to `spelling` as `at`, when its UTF-8 takes at most
/// `max_bytes` bytes, and returns `None` otherwise.
///
/// Writing stops soon after the text passes `max_bytes`, so a value whose
/// text would be far longer costs no more than the bound and the one part
/// that crossed it. The walk keeps what is still to write on a stack on the
/// heap, so a value nested deeper than the native stack is written too.
///
/// # Errors
///
/// [`DataError::NotData`] on reaching a value that is not data.
pub fn spell_within<'a, S: Spelling<'a>>(
    spelling: &S,
    at: S::At,
    value: &'a Value,
    max_bytes: usize,
) -> Result<Option<String>, DataError> {
    let mut out = String::new();
    let mut pending = vec![Piece::Value(value, at)];
    while let Some(piece) = pending.pop() {
        match piece {
            Piece::Str(text) => out.push_str(text),
            // A number's text can be far longer than the number: one with a
            // vast exponent is measured, and refused before it is written.
            // So is a duration's or an instant's, which is a number of
            // seconds.
            Piece::Value(value, _) if at_least_len(value) > room(max_bytes, out.len()) => {
                return Ok(None);
            }
            Piece::Value(value, at) => write_value(spelling, &mut out, value, &at, &mut pending)?,
        }
        if out.len() > max_bytes {
            return Ok(None);
        }
    }
    Ok(Some(out))
}

/// The bytes left before `written` passes `max_bytes`.
fn room(max_bytes: usize, written: usize) -> u128 {
    u128::try_from(max_bytes - written).expect("a usize fits 128 bits")
}

/// A lower bound on the bytes of `value`'s text form, without writing it,
/// for a scalar that is written whole at once: a text or bytes, which may be
/// long, and a number, a duration or an instant, whose text may be far longer
/// than the value when its exponent is vast. Any other value answers 0.
fn at_least_len(value: &Value) -> u128 {
    let widen = |n: usize| u128::try_from(n).expect("a usize fits 128 bits");
    match value {
        // The quotes around the UTF-8, which escaping only lengthens.
        Value::Text(text) => widen(text.byte_len()) + 2,
        // The quotes around padded base64.
        Value::Bytes(bytes) => widen(bytes.len().div_ceil(3)) * 4 + 2,
        Value::Decimal(number) => number.text_len(),
        // `PT`, the seconds, `S`.
        Value::Duration(span) => span.seconds().text_len() + 3,
        // The seconds' fraction is written in full after the second of the
        // minute, and the year has at least as many digits as the whole
        // seconds less the eight a year of seconds takes: so the instant's
        // text is never shorter than the seconds' text less sixteen bytes.
        Value::Instant(at) => at.unix_seconds().text_len().saturating_sub(16),
        _ => 0,
    }
}

/// What is still to write: fixed text, or a value and what the spelling
/// knows of it.
enum Piece<'a, A> {
    Str(&'a str),
    Value(&'a Value, A),
}

/// Writes a scalar `value`, or pushes an aggregate's pieces, or a newtype's
/// constructor around its base, onto `pending`, last first, so that they pop
/// in order.
fn write_value<'a, S: Spelling<'a>>(
    spelling: &S,
    out: &mut String,
    value: &'a Value,
    at: &S::At,
    pending: &mut Vec<Piece<'a, S::At>>,
) -> Result<(), DataError> {
    let mut pieces: Vec<Piece<'a, S::At>> = Vec::new();
    if let Some((name, base)) = spelling.newtype(at) {
        pieces.extend([
            Piece::Str(name),
            Piece::Str("("),
            Piece::Value(value, base),
            Piece::Str(")"),
        ]);
        pending.extend(pieces.into_iter().rev());
        return Ok(());
    }
    let part = |part: Part| spelling.part(at, part);
    match value {
        Value::Unit => out.push_str("()"),
        Value::Bool(flag) => out.push_str(if *flag { "true" } else { "false" }),
        Value::Int(number) => write!(out, "{number}").expect("writing to a String"),
        Value::Decimal(number) => spelling.decimal(out, number),
        Value::Text(text) => write_literal(out, text.as_str()),
        Value::Bytes(bytes) => {
            write!(out, "\"{}\"", bytes.to_base64()).expect("writing to a String");
        }
        Value::Duration(span) => write!(out, "\"{span}\"").expect("writing to a String"),
        Value::Instant(at) => write!(out, "\"{at}\"").expect("writing to a String"),
        Value::List(items) => all(
            &mut pieces,
            "[",
            items.iter().map(|item| (item, part(Part::Item))),
            "]",
        ),
        Value::Set(items) => all(
            &mut pieces,
            "[",
            items.iter().map(|item| (item, part(Part::Item))),
            "]",
        ),
        Value::Tuple(tuple) => all(
            &mut pieces,
            "(",
            tuple
                .parts()
                .iter()
                .enumerate()
                .map(|(at, item)| (item, part(Part::Tuple(at)))),
            ")",
        ),
        Value::Dict(entries) if entries.is_empty() => out.push_str("[:]"),
        Value::Dict(entries) => {
            pieces.push(Piece::Str("["));
            for (at, (key, item)) in entries.iter().enumerate() {
                if at > 0 {
                    pieces.push(Piece::Str(", "));
                }
                pieces.extend([
                    Piece::Value(key, part(Part::Key)),
                    Piece::Str(": "),
                    Piece::Value(item, part(Part::Entry)),
                ]);
            }
            pieces.push(Piece::Str("]"));
        }
        Value::Record(record) => {
            pieces.push(Piece::Str(record.shape().name()));
            named(
                &mut pieces,
                record.shape().fields(),
                record
                    .fields()
                    .iter()
                    .enumerate()
                    .map(|(at, field)| (field, part(Part::Field(at)))),
            );
        }
        Value::Variant(variant) => {
            let constructor = variant.constructor();
            let payload = variant.payload().iter().enumerate().map(|(at, item)| {
                let at = Part::Payload {
                    constructor: variant.index(),
                    part: at,
                };
                (item, part(at))
            });
            pieces.push(Piece::Str(constructor.name()));
            match constructor.payload() {
                Payload::None => {}
                Payload::Positional(_) => all(&mut pieces, "(", payload, ")"),
                Payload::Named(fields) => {
                    named(&mut pieces, fields.iter().map(|field| &**field), payload);
                }
            }
        }
        Value::Native(_) | Value::Task(_) | Value::Host(_) => return Err(DataError::NotData),
    }
    pending.extend(pieces.into_iter().rev());
    Ok(())
}

/// `open`, the items separated by `, `, and `close`.
fn all<'a, A>(
    pieces: &mut Vec<Piece<'a, A>>,
    open: &'a str,
    items: impl Iterator<Item = (&'a Value, A)>,
    close: &'a str,
) {
    pieces.push(Piece::Str(open));
    for (at, (item, known)) in items.enumerate() {
        if at > 0 {
            pieces.push(Piece::Str(", "));
        }
        pieces.push(Piece::Value(item, known));
    }
    pieces.push(Piece::Str(close));
}

/// ` { name: value, ... }`, or ` {}` for no fields.
fn named<'a, A>(
    pieces: &mut Vec<Piece<'a, A>>,
    names: impl Iterator<Item = &'a str>,
    values: impl ExactSizeIterator<Item = (&'a Value, A)>,
) {
    if values.len() == 0 {
        pieces.push(Piece::Str(" {}"));
        return;
    }
    pieces.push(Piece::Str(" { "));
    for (at, (name, (item, known))) in names.zip(values).enumerate() {
        if at > 0 {
            pieces.push(Piece::Str(", "));
        }
        pieces.extend([
            Piece::Str(name),
            Piece::Str(": "),
            Piece::Value(item, known),
        ]);
    }
    pieces.push(Piece::Str(" }"));
}

/// Writes `text` as the one-line text literal that denotes it.
///
/// `\`, `"`, line feed and tab use their own escapes, `${` is written `\${`
/// so that it starts no interpolation, every other code point below U+0020
/// and U+007F use `\u{...}` in uppercase hexadecimal, and every other code
/// point is written as itself.
fn write_literal(out: &mut String, text: &str) {
    out.push('"');
    let mut code_points = text.chars().peekable();
    while let Some(code_point) = code_points.next() {
        match code_point {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\t' => out.push_str("\\t"),
            '$' if code_points.peek() == Some(&'{') => out.push_str("\\$"),
            '\u{0}'..='\u{1f}' | '\u{7f}' => {
                write!(out, "\\u{{{:X}}}", u32::from(code_point)).expect("writing to a String");
            }
            other => out.push(other),
        }
    }
    out.push('"');
}