Skip to main content

flow_value/
value.rs

1//! What a value *is*, and the equality and order every data value has.
2//!
3//! `types.md` gives every data type `==` and the ordering operators,
4//! structurally and automatically, and none to a type that is not data. Both
5//! are one function here, [`compare`]: equality is "compares as equal", so the
6//! two cannot disagree, and a value that is not data is refused by the same
7//! check for both.
8
9use std::any::Any;
10use std::cmp::Ordering;
11use std::fmt;
12use std::sync::Arc;
13
14use crate::collection::{Dict, List, Set};
15use crate::decimal::Decimal;
16use crate::error::DataError;
17use crate::int::Int;
18use crate::shape::{Record, Variant};
19use crate::text::{Bytes, Text};
20use crate::time::{Duration, Instant};
21
22/// A run-time value.
23///
24/// The data variants are `data.md`'s built-in types and `types.md`'s records,
25/// enums, tuples and `Unit`. The last three are values a run holds but that
26/// are not data: they have no equality, order, text or encoding, and every
27/// operation that would need one refuses them with [`DataError::NotData`].
28/// An aggregate holding one is not data either, and the refusal is reached
29/// when the operation reaches it.
30///
31/// Cloning is cheap: every aggregate shares its parts.
32#[derive(Clone, Debug)]
33pub enum Value {
34    /// `()`, the one value of `Unit`.
35    Unit,
36    /// `true` or `false`.
37    Bool(bool),
38    /// An integer.
39    Int(Int),
40    /// An exact decimal.
41    Decimal(Decimal),
42    /// A sequence of code points.
43    Text(Text),
44    /// A sequence of bytes.
45    Bytes(Bytes),
46    /// A list.
47    List(List),
48    /// A dictionary, sorted by key.
49    Dict(Dict),
50    /// A set, sorted.
51    Set(Set),
52    /// A tuple of at least two parts.
53    Tuple(Tuple),
54    /// A record value.
55    Record(Record),
56    /// An enum value: a constructor and its payload.
57    Variant(Variant),
58    /// A length of time.
59    Duration(Duration),
60    /// A point in time.
61    Instant(Instant),
62    /// A value the evaluator implements and this crate cannot see into: a
63    /// function, a closure, a compiled pattern.
64    Native(Native),
65    /// A handle to a running task.
66    Task(TaskId),
67    /// A value of a `@tool type`: the token the host chose for it.
68    Host(HostToken),
69}
70
71impl Value {
72    /// Returns the value `text` holds.
73    pub fn text(text: &str) -> Value {
74        Value::Text(Text::new(text))
75    }
76
77    /// Returns the integer `value`.
78    pub fn int(value: i64) -> Value {
79        Value::Int(Int::from(value))
80    }
81
82    /// Returns a list of `items`, in order.
83    pub fn list(items: impl IntoIterator<Item = Value>) -> Value {
84        Value::List(items.into_iter().collect())
85    }
86
87    /// Returns a tuple of `parts`, in order.
88    pub fn tuple(parts: impl IntoIterator<Item = Value>) -> Value {
89        Value::Tuple(Tuple::new(parts))
90    }
91}
92
93impl Value {
94    /// How deeply the value nests, or more: a scalar is 0 deep and an
95    /// aggregate one deeper than its deepest part, so `[[1]]` is 2 deep.
96    ///
97    /// It costs constant time, since every aggregate records it when it is
98    /// made. It is exact but for a list, a dictionary or a set that kept the
99    /// measure of a larger one it was cut from — a part of a list, or a
100    /// dictionary an entry was removed from — which may report more than it
101    /// holds; [`Value::deeper_than`] is exact.
102    pub fn depth_bound(&self) -> usize {
103        self.meta().depth()
104    }
105
106    /// Whether some part of the value may be a task handle or a [`Native`]
107    /// value, which may itself hold one; `false` means no part is either.
108    ///
109    /// It costs constant time, and like [`Value::depth_bound`] may answer
110    /// `true` for a list, dictionary or set that kept the measure of a
111    /// larger one.
112    pub fn may_hold_tasks(&self) -> bool {
113        self.meta().holds()
114    }
115
116    /// Whether the value nests more than `bound` levels deep.
117    ///
118    /// The answer is exact. It costs constant time when the measure each
119    /// aggregate records settles it, and otherwise walks only the parts
120    /// whose measures do not: those of a part cut from a deeper list. The
121    /// walk is iterative, so a value nested deeper than the native stack is
122    /// measured too.
123    pub fn deeper_than(&self, bound: usize) -> bool {
124        let mut pending: Vec<(&Value, usize)> = vec![(self, bound)];
125        while let Some((value, room)) = pending.pop() {
126            if value.depth_bound() <= room {
127                continue;
128            }
129            // Only an aggregate measures more than 0, so it is too deep
130            // here when no room is left for its parts.
131            let Some(room) = room.checked_sub(1) else {
132                return true;
133            };
134            let at = |part| (part, room);
135            match value {
136                Value::List(items) => pending.extend(items.iter().map(at)),
137                Value::Set(items) => pending.extend(items.iter().map(at)),
138                Value::Tuple(tuple) => pending.extend(tuple.parts().iter().map(at)),
139                Value::Record(record) => pending.extend(record.fields().iter().map(at)),
140                Value::Variant(variant) => pending.extend(variant.payload().iter().map(at)),
141                Value::Dict(entries) => {
142                    pending.extend(entries.iter().flat_map(|(key, item)| [at(key), at(item)]));
143                }
144                _ => unreachable!("only an aggregate measures more than 0"),
145            }
146        }
147        false
148    }
149
150    /// What the value records of its parts.
151    pub(crate) fn meta(&self) -> Meta {
152        match self {
153            Value::List(items) => items.meta,
154            Value::Dict(entries) => entries.meta,
155            Value::Set(items) => items.meta,
156            Value::Tuple(tuple) => tuple.meta,
157            Value::Record(record) => record.meta(),
158            Value::Variant(variant) => variant.meta(),
159            Value::Native(_) | Value::Task(_) => Meta::HANDLE,
160            Value::Unit
161            | Value::Bool(_)
162            | Value::Int(_)
163            | Value::Decimal(_)
164            | Value::Text(_)
165            | Value::Bytes(_)
166            | Value::Duration(_)
167            | Value::Instant(_)
168            | Value::Host(_) => Meta::SCALAR,
169        }
170    }
171}
172
173/// What an aggregate records of its parts when it is made: how deeply it
174/// nests, and whether any part may be a task handle or a native value. Both
175/// are read in constant time ([`Value::depth_bound`],
176/// [`Value::may_hold_tasks`]) and kept in one word, the depth saturating
177/// far beyond any nesting a host allows.
178#[derive(Clone, Copy, PartialEq, Eq, Debug)]
179pub(crate) struct Meta(u32);
180
181impl Meta {
182    /// The bit that says a part may be a task handle or a native value.
183    const HOLDS: u32 = 1 << 31;
184
185    /// The bits that hold the depth, which saturates at their largest value.
186    const DEPTH: u32 = !Meta::HOLDS;
187
188    /// A scalar: 0 deep, holding neither.
189    const SCALAR: Meta = Meta(0);
190
191    /// A task handle or a native value: 0 deep, and one of them.
192    const HANDLE: Meta = Meta(Meta::HOLDS);
193
194    /// An aggregate with no parts: 1 deep.
195    pub(crate) const EMPTY: Meta = Meta(1);
196
197    /// The measure of an aggregate whose parts are `parts`.
198    pub(crate) fn around<'a>(parts: impl IntoIterator<Item = &'a Value>) -> Meta {
199        parts.into_iter().fold(Meta::EMPTY, Meta::with)
200    }
201
202    /// This aggregate's measure with `part` among its parts.
203    #[must_use]
204    pub(crate) fn with(self, part: &Value) -> Meta {
205        self.join(part.meta().deepened())
206    }
207
208    /// The measure of an aggregate holding the parts both `self` and
209    /// `other` measure.
210    #[must_use]
211    pub(crate) fn join(self, other: Meta) -> Meta {
212        let depth = (self.0 & Meta::DEPTH).max(other.0 & Meta::DEPTH);
213        // The two parts are disjoint bits.
214        Meta(depth + ((self.0 | other.0) & Meta::HOLDS))
215    }
216
217    /// The measure one level above: what an aggregate holding only this
218    /// value measures.
219    fn deepened(self) -> Meta {
220        let depth = (self.0 & Meta::DEPTH).saturating_add(1).min(Meta::DEPTH);
221        Meta(depth + (self.0 & Meta::HOLDS))
222    }
223
224    fn depth(self) -> usize {
225        (self.0 & Meta::DEPTH) as usize
226    }
227
228    fn holds(self) -> bool {
229        self.0 & Meta::HOLDS != 0
230    }
231}
232
233/// A tuple's parts, in order.
234#[derive(Clone, Debug)]
235pub struct Tuple {
236    parts: Arc<[Value]>,
237    meta: Meta,
238}
239
240impl Tuple {
241    /// Returns the tuple of `parts`.
242    pub fn new(parts: impl IntoIterator<Item = Value>) -> Self {
243        let parts: Arc<[Value]> = parts.into_iter().collect();
244        Tuple {
245            meta: Meta::around(parts.iter()),
246            parts,
247        }
248    }
249
250    /// Returns the parts, in order.
251    pub fn parts(&self) -> &[Value] {
252        &self.parts
253    }
254}
255
256impl Drop for Tuple {
257    fn drop(&mut self) {
258        if let Some(parts) = Arc::get_mut(&mut self.parts) {
259            dismantle(parts.iter_mut());
260        }
261    }
262}
263
264/// Drops `parts`, the parts of an aggregate being dropped that nothing else
265/// holds, without recursing through them.
266///
267/// Each part that has parts of its own is moved out, leaving `()` behind, so
268/// the aggregate itself drops shallowly; then each moved-out part's own
269/// unshared parts are moved out the same way before it drops. The parts
270/// waiting to drop are a stack on the heap, so dropping a value nested deeper
271/// than the native stack takes constant native depth. A part another value
272/// still holds only loses a reference.
273pub(crate) fn dismantle<'a>(parts: impl Iterator<Item = &'a mut Value>) {
274    let mut pending: Vec<Nested> = Vec::new();
275    move_nested(parts, &mut pending);
276    while let Some(mut nested) = pending.pop() {
277        match &mut nested {
278            Nested::List(items) => {
279                if let Some(buffer) = items.buffer_mut() {
280                    move_nested(buffer.iter_mut(), &mut pending);
281                }
282            }
283            Nested::Dict(entries) => {
284                if let Some(entries) = entries.entries_mut() {
285                    let parts = entries.iter_mut().flat_map(|(key, item)| [key, item]);
286                    move_nested(parts, &mut pending);
287                }
288            }
289            Nested::Set(items) => move_unshared(items.items_mut(), &mut pending),
290            Nested::Tuple(tuple) => move_unshared(Arc::get_mut(&mut tuple.parts), &mut pending),
291            Nested::Record(record) => move_unshared(record.fields_mut(), &mut pending),
292            Nested::Variant(variant) => move_unshared(variant.payload_mut(), &mut pending),
293            Nested::Native(native) => move_unshared(native.held_mut(), &mut pending),
294        }
295        // `nested` drops here, holding no part with parts of its own.
296    }
297}
298
299/// A value that has parts of its own, moved out of the aggregate that held
300/// it to be dropped by `dismantle`.
301enum Nested {
302    List(List),
303    Dict(Dict),
304    Set(Set),
305    Tuple(Tuple),
306    Record(Record),
307    Variant(Variant),
308    Native(Native),
309}
310
311/// Moves `parts`, when nothing else holds them, as [`move_nested`] does.
312fn move_unshared(parts: Option<&mut [Value]>, pending: &mut Vec<Nested>) {
313    if let Some(parts) = parts {
314        move_nested(parts.iter_mut(), pending);
315    }
316}
317
318/// Moves each of `parts` that has parts of its own onto `pending`, leaving
319/// `()` in its place, and leaves every other part where it is.
320fn move_nested<'a>(parts: impl Iterator<Item = &'a mut Value>, pending: &mut Vec<Nested>) {
321    for part in parts {
322        let nested = match std::mem::replace(part, Value::Unit) {
323            Value::List(items) => Nested::List(items),
324            Value::Dict(entries) => Nested::Dict(entries),
325            Value::Set(items) => Nested::Set(items),
326            Value::Tuple(tuple) => Nested::Tuple(tuple),
327            Value::Record(record) => Nested::Record(record),
328            Value::Variant(variant) => Nested::Variant(variant),
329            Value::Native(native) => Nested::Native(native),
330            other => {
331                *part = other;
332                continue;
333            }
334        };
335        pending.push(nested);
336    }
337}
338
339/// A value the evaluator owns, carried opaquely.
340///
341/// This crate cannot depend on the evaluator, so a function value or any
342/// other evaluator-made value is held as `dyn Any` and recovered by the
343/// evaluator with [`Native::downcast`]. Nothing here compares, orders or
344/// prints one.
345///
346/// One that holds values of its own, such as a closure holding what it
347/// captured, is made with [`Native::holding`], so that dropping it hands those
348/// values to `dismantle` like the parts of any other aggregate: a chain of
349/// closures each capturing the last drops without deep recursion.
350#[derive(Clone)]
351pub struct Native(Arc<Carried<dyn Any + Send + Sync>>);
352
353/// A value that a [`Native`] carries and that holds values of its own.
354pub trait Holding: Any + Send + Sync {
355    /// The values it holds, when nothing else holds them with it.
356    fn held_mut(&mut self) -> Option<&mut [Value]>;
357}
358
359/// What a [`Native`] carries: the evaluator's value, and how to reach the
360/// values it holds, if it holds any.
361struct Carried<T: ?Sized> {
362    held: Option<Held>,
363    inner: T,
364}
365
366/// Reaches the values a carried value holds.
367type Held = fn(&mut (dyn Any + Send + Sync)) -> Option<&mut [Value]>;
368
369/// The values `inner`, a `T`, holds.
370fn held_by<T: Holding>(inner: &mut (dyn Any + Send + Sync)) -> Option<&mut [Value]> {
371    inner.downcast_mut::<T>().and_then(T::held_mut)
372}
373
374impl Native {
375    /// Returns a handle to `inner`, which holds no values.
376    pub fn new<T: Any + Send + Sync>(inner: T) -> Self {
377        Native(Arc::new(Carried { held: None, inner }))
378    }
379
380    /// Returns a handle to `inner`, which holds values.
381    pub fn holding<T: Holding>(inner: T) -> Self {
382        Native(Arc::new(Carried {
383            held: Some(held_by::<T>),
384            inner,
385        }))
386    }
387
388    /// Returns the inner value, when it is a `T`.
389    pub fn downcast<T: Any>(&self) -> Option<&T> {
390        self.0.inner.downcast_ref()
391    }
392
393    /// The values the inner value holds, when nothing else holds it.
394    fn held_mut(&mut self) -> Option<&mut [Value]> {
395        let carried = Arc::get_mut(&mut self.0)?;
396        (carried.held?)(&mut carried.inner)
397    }
398}
399
400impl Drop for Native {
401    fn drop(&mut self) {
402        if let Some(held) = self.held_mut() {
403            dismantle(held.iter_mut());
404        }
405    }
406}
407
408impl fmt::Debug for Native {
409    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
410        f.write_str("<native>")
411    }
412}
413
414/// Which task a task handle names. What the number means is the evaluator's.
415#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
416pub struct TaskId(pub u64);
417
418/// The token a host chose for a `@tool type` value. Flow stores it, compares
419/// nothing about it, and hands it back unchanged (`abi.md`).
420#[derive(Clone, Debug)]
421pub struct HostToken(Arc<str>);
422
423impl HostToken {
424    /// Returns the token `text` is.
425    pub fn new(text: &str) -> Self {
426        HostToken(Arc::from(text))
427    }
428
429    /// Returns the token's text.
430    pub fn as_str(&self) -> &str {
431        &self.0
432    }
433}
434
435/// Returns how `left` orders against `right`.
436///
437/// The order is `types.md`'s, structural and total over each data type:
438/// numbers by value, text by code point and bytes by byte, `false` before
439/// `true`; lists, tuples and records element by element in order, with a
440/// proper prefix first; enum values by their constructors' declaration order,
441/// then by payload; dictionaries as their entry lists in key order would, and
442/// sets as their sorted elements would; durations and instants
443/// chronologically.
444///
445/// The two values must be of one type. Reaching a value that is not data is
446/// [`DataError::NotData`], and two values of different shapes is
447/// [`DataError::Mismatch`]; a checked program reaches neither.
448///
449/// The walk keeps the aggregates it is inside on a stack on the heap, so a
450/// value nested deeper than the native stack is compared like any other.
451pub fn compare(left: &Value, right: &Value) -> Result<Ordering, DataError> {
452    let mut open: Vec<(Parts<'_>, Parts<'_>)> = Vec::new();
453    let (mut left, mut right) = (left, right);
454    loop {
455        match step(left, right)? {
456            Step::Decided(Ordering::Equal) => {}
457            Step::Decided(unequal) => return Ok(unequal),
458            Step::Within(a, b) => open.push((a, b)),
459        }
460        // The next pair of parts, closing each aggregate whose parts were all
461        // equal; a proper prefix orders first.
462        loop {
463            let Some((a, b)) = open.last_mut() else {
464                return Ok(Ordering::Equal);
465            };
466            match (a.next(), b.next()) {
467                (Some(a), Some(b)) => {
468                    (left, right) = (a, b);
469                    break;
470                }
471                (Some(_), None) => return Ok(Ordering::Greater),
472                (None, Some(_)) => return Ok(Ordering::Less),
473                (None, None) => {
474                    open.pop();
475                }
476            }
477        }
478    }
479}
480
481/// Returns whether `left == right`: structural equality, which holds exactly
482/// when [`compare`] answers `Equal`.
483pub fn equal(left: &Value, right: &Value) -> Result<bool, DataError> {
484    Ok(compare(left, right)? == Ordering::Equal)
485}
486
487/// What comparing two values comes to at their own level.
488enum Step<'a> {
489    /// Their order, whatever their parts.
490    Decided(Ordering),
491    /// The order of these two sequences of parts, element by element.
492    Within(Parts<'a>, Parts<'a>),
493}
494
495fn step<'a>(left: &'a Value, right: &'a Value) -> Result<Step<'a>, DataError> {
496    let order = match (left, right) {
497        (Value::Unit, Value::Unit) => Ordering::Equal,
498        (Value::Bool(a), Value::Bool(b)) => a.cmp(b),
499        (Value::Int(a), Value::Int(b)) => a.cmp(b),
500        (Value::Decimal(a), Value::Decimal(b)) => a.cmp(b),
501        (Value::Text(a), Value::Text(b)) => a.cmp(b),
502        (Value::Bytes(a), Value::Bytes(b)) => a.cmp(b),
503        (Value::Duration(a), Value::Duration(b)) => a.cmp(b),
504        (Value::Instant(a), Value::Instant(b)) => a.cmp(b),
505        (Value::Variant(a), Value::Variant(b)) if a.index() != b.index() => {
506            a.index().cmp(&b.index())
507        }
508        (Value::List(a), Value::List(b)) => {
509            return Ok(Step::Within(
510                Parts::List(a.elements()),
511                Parts::List(b.elements()),
512            ));
513        }
514        (Value::Set(a), Value::Set(b)) => return Ok(within(a.as_slice(), b.as_slice())),
515        (Value::Tuple(a), Value::Tuple(b)) => return Ok(within(a.parts(), b.parts())),
516        (Value::Record(a), Value::Record(b)) => return Ok(within(a.fields(), b.fields())),
517        (Value::Variant(a), Value::Variant(b)) => return Ok(within(a.payload(), b.payload())),
518        // Entry lists compared pair by pair are the flattened key, value,
519        // key, value sequences compared element by element: each pair has
520        // exactly two parts, so the first difference and the shorter list
521        // fall at the same place in both.
522        (Value::Dict(a), Value::Dict(b)) => {
523            let (a, b) = (a.entries().iter(), b.entries().iter());
524            return Ok(Step::Within(Parts::Dict(a, None), Parts::Dict(b, None)));
525        }
526        (Value::Native(_) | Value::Task(_) | Value::Host(_), _)
527        | (_, Value::Native(_) | Value::Task(_) | Value::Host(_)) => {
528            return Err(DataError::NotData);
529        }
530        _ => return Err(DataError::Mismatch),
531    };
532    Ok(Step::Decided(order))
533}
534
535/// Two slices of parts to compare element by element.
536fn within<'a>(left: &'a [Value], right: &'a [Value]) -> Step<'a> {
537    Step::Within(Parts::Slice(left.iter()), Parts::Slice(right.iter()))
538}
539
540/// The parts of an aggregate, in the order equality and order read them: a
541/// dictionary's as key, value, key, value in key order.
542enum Parts<'a> {
543    /// A slice of parts.
544    Slice(std::slice::Iter<'a, Value>),
545    /// A list's elements.
546    List(std::collections::vec_deque::Iter<'a, Value>),
547    /// A dictionary's entries, and the value of the last key read while it
548    /// is still to come.
549    Dict(std::slice::Iter<'a, (Value, Value)>, Option<&'a Value>),
550}
551
552impl<'a> Iterator for Parts<'a> {
553    type Item = &'a Value;
554
555    fn next(&mut self) -> Option<&'a Value> {
556        match self {
557            Parts::Slice(parts) => parts.next(),
558            Parts::List(items) => items.next(),
559            Parts::Dict(entries, value) => value.take().or_else(|| {
560                let (key, next) = entries.next()?;
561                *value = Some(next);
562                Some(key)
563            }),
564        }
565    }
566}