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
//! Records and enum values, by declaration (`types.md`, *Records* and
//! *Enums*).
//!
//! A value holds its parts in **declaration order**, as slots, beside a shared
//! description of its declaration. The slots are what equality and order read
//! — field by field in declaration order, and for an enum the constructor's
//! position first — and the description is what the text form reads: the
//! type's name, its constructors' names and its fields' names. Two values of
//! one type share one description, so holding it costs a pointer.

use std::sync::Arc;

use crate::value::{Meta, Value};

/// A record declaration: its name and its fields in declaration order.
#[derive(Debug, PartialEq, Eq)]
pub struct RecordShape {
    name: Arc<str>,
    fields: Box<[Arc<str>]>,
}

impl RecordShape {
    /// Returns the shape of the record `name` declaring `fields`, in order.
    pub fn new<'a>(name: &str, fields: impl IntoIterator<Item = &'a str>) -> Arc<Self> {
        Arc::new(RecordShape {
            name: Arc::from(name),
            fields: fields.into_iter().map(Arc::from).collect(),
        })
    }

    /// Returns the type's declared name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the field names, in declaration order.
    pub fn fields(&self) -> impl ExactSizeIterator<Item = &str> {
        self.fields.iter().map(|field| &**field)
    }
}

/// A record value.
#[derive(Clone, Debug)]
pub struct Record {
    shape: Arc<RecordShape>,
    fields: Arc<[Value]>,
    meta: Meta,
}

impl Record {
    /// Returns the record of `shape` with `fields` in declaration order, or
    /// `None` when there is not exactly one value per declared field.
    pub fn new(shape: Arc<RecordShape>, fields: Vec<Value>) -> Option<Self> {
        (fields.len() == shape.fields.len()).then(|| Record {
            meta: Meta::around(&fields),
            shape,
            fields: fields.into(),
        })
    }

    /// Returns the declaration.
    pub fn shape(&self) -> &Arc<RecordShape> {
        &self.shape
    }

    /// Returns the field values, in declaration order.
    pub fn fields(&self) -> &[Value] {
        &self.fields
    }

    /// Returns the field values when nothing else holds them.
    /// What it records of its fields.
    pub(crate) fn meta(&self) -> Meta {
        self.meta
    }

    pub(crate) fn fields_mut(&mut self) -> Option<&mut [Value]> {
        Arc::get_mut(&mut self.fields)
    }

    /// Returns the field at a declaration index.
    pub fn field(&self, index: usize) -> Option<&Value> {
        self.fields.get(index)
    }
}

impl Drop for Record {
    fn drop(&mut self) {
        if let Some(fields) = self.fields_mut() {
            crate::value::dismantle(fields.iter_mut());
        }
    }
}

/// What a constructor carries.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Payload {
    /// Nothing: `TimedOut`.
    None,
    /// This many positional values: `Failed(problem)`.
    Positional(usize),
    /// Named fields, in declaration order: `StepFailed { step, last }`.
    Named(Box<[Arc<str>]>),
}

impl Payload {
    /// Returns how many values the payload holds.
    pub fn arity(&self) -> usize {
        match self {
            Payload::None => 0,
            Payload::Positional(count) => *count,
            Payload::Named(fields) => fields.len(),
        }
    }

    /// Returns named fields, in declaration order.
    pub fn named<'a>(fields: impl IntoIterator<Item = &'a str>) -> Self {
        Payload::Named(fields.into_iter().map(Arc::from).collect())
    }
}

/// One constructor of an enum declaration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Constructor {
    name: Arc<str>,
    payload: Payload,
}

impl Constructor {
    /// Returns the constructor `name` carrying `payload`.
    pub fn new(name: &str, payload: Payload) -> Self {
        Constructor {
            name: Arc::from(name),
            payload,
        }
    }

    /// Returns the constructor's name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns what it carries.
    pub fn payload(&self) -> &Payload {
        &self.payload
    }
}

/// An enum declaration: its name and its constructors in declaration order.
#[derive(Debug, PartialEq, Eq)]
pub struct EnumShape {
    name: Arc<str>,
    constructors: Box<[Constructor]>,
}

impl EnumShape {
    /// Returns the shape of the enum `name` declaring `constructors`, in
    /// order.
    pub fn new(name: &str, constructors: impl IntoIterator<Item = Constructor>) -> Arc<Self> {
        Arc::new(EnumShape {
            name: Arc::from(name),
            constructors: constructors.into_iter().collect(),
        })
    }

    /// Returns the type's declared name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the constructor at a declaration index.
    pub fn constructor(&self, index: usize) -> Option<&Constructor> {
        self.constructors.get(index)
    }
}

/// An enum value.
#[derive(Clone, Debug)]
pub struct Variant {
    shape: Arc<EnumShape>,
    index: u32,
    meta: Meta,
    payload: Arc<[Value]>,
}

impl Variant {
    /// Returns the value of the constructor at a declaration index carrying
    /// `payload`, or `None` when there is no such constructor or the payload
    /// does not hold exactly as many values as it declares.
    pub fn new(shape: Arc<EnumShape>, index: usize, payload: Vec<Value>) -> Option<Self> {
        let arity = shape.constructor(index)?.payload.arity();
        let index = u32::try_from(index).ok()?;
        (payload.len() == arity).then(|| Variant {
            meta: Meta::around(&payload),
            shape,
            index,
            payload: payload.into(),
        })
    }

    /// Returns the declaration.
    pub fn shape(&self) -> &Arc<EnumShape> {
        &self.shape
    }

    /// Returns the constructor's declaration index.
    pub fn index(&self) -> usize {
        self.index as usize
    }

    /// Returns the constructor.
    pub fn constructor(&self) -> &Constructor {
        &self.shape.constructors[self.index()]
    }

    /// Returns the payload values, in declaration order.
    pub fn payload(&self) -> &[Value] {
        &self.payload
    }

    /// Returns the payload values when nothing else holds them.
    /// What it records of its payload.
    pub(crate) fn meta(&self) -> Meta {
        self.meta
    }

    pub(crate) fn payload_mut(&mut self) -> Option<&mut [Value]> {
        Arc::get_mut(&mut self.payload)
    }
}

impl Drop for Variant {
    fn drop(&mut self) {
        if let Some(payload) = self.payload_mut() {
            crate::value::dismantle(payload.iter_mut());
        }
    }
}