flow-lang-value 0.1.0

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 |
//! | `Duration`, `Instant` | ISO 8601: `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.

use std::fmt::Write as _;

use crate::error::DataError;
use crate::shape::Payload;
use crate::text::Text;
use crate::value::Value;

/// Returns what interpolating `value` inserts: a `Text` value's own code
/// points, and any other data value's text form.
pub fn interpolate(value: &Value) -> Result<Text, DataError> {
    match value {
        Value::Text(text) => Ok(text.clone()),
        other => text_form(other).map(Text::from),
    }
}

/// Returns `value`'s text form, with a `Text` written as a literal.
///
/// Reaching a value that is not data is [`DataError::NotData`].
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.
///
/// 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.
pub fn text_form_within(value: &Value, max_bytes: usize) -> Result<Option<String>, DataError> {
    let mut out = String::new();
    let mut pending = vec![Piece::Value(value)];
    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.
            Piece::Value(Value::Decimal(number))
                if number.text_len() > (max_bytes - out.len()) as u128 =>
            {
                return Ok(None);
            }
            Piece::Value(value) => write_value(&mut out, value, &mut pending)?,
        }
        if out.len() > max_bytes {
            return Ok(None);
        }
    }
    Ok(Some(out))
}

/// What is still to write: fixed text, or a value's text form.
enum Piece<'a> {
    Str(&'a str),
    Value(&'a Value),
}

/// Writes a scalar `value`, or pushes an aggregate's pieces onto `pending`,
/// last first, so that they pop in order.
fn write_value<'a>(
    out: &mut String,
    value: &'a Value,
    pending: &mut Vec<Piece<'a>>,
) -> Result<(), DataError> {
    let mut pieces: Vec<Piece<'a>> = Vec::new();
    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) => write!(out, "{number}").expect("writing to a String"),
        Value::Text(text) => write_literal(out, text.as_str()),
        Value::Bytes(bytes) => out.push_str(&bytes.to_base64()),
        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(), "]"),
        Value::Set(items) => all(&mut pieces, "[", items.iter(), "]"),
        Value::Tuple(tuple) => all(&mut pieces, "(", tuple.parts().iter(), ")"),
        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), Piece::Str(": "), Piece::Value(item)]);
            }
            pieces.push(Piece::Str("]"));
        }
        Value::Record(record) => {
            pieces.push(Piece::Str(record.shape().name()));
            named(&mut pieces, record.shape().fields(), record.fields());
        }
        Value::Variant(variant) => {
            let constructor = variant.constructor();
            pieces.push(Piece::Str(constructor.name()));
            match constructor.payload() {
                Payload::None => {}
                Payload::Positional(_) => all(&mut pieces, "(", variant.payload().iter(), ")"),
                Payload::Named(fields) => {
                    named(
                        &mut pieces,
                        fields.iter().map(|field| &**field),
                        variant.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>(
    pieces: &mut Vec<Piece<'a>>,
    open: &'a str,
    items: impl Iterator<Item = &'a Value>,
    close: &'a str,
) {
    pieces.push(Piece::Str(open));
    for (at, item) in items.enumerate() {
        if at > 0 {
            pieces.push(Piece::Str(", "));
        }
        pieces.push(Piece::Value(item));
    }
    pieces.push(Piece::Str(close));
}

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