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};
21use crate::tree::{Measure, Member};
22use flow_types::Payload;
23
24/// A run-time value.
25///
26/// The data variants are `data.md`'s built-in types and `types.md`'s records,
27/// enums, tuples and `Unit`. The last three are values a run holds but that
28/// are not data: they have no equality, order, text or encoding, and every
29/// operation that would need one refuses them with [`DataError::NotData`].
30/// An aggregate holding one is not data either, and the refusal is reached
31/// when the operation reaches it.
32///
33/// Cloning is cheap: every aggregate shares its parts.
34#[derive(Clone, Debug)]
35pub enum Value {
36    /// `()`, the one value of `Unit`.
37    Unit,
38    /// `true` or `false`.
39    Bool(bool),
40    /// An integer.
41    Int(Int),
42    /// An exact decimal.
43    Decimal(Decimal),
44    /// A sequence of code points.
45    Text(Text),
46    /// A sequence of bytes.
47    Bytes(Bytes),
48    /// A list.
49    List(List),
50    /// A dictionary, sorted by key.
51    Dict(Dict),
52    /// A set, sorted.
53    Set(Set),
54    /// A tuple of at least two parts.
55    Tuple(Tuple),
56    /// A record value.
57    Record(Record),
58    /// An enum value: a constructor and its payload.
59    Variant(Variant),
60    /// A length of time.
61    Duration(Duration),
62    /// A point in time.
63    Instant(Instant),
64    /// A value the evaluator implements and this crate cannot see into: a
65    /// function, a closure, a compiled pattern.
66    Native(Native),
67    /// A handle to a running task.
68    Task(TaskId),
69    /// A value of a host type: the token the host chose for it.
70    Host(HostToken),
71}
72
73impl Value {
74    /// Returns the value `text` holds.
75    pub fn text(text: &str) -> Value {
76        Value::Text(Text::new(text))
77    }
78
79    /// Returns the integer `value`.
80    pub fn int(value: i64) -> Value {
81        Value::Int(Int::from(value))
82    }
83
84    /// Returns a list of `items`, in order.
85    pub fn list(items: impl IntoIterator<Item = Value>) -> Value {
86        Value::List(items.into_iter().collect())
87    }
88
89    /// Returns a tuple of `parts`, in order.
90    pub fn tuple(parts: impl IntoIterator<Item = Value>) -> Value {
91        Value::Tuple(Tuple::new(parts))
92    }
93
94    /// The list this is, if it is one.
95    pub fn as_list(&self) -> Option<&List> {
96        if let Value::List(list) = self {
97            Some(list)
98        } else {
99            None
100        }
101    }
102}
103
104impl Value {
105    /// How deeply the value nests as data: a scalar is 0 deep and an
106    /// aggregate one deeper than its deepest part, so `[[1]]` is 2 deep. A
107    /// task or a [`Native`] value is a handle, 0 deep whatever it holds, so
108    /// a function value adds no depth for what it captured.
109    ///
110    /// It is exact for every value whose parts are data, and costs constant
111    /// time: every aggregate records it when it is made, and a part cut from
112    /// a list or a dictionary an entry was removed from measures what it
113    /// holds.
114    pub fn depth_bound(&self) -> usize {
115        self.meta().depth()
116    }
117
118    /// Whether some part of the value is a task handle or a [`Native`]
119    /// value, which may itself hold one; `false` means no part is either.
120    ///
121    /// It costs constant time, as [`Value::depth_bound`] does.
122    pub fn may_hold_tasks(&self) -> bool {
123        self.meta().holds()
124    }
125
126    /// Whether the value nests more than `bound` levels deep, in constant
127    /// time.
128    pub fn deeper_than(&self, bound: usize) -> bool {
129        self.depth_bound() > bound
130    }
131
132    /// Returns what tells this value apart from the values alive that were
133    /// made separately, or `None` for a value that history never points at.
134    ///
135    /// It is `Some` for a `Text`, `Bytes`, a host token, a `List`, a `Set`, a
136    /// `Dict`, a tuple, a record and an enum value: the values history
137    /// writes once and points at afterwards (`trace.md`, *Slots*). It is
138    /// read from the shared parts the value is made of, in constant time,
139    /// so a clone answers as the original does. Two values that answer
140    /// alike are equal; two that answer differently may be equal too,
141    /// having been made separately, and two windows onto one list's tree
142    /// are different lists and answer differently.
143    ///
144    /// The answer means something only while the value, or a clone of it,
145    /// is kept: once every clone is dropped, a value made later may reuse
146    /// its memory and answer alike. A writer that remembers what it wrote by
147    /// identity keeps a clone of each value it remembers.
148    pub fn identity(&self) -> Option<Identity> {
149        let addresses = match self {
150            Value::Text(text) => Addresses::Text(text.id()),
151            Value::Bytes(bytes) => Addresses::Bytes(bytes.id()),
152            Value::Host(token) => Addresses::Host(token.id()),
153            Value::List(items) => Addresses::List(items.id()),
154            Value::Set(items) => Addresses::Set(items.id()),
155            Value::Dict(entries) => Addresses::Dict(entries.id()),
156            Value::Tuple(tuple) => Addresses::Tuple(tuple.id()),
157            Value::Record(record) => Addresses::Record(record.id()),
158            Value::Variant(variant) => Addresses::Variant(variant.id()),
159            Value::Unit
160            | Value::Bool(_)
161            | Value::Int(_)
162            | Value::Decimal(_)
163            | Value::Duration(_)
164            | Value::Instant(_)
165            | Value::Native(_)
166            | Value::Task(_) => return None,
167        };
168        Some(Identity(addresses))
169    }
170
171    /// What the value records of its parts.
172    pub(crate) fn meta(&self) -> Meta {
173        match self {
174            Value::List(items) => items.meta,
175            Value::Dict(entries) => entries.meta(),
176            Value::Set(items) => items.meta(),
177            Value::Tuple(tuple) => tuple.meta,
178            Value::Record(record) => record.meta(),
179            Value::Variant(variant) => variant.meta(),
180            Value::Native(_) | Value::Task(_) => Meta::HANDLE,
181            Value::Unit
182            | Value::Bool(_)
183            | Value::Int(_)
184            | Value::Decimal(_)
185            | Value::Text(_)
186            | Value::Bytes(_)
187            | Value::Duration(_)
188            | Value::Instant(_)
189            | Value::Host(_) => Meta::SCALAR,
190        }
191    }
192}
193
194/// What tells a value apart from the values alive that were made separately
195/// ([`Value::identity`]): the kind of value, and the addresses of the shared
196/// parts it is made of.
197#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
198pub struct Identity(Addresses);
199
200/// The shared parts each kind of value is made of, by address. The kind is
201/// part of the answer, so that values of two kinds with no parts of their
202/// own, such as an empty list and an empty dictionary, never answer alike.
203#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
204enum Addresses {
205    Text(usize),
206    Bytes(usize),
207    Host(usize),
208    /// Its front, its tree, its window onto the tree (where it starts and
209    /// how many elements it takes) and its back.
210    List([usize; 5]),
211    Set(usize),
212    Dict(usize),
213    Tuple(usize),
214    /// Its shape and its fields.
215    Record([usize; 2]),
216    /// Its shape, its constructor's index and its payload.
217    Variant([usize; 3]),
218}
219
220/// What an aggregate records of its parts when it is made: how deeply it
221/// nests, and whether any part may be a task handle or a native value. Both
222/// are read in constant time ([`Value::depth_bound`],
223/// [`Value::may_hold_tasks`]) and kept in one word, the depth saturating
224/// far beyond any nesting a host allows.
225#[derive(Clone, Copy, PartialEq, Eq, Debug)]
226pub struct Meta(u32);
227
228impl Meta {
229    /// The bit that says a part may be a task handle or a native value.
230    const HOLDS: u32 = 1 << 31;
231
232    /// The bits that hold the depth, which saturates at their largest value.
233    const DEPTH: u32 = !Meta::HOLDS;
234
235    /// A scalar: 0 deep, holding neither.
236    const SCALAR: Meta = Meta(0);
237
238    /// A task handle or a native value: 0 deep, and one of them.
239    const HANDLE: Meta = Meta(Meta::HOLDS);
240
241    /// The measure of an aggregate whose parts are `parts`.
242    pub(crate) fn around<'a>(parts: impl IntoIterator<Item = &'a Value>) -> Meta {
243        parts.into_iter().fold(Meta::EMPTY, Meta::with)
244    }
245
246    /// This aggregate's measure with `part` among its parts.
247    #[must_use]
248    pub(crate) fn with(self, part: &Value) -> Meta {
249        self.join(part.meta().deepened())
250    }
251
252    /// The measure one level above: what an aggregate holding only this
253    /// value measures.
254    fn deepened(self) -> Meta {
255        let depth = (self.0 & Meta::DEPTH).saturating_add(1).min(Meta::DEPTH);
256        Meta(depth + (self.0 & Meta::HOLDS))
257    }
258
259    fn depth(self) -> usize {
260        usize::try_from(self.0 & Meta::DEPTH).expect("a depth of 31 bits fits usize")
261    }
262
263    fn holds(self) -> bool {
264        self.0 & Meta::HOLDS != 0
265    }
266}
267
268impl Measure for Meta {
269    /// An aggregate with no parts: 1 deep.
270    const EMPTY: Meta = Meta(1);
271
272    /// The measure of an aggregate holding the parts both `self` and
273    /// `other` measure.
274    fn join(self, other: Meta) -> Meta {
275        let depth = (self.0 & Meta::DEPTH).max(other.0 & Meta::DEPTH);
276        // The two parts are disjoint bits.
277        Meta(depth + ((self.0 | other.0) & Meta::HOLDS))
278    }
279}
280
281/// A tuple's parts, in order.
282#[derive(Clone, Debug)]
283pub struct Tuple {
284    parts: Arc<[Value]>,
285    meta: Meta,
286}
287
288impl Tuple {
289    /// Returns the tuple of `parts`.
290    pub fn new(parts: impl IntoIterator<Item = Value>) -> Self {
291        let parts: Arc<[Value]> = parts.into_iter().collect();
292        Tuple {
293            meta: Meta::around(parts.iter()),
294            parts,
295        }
296    }
297
298    /// Returns the parts, in order.
299    pub fn parts(&self) -> &[Value] {
300        &self.parts
301    }
302
303    /// The parts, when nothing else holds them.
304    fn parts_mut(&mut self) -> Option<&mut [Value]> {
305        Arc::get_mut(&mut self.parts)
306    }
307
308    /// What tells this tuple apart from every other alive: its parts.
309    fn id(&self) -> usize {
310        Arc::as_ptr(&self.parts).cast::<Value>().addr()
311    }
312}
313
314impl Drop for Tuple {
315    fn drop(&mut self) {
316        if let Some(parts) = self.parts_mut() {
317            dismantle(parts.iter_mut());
318        }
319    }
320}
321
322/// Drops `parts`, the parts of an aggregate being dropped that nothing else
323/// holds, without recursing through them.
324///
325/// Each part that has parts of its own is moved out, leaving `()` behind, so
326/// the aggregate itself drops shallowly; then each moved-out part's own
327/// unshared parts are moved out the same way before it drops. The parts
328/// waiting to drop are a stack on the heap, so dropping a value nested deeper
329/// than the native stack takes constant native depth. A part another value
330/// still holds only loses a reference.
331pub(crate) fn dismantle<'a>(parts: impl Iterator<Item = &'a mut Value>) {
332    let mut pending: Vec<Value> = Vec::new();
333    take_nested(parts, &mut pending);
334    while let Some(mut value) = pending.pop() {
335        value.take_unshared_parts(&mut pending);
336        // `value` drops here, holding no part with parts of its own.
337    }
338}
339
340/// Moves each of `parts` that may have parts of its own onto `into`,
341/// leaving `()` in its place: an aggregate, or a [`Native`] value, whose
342/// parts its depth does not count. Every scalar and task stays where it is.
343fn take_nested<'a>(parts: impl Iterator<Item = &'a mut Value>, into: &mut Vec<Value>) {
344    for part in parts {
345        if part.depth_bound() > 0 || matches!(part, Value::Native(_)) {
346            into.push(std::mem::replace(part, Value::Unit));
347        }
348    }
349}
350
351impl Value {
352    /// Returns the parts the value holds, in the order equality and order
353    /// read them: a list's elements, a dictionary's keys and values as key,
354    /// value, key, value in key order, a set's members, a tuple's, record's
355    /// or enum value's parts, and the values a [`Native`] value holds. A
356    /// scalar has none.
357    ///
358    /// This is the one place that knows what an aggregate holds; every walk
359    /// over a value's parts reads it, so none recurses once per level.
360    pub fn parts(&self) -> Parts<'_> {
361        Parts(match self {
362            Value::List(items) => Of::List(items.elements()),
363            Value::Dict(entries) => Of::Dict(entries.entries(), None),
364            Value::Set(items) => Of::Set(items.members()),
365            Value::Tuple(tuple) => Of::Slice(tuple.parts().iter()),
366            Value::Record(record) => Of::Slice(record.fields().iter()),
367            Value::Variant(variant) => Of::Slice(variant.payload().iter()),
368            Value::Native(native) => Of::Slice(native.held().iter()),
369            Value::Unit
370            | Value::Bool(_)
371            | Value::Int(_)
372            | Value::Decimal(_)
373            | Value::Text(_)
374            | Value::Bytes(_)
375            | Value::Duration(_)
376            | Value::Instant(_)
377            | Value::Task(_)
378            | Value::Host(_) => Of::Slice([].iter()),
379        })
380    }
381
382    /// Returns the part at `index` in [`Value::parts`] order, if there is
383    /// one: a dictionary's entry `i` is its parts `2i`, the key, and
384    /// `2i + 1`, the value.
385    pub fn part(&self, index: usize) -> Option<&Value> {
386        match self {
387            Value::List(items) => items.get(index),
388            Value::Dict(entries) => {
389                let (key, value) = entries.entry(index / 2)?;
390                Some(if index.is_multiple_of(2) { key } else { value })
391            }
392            Value::Set(items) => items.member(index),
393            Value::Tuple(tuple) => tuple.parts().get(index),
394            Value::Record(record) => record.fields().get(index),
395            Value::Variant(variant) => variant.payload().get(index),
396            Value::Native(native) => native.held().get(index),
397            Value::Unit
398            | Value::Bool(_)
399            | Value::Int(_)
400            | Value::Decimal(_)
401            | Value::Text(_)
402            | Value::Bytes(_)
403            | Value::Duration(_)
404            | Value::Instant(_)
405            | Value::Task(_)
406            | Value::Host(_) => None,
407        }
408    }
409
410    /// Returns the value and every part inside it, each before its own
411    /// parts, keeping the parts still to visit on a stack on the heap, so a
412    /// value nested deeper than the native stack is walked like any other.
413    /// [`Walk::skip_current`] passes over the parts of the value last
414    /// returned.
415    pub fn walk(&self) -> Walk<'_> {
416        Walk {
417            first: Some(self),
418            last: None,
419            open: Vec::new(),
420        }
421    }
422
423    /// Moves the parts of this value that nothing else holds and that may
424    /// have parts of their own onto `into`, leaving `()` in their place, so
425    /// that the value drops shallowly.
426    fn take_unshared_parts(&mut self, into: &mut Vec<Value>) {
427        match self {
428            Value::List(items) => take_nested(items.unshared_parts(), into),
429            Value::Dict(entries) => take_nested(entries.unshared_parts(), into),
430            Value::Set(items) => take_nested(items.unshared_parts(), into),
431            Value::Tuple(tuple) => take_nested(tuple.parts_mut().into_iter().flatten(), into),
432            Value::Record(record) => take_nested(record.fields_mut().into_iter().flatten(), into),
433            Value::Variant(variant) => {
434                take_nested(variant.payload_mut().into_iter().flatten(), into);
435            }
436            Value::Native(native) => take_nested(native.held_mut().into_iter().flatten(), into),
437            Value::Unit
438            | Value::Bool(_)
439            | Value::Int(_)
440            | Value::Decimal(_)
441            | Value::Text(_)
442            | Value::Bytes(_)
443            | Value::Duration(_)
444            | Value::Instant(_)
445            | Value::Task(_)
446            | Value::Host(_) => {}
447        }
448    }
449
450    /// Returns whether the two values are the same: equal as data, where
451    /// both are, and otherwise built alike, with the same host tokens, the
452    /// same task handles, and native values their carriers call the same
453    /// ([`Carry::same`]). A value shares its identity with itself and its
454    /// clones, which answers at once. Two values of different shapes are not
455    /// the same.
456    ///
457    /// This is how a run's history tells a value it recorded from one it
458    /// meets again; it is an equivalence and orders nothing. The walk keeps
459    /// its place on the heap.
460    pub fn same(&self, other: &Value) -> bool {
461        zip(Rule::Recorded, self, other).is_ok()
462    }
463
464    /// Where `self` and `other` first differ by [`Value::same`], in the order
465    /// their parts are compared: the path to the two parts that differ, and
466    /// those parts. `None` when they are the same.
467    ///
468    /// Two aggregates of different lengths differ as wholes, at the path to
469    /// them.
470    pub fn first_difference<'a>(&'a self, other: &'a Value) -> Option<Difference<'a>> {
471        zip(Rule::Recorded, self, other)
472            .err()
473            .map(Stopped::difference)
474    }
475}
476
477/// Where two values first differ ([`Value::first_difference`]).
478#[derive(Debug)]
479pub struct Difference<'a> {
480    /// The steps from the whole value to the parts that differ.
481    pub path: Path<'a>,
482    /// The part of the first value.
483    pub left: &'a Value,
484    /// The part of the second value.
485    pub right: &'a Value,
486}
487
488/// Steps into a value from the whole of it, outermost first.
489#[derive(Debug, Default)]
490pub struct Path<'a>(pub Vec<Step<'a>>);
491
492/// One step into a value from the aggregate that holds it.
493#[derive(Debug)]
494pub enum Step<'a> {
495    /// A record field, or a named payload field, by name.
496    Field(&'a str),
497    /// The payload of the enum constructor of this name.
498    Constructor(&'a str),
499    /// The element at this index, from 0, of a list, set, tuple or
500    /// positional payload, or the key of a dictionary's entry at this index.
501    Element(usize),
502    /// The value under this key of a dictionary.
503    Key(&'a Value),
504}
505
506/// The bound on a key's text in a shown path.
507const SHOWN_KEY: usize = 40;
508
509impl fmt::Display for Path<'_> {
510    /// As std's `json.show_path` writes a path: a field or constructor as
511    /// its name, after a `.` unless it comes first, an element as `[i]`, and
512    /// a key as `[`, its text form, `]`.
513    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514        for (index, step) in self.0.iter().enumerate() {
515            match step {
516                Step::Field(name) | Step::Constructor(name) => {
517                    if index > 0 {
518                        f.write_str(".")?;
519                    }
520                    f.write_str(name)?;
521                }
522                Step::Element(at) => write!(f, "[{at}]")?,
523                Step::Key(key) => match crate::render::text_form_within(key, SHOWN_KEY) {
524                    Ok(Some(text)) => write!(f, "[{text}]")?,
525                    _ => f.write_str("[…]")?,
526                },
527            }
528        }
529        Ok(())
530    }
531}
532
533/// The parts of a value ([`Value::parts`]), in order.
534#[derive(Debug)]
535pub struct Parts<'a>(Of<'a>);
536
537/// Where the parts of a value lie.
538#[derive(Debug)]
539enum Of<'a> {
540    /// A slice of parts.
541    Slice(std::slice::Iter<'a, Value>),
542    /// A list's elements.
543    List(crate::collection::Elements<'a>),
544    /// A set's members.
545    Set(crate::tree::Iter<'a, Member>),
546    /// A dictionary's entries, and the value of the last key read while it
547    /// is still to come.
548    Dict(crate::tree::Iter<'a, (Value, Value)>, Option<&'a Value>),
549}
550
551impl<'a> Iterator for Parts<'a> {
552    type Item = &'a Value;
553
554    #[inline]
555    fn next(&mut self) -> Option<&'a Value> {
556        match &mut self.0 {
557            Of::Slice(parts) => parts.next(),
558            Of::List(items) => items.next(),
559            Of::Set(members) => members.next().map(Member::value),
560            Of::Dict(entries, value) => value.take().or_else(|| {
561                let (key, next) = entries.next()?;
562                *value = Some(next);
563                Some(key)
564            }),
565        }
566    }
567
568    #[inline]
569    fn size_hint(&self) -> (usize, Option<usize>) {
570        let left = match &self.0 {
571            Of::Slice(parts) => parts.len(),
572            Of::List(items) => items.len(),
573            Of::Set(members) => members.len(),
574            Of::Dict(entries, value) => 2 * entries.len() + usize::from(value.is_some()),
575        };
576        (left, Some(left))
577    }
578}
579
580impl ExactSizeIterator for Parts<'_> {}
581
582/// A value and every part inside it, each before its own parts
583/// ([`Value::walk`]).
584#[derive(Debug)]
585pub struct Walk<'a> {
586    /// The value the walk starts at, until it is returned.
587    first: Option<&'a Value>,
588    /// The value last returned, whose parts are still to be opened.
589    last: Option<&'a Value>,
590    /// The parts of each value being walked through, innermost last.
591    open: Vec<Parts<'a>>,
592}
593
594impl Walk<'_> {
595    /// Passes over the parts of the value last returned.
596    pub fn skip_current(&mut self) {
597        self.last = None;
598    }
599}
600
601impl<'a> Iterator for Walk<'a> {
602    type Item = &'a Value;
603
604    fn next(&mut self) -> Option<&'a Value> {
605        if let Some(last) = self.last.take() {
606            self.open.push(last.parts());
607        }
608        if let Some(first) = self.first.take() {
609            self.last = Some(first);
610            return Some(first);
611        }
612        loop {
613            let parts = self.open.last_mut()?;
614            if let Some(part) = parts.next() {
615                self.last = Some(part);
616                return Some(part);
617            }
618            self.open.pop();
619        }
620    }
621}
622
623/// A value the evaluator owns, carried opaquely.
624///
625/// This crate cannot depend on the evaluator, so a function value or any
626/// other evaluator-made value is carried as a [`Carry`] and recovered by the
627/// evaluator with [`Native::downcast`]. Nothing here compares, orders or
628/// prints one.
629///
630/// The values a carried value holds, such as what a closure captured, are
631/// among the native value's parts ([`Value::parts`]), and dropping it hands
632/// them to `dismantle` like the parts of any other aggregate: a chain of
633/// closures each capturing the last drops without deep recursion.
634#[derive(Clone)]
635pub struct Native(Arc<dyn Carry>);
636
637/// What a [`Native`] value carries, and what it can say of itself.
638pub trait Carry: Any + Send + Sync {
639    /// The values it holds.
640    fn held(&self) -> &[Value];
641
642    /// The values [`Carry::held`] returns, to be moved out as it drops, or
643    /// none when another carrier shares them and drops them in its turn.
644    /// Neither has a default, so a carrier that holds values says how to
645    /// move them out and its drop stays shallow.
646    fn held_mut(&mut self) -> &mut [Value];
647
648    /// Whether `other` is the same as this one, as [`Value::same`] asks.
649    fn same(&self, _other: &dyn Carry) -> bool {
650        false
651    }
652}
653
654impl Native {
655    /// Returns a handle to `inner`.
656    pub fn new<T: Carry>(inner: T) -> Self {
657        Native(Arc::new(inner))
658    }
659
660    /// Returns the inner value, when it is a `T`.
661    pub fn downcast<T: Any>(&self) -> Option<&T> {
662        let inner: &dyn Any = &*self.0;
663        inner.downcast_ref()
664    }
665
666    /// The values the inner value holds.
667    pub(crate) fn held(&self) -> &[Value] {
668        self.0.held()
669    }
670
671    /// The values the inner value holds, when nothing else holds it.
672    fn held_mut(&mut self) -> Option<&mut [Value]> {
673        Arc::get_mut(&mut self.0).map(Carry::held_mut)
674    }
675
676    /// Whether the two carry one value, or what their carrier calls the
677    /// same.
678    fn same(&self, other: &Native) -> bool {
679        Arc::ptr_eq(&self.0, &other.0) || self.0.same(&*other.0)
680    }
681}
682
683impl Drop for Native {
684    fn drop(&mut self) {
685        if let Some(held) = self.held_mut() {
686            dismantle(held.iter_mut());
687        }
688    }
689}
690
691impl fmt::Debug for Native {
692    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
693        f.write_str("<native>")
694    }
695}
696
697/// Which task a task handle names. What the number means is the evaluator's,
698/// which makes each one with [`TaskId::next`] from [`TaskId::FIRST`].
699#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
700pub struct TaskId(u64);
701
702impl TaskId {
703    /// The first task's id.
704    pub const FIRST: TaskId = TaskId(0);
705
706    /// The id after this one.
707    ///
708    /// # Panics
709    ///
710    /// When it is the last id a `u64` holds, which no run makes.
711    #[must_use]
712    pub fn next(self) -> TaskId {
713        TaskId(self.0.checked_add(1).expect("fewer than 2^64 tasks"))
714    }
715}
716
717/// Its number, which says which task it is and nothing more.
718impl fmt::Display for TaskId {
719    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
720        self.0.fmt(f)
721    }
722}
723
724/// The token a host chose for a host type value. Flow stores it, compares
725/// nothing about it, and hands it back unchanged (`abi.md`).
726#[derive(Clone, Debug)]
727pub struct HostToken(Arc<str>);
728
729impl HostToken {
730    /// Returns the token `text` is.
731    pub fn new(text: &str) -> Self {
732        HostToken(Arc::from(text))
733    }
734
735    /// Returns the token's text.
736    pub fn as_str(&self) -> &str {
737        &self.0
738    }
739
740    /// What tells this token apart from every other alive.
741    fn id(&self) -> usize {
742        Arc::as_ptr(&self.0).cast::<u8>().addr()
743    }
744}
745
746/// Returns how `left` orders against `right`.
747///
748/// The order is `types.md`'s, structural and total over each data type:
749/// numbers by value, text by code point and bytes by byte, `false` before
750/// `true`; lists, tuples and records element by element in order, with a
751/// proper prefix first; enum values by their constructors' declaration order,
752/// then by payload; dictionaries as their entry lists in key order would, and
753/// sets as their sorted elements would; durations and instants
754/// chronologically.
755///
756/// The two values must be of one type. Reaching a value that is not data is
757/// [`DataError::NotData`], and two values of different shapes is
758/// [`DataError::Mismatch`]; a checked program reaches neither.
759///
760/// Two records or two enum values of different declarations are of
761/// different shapes. The walk keeps the aggregates it is inside on a stack on
762/// the heap, so a value nested deeper than the native stack is compared like
763/// any other.
764///
765/// # Errors
766///
767/// [`DataError::NotData`] on reaching a value that is not data, and
768/// [`DataError::Mismatch`] on two values of different shapes.
769pub fn compare(left: &Value, right: &Value) -> Result<Ordering, DataError> {
770    match zip(Rule::Data, left, right).map_err(|stopped| stopped.stop) {
771        Ok(()) => Ok(Ordering::Equal),
772        Err(Stop::Unequal(order)) => Ok(order),
773        Err(Stop::Mismatch) => Err(DataError::Mismatch),
774        Err(Stop::NotData) => Err(DataError::NotData),
775    }
776}
777
778/// Returns whether `left == right`: structural equality, which holds exactly
779/// when [`compare`] answers `Equal`.
780///
781/// # Errors
782///
783/// As [`compare`].
784pub fn equal(left: &Value, right: &Value) -> Result<bool, DataError> {
785    Ok(compare(left, right)? == Ordering::Equal)
786}
787
788/// Which rule a walk over two values compares them by.
789#[derive(Clone, Copy, PartialEq, Eq)]
790enum Rule {
791    /// `types.md`'s equality and order over data ([`compare`]).
792    Data,
793    /// Whether the two are the same ([`Value::same`]).
794    Recorded,
795}
796
797/// Why a walk over two values stopped before finding them equal.
798enum Stop {
799    /// They differ, ordered so.
800    Unequal(Ordering),
801    /// They are of different shapes.
802    Mismatch,
803    /// One part is not data.
804    NotData,
805}
806
807/// An aggregate pair a walk is inside: the two aggregates, their parts
808/// still to compare, how many parts of each it has taken, and the parts of
809/// `left` it took last and before that.
810struct Level<'a> {
811    left: &'a Value,
812    right: &'a Value,
813    parts: (Parts<'a>, Parts<'a>),
814    taken: usize,
815    current: Option<&'a Value>,
816    last: Option<&'a Value>,
817}
818
819/// Where a walk over two values stopped, and why.
820struct Stopped<'a> {
821    stop: Stop,
822    open: Vec<Level<'a>>,
823    left: &'a Value,
824    right: &'a Value,
825}
826
827impl<'a> Stopped<'a> {
828    /// The path through the open aggregates to the parts the walk stopped at.
829    fn difference(self) -> Difference<'a> {
830        let mut path = Vec::new();
831        for level in &self.open {
832            let at = level.taken - 1;
833            match level.left {
834                Value::Record(record) => {
835                    path.push(
836                        record
837                            .shape()
838                            .field(at)
839                            .map_or(Step::Element(at), Step::Field),
840                    );
841                }
842                Value::Variant(variant) => {
843                    let constructor = variant.constructor();
844                    path.push(Step::Constructor(constructor.name()));
845                    path.push(match constructor.payload() {
846                        Payload::Named(fields) => Step::Field(&fields[at]),
847                        Payload::None | Payload::Positional(_) => Step::Element(at),
848                    });
849                }
850                Value::Dict(_) if at % 2 == 1 => {
851                    path.push(level.last.map_or(Step::Element(at / 2), Step::Key));
852                }
853                Value::Dict(_) => path.push(Step::Element(at / 2)),
854                Value::List(_)
855                | Value::Set(_)
856                | Value::Tuple(_)
857                | Value::Unit
858                | Value::Bool(_)
859                | Value::Int(_)
860                | Value::Decimal(_)
861                | Value::Text(_)
862                | Value::Bytes(_)
863                | Value::Duration(_)
864                | Value::Instant(_)
865                | Value::Native(_)
866                | Value::Task(_)
867                | Value::Host(_) => path.push(Step::Element(at)),
868            }
869        }
870        Difference {
871            path: Path(path),
872            left: self.left,
873            right: self.right,
874        }
875    }
876}
877
878/// Walks `left` and `right` side by side under `rule`, keeping the
879/// aggregates it is inside on a stack on the heap; `Ok` when they are equal
880/// throughout, and otherwise where it stopped.
881fn zip<'a>(rule: Rule, left: &'a Value, right: &'a Value) -> Result<(), Stopped<'a>> {
882    let mut open: Vec<Level<'a>> = Vec::new();
883    let (mut left, mut right) = (left, right);
884    loop {
885        match step(rule, left, right) {
886            Ok(Some(parts)) => open.push(Level {
887                left,
888                right,
889                parts,
890                taken: 0,
891                current: None,
892                last: None,
893            }),
894            Ok(None) => {}
895            Err(stop) => {
896                return Err(Stopped {
897                    stop,
898                    open,
899                    left,
900                    right,
901                });
902            }
903        }
904        // The next pair of parts, closing each aggregate whose parts were all
905        // equal; a proper prefix orders first.
906        loop {
907            let Some(level) = open.last_mut() else {
908                return Ok(());
909            };
910            let (a, b) = (level.parts.0.next(), level.parts.1.next());
911            let order = match (a, b) {
912                (Some(a), Some(b)) => {
913                    level.taken += 1;
914                    level.last = level.current.replace(a);
915                    (left, right) = (a, b);
916                    break;
917                }
918                (Some(_), None) => Ordering::Greater,
919                (None, Some(_)) => Ordering::Less,
920                (None, None) => {
921                    open.pop();
922                    continue;
923                }
924            };
925            let whole = open.pop().expect("the level just read");
926            return Err(Stopped {
927                stop: Stop::Unequal(order),
928                open,
929                left: whole.left,
930                right: whole.right,
931            });
932        }
933    }
934}
935
936/// Compares two values at their own level under `rule`: `None` when they
937/// are equal whatever their parts, or the two sequences of parts to compare
938/// element by element.
939///
940/// A record or an enum value of one declaration is never equal to one of
941/// another: their shapes are compared before their parts, which is the
942/// guard [`compare`] documents for values no checked program makes.
943fn step<'a>(
944    rule: Rule,
945    left: &'a Value,
946    right: &'a Value,
947) -> Result<Option<(Parts<'a>, Parts<'a>)>, Stop> {
948    if rule == Rule::Recorded
949        && let (Some(a), Some(b)) = (left.identity(), right.identity())
950        && a == b
951    {
952        return Ok(None);
953    }
954    let order = match (left, right) {
955        (Value::Unit, Value::Unit) => Ordering::Equal,
956        (Value::Bool(a), Value::Bool(b)) => a.cmp(b),
957        (Value::Int(a), Value::Int(b)) => a.cmp(b),
958        (Value::Decimal(a), Value::Decimal(b)) => a.cmp(b),
959        (Value::Text(a), Value::Text(b)) => a.cmp(b),
960        (Value::Bytes(a), Value::Bytes(b)) => a.cmp(b),
961        (Value::Duration(a), Value::Duration(b)) => a.cmp(b),
962        (Value::Instant(a), Value::Instant(b)) => a.cmp(b),
963        (Value::Record(a), Value::Record(b)) if !same_shape(a.shape(), b.shape()) => {
964            return Err(Stop::Mismatch);
965        }
966        (Value::Variant(a), Value::Variant(b)) if !same_shape(a.shape(), b.shape()) => {
967            return Err(Stop::Mismatch);
968        }
969        (Value::Variant(a), Value::Variant(b)) if a.index() != b.index() => {
970            a.index().cmp(&b.index())
971        }
972        (Value::List(_), Value::List(_))
973        | (Value::Dict(_), Value::Dict(_))
974        | (Value::Set(_), Value::Set(_))
975        | (Value::Tuple(_), Value::Tuple(_))
976        | (Value::Record(_), Value::Record(_))
977        | (Value::Variant(_), Value::Variant(_)) => {
978            return Ok(Some((left.parts(), right.parts())));
979        }
980        (Value::Host(a), Value::Host(b)) if rule == Rule::Recorded => a.as_str().cmp(b.as_str()),
981        (Value::Task(a), Value::Task(b)) if rule == Rule::Recorded => a.0.cmp(&b.0),
982        (Value::Native(a), Value::Native(b)) if rule == Rule::Recorded => {
983            if a.same(b) {
984                Ordering::Equal
985            } else {
986                return Err(Stop::Mismatch);
987            }
988        }
989        (Value::Native(_) | Value::Task(_) | Value::Host(_), _)
990        | (_, Value::Native(_) | Value::Task(_) | Value::Host(_)) => return Err(Stop::NotData),
991        _ => return Err(Stop::Mismatch),
992    };
993    match order {
994        Ordering::Equal => Ok(None),
995        unequal => Err(Stop::Unequal(unequal)),
996    }
997}
998
999/// Whether two declarations' shapes are one: the same description, or two
1000/// equal ones.
1001fn same_shape<T: PartialEq>(left: &Arc<T>, right: &Arc<T>) -> bool {
1002    Arc::ptr_eq(left, right) || left == right
1003}