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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
//! What a value *is*, and the equality and order every data value has.
//!
//! `types.md` gives every data type `==` and the ordering operators,
//! structurally and automatically, and none to a type that is not data. Both
//! are one function here, [`compare`]: equality is "compares as equal", so the
//! two cannot disagree, and a value that is not data is refused by the same
//! check for both.

use std::any::Any;
use std::cmp::Ordering;
use std::fmt;
use std::sync::Arc;

use crate::collection::{Dict, List, Set};
use crate::decimal::Decimal;
use crate::error::DataError;
use crate::int::Int;
use crate::shape::{Record, Variant};
use crate::text::{Bytes, Text};
use crate::time::{Duration, Instant};
use crate::tree::{Measure, Member};
use flow_types::Payload;

/// A run-time value.
///
/// The data variants are `data.md`'s built-in types and `types.md`'s records,
/// enums, tuples and `Unit`. The last three are values a run holds but that
/// are not data: they have no equality, order, text or encoding, and every
/// operation that would need one refuses them with [`DataError::NotData`].
/// An aggregate holding one is not data either, and the refusal is reached
/// when the operation reaches it.
///
/// Cloning is cheap: every aggregate shares its parts.
#[derive(Clone, Debug)]
pub enum Value {
    /// `()`, the one value of `Unit`.
    Unit,
    /// `true` or `false`.
    Bool(bool),
    /// An integer.
    Int(Int),
    /// An exact decimal.
    Decimal(Decimal),
    /// A sequence of code points.
    Text(Text),
    /// A sequence of bytes.
    Bytes(Bytes),
    /// A list.
    List(List),
    /// A dictionary, sorted by key.
    Dict(Dict),
    /// A set, sorted.
    Set(Set),
    /// A tuple of at least two parts.
    Tuple(Tuple),
    /// A record value.
    Record(Record),
    /// An enum value: a constructor and its payload.
    Variant(Variant),
    /// A length of time.
    Duration(Duration),
    /// A point in time.
    Instant(Instant),
    /// A value the evaluator implements and this crate cannot see into: a
    /// function, a closure, a compiled pattern.
    Native(Native),
    /// A handle to a running task.
    Task(TaskId),
    /// A value of a host type: the token the host chose for it.
    Host(HostToken),
}

impl Value {
    /// Returns the value `text` holds.
    pub fn text(text: &str) -> Value {
        Value::Text(Text::new(text))
    }

    /// Returns the integer `value`.
    pub fn int(value: i64) -> Value {
        Value::Int(Int::from(value))
    }

    /// Returns a list of `items`, in order.
    pub fn list(items: impl IntoIterator<Item = Value>) -> Value {
        Value::List(items.into_iter().collect())
    }

    /// Returns a tuple of `parts`, in order.
    pub fn tuple(parts: impl IntoIterator<Item = Value>) -> Value {
        Value::Tuple(Tuple::new(parts))
    }

    /// The list this is, if it is one.
    pub fn as_list(&self) -> Option<&List> {
        if let Value::List(list) = self {
            Some(list)
        } else {
            None
        }
    }
}

impl Value {
    /// How deeply the value nests as data: a scalar is 0 deep and an
    /// aggregate one deeper than its deepest part, so `[[1]]` is 2 deep. A
    /// task or a [`Native`] value is a handle, 0 deep whatever it holds, so
    /// a function value adds no depth for what it captured.
    ///
    /// It is exact for every value whose parts are data, and costs constant
    /// time: every aggregate records it when it is made, and a part cut from
    /// a list or a dictionary an entry was removed from measures what it
    /// holds.
    pub fn depth_bound(&self) -> usize {
        self.meta().depth()
    }

    /// Whether some part of the value is a task handle or a [`Native`]
    /// value, which may itself hold one; `false` means no part is either.
    ///
    /// It costs constant time, as [`Value::depth_bound`] does.
    pub fn may_hold_tasks(&self) -> bool {
        self.meta().holds()
    }

    /// Whether the value nests more than `bound` levels deep, in constant
    /// time.
    pub fn deeper_than(&self, bound: usize) -> bool {
        self.depth_bound() > bound
    }

    /// Returns what tells this value apart from the values alive that were
    /// made separately, or `None` for a value that history never points at.
    ///
    /// It is `Some` for a `Text`, `Bytes`, a host token, a `List`, a `Set`, a
    /// `Dict`, a tuple, a record and an enum value: the values history
    /// writes once and points at afterwards (`trace.md`, *Slots*). It is
    /// read from the shared parts the value is made of, in constant time,
    /// so a clone answers as the original does. Two values that answer
    /// alike are equal; two that answer differently may be equal too,
    /// having been made separately, and two windows onto one list's tree
    /// are different lists and answer differently.
    ///
    /// The answer means something only while the value, or a clone of it,
    /// is kept: once every clone is dropped, a value made later may reuse
    /// its memory and answer alike. A writer that remembers what it wrote by
    /// identity keeps a clone of each value it remembers.
    pub fn identity(&self) -> Option<Identity> {
        let addresses = match self {
            Value::Text(text) => Addresses::Text(text.id()),
            Value::Bytes(bytes) => Addresses::Bytes(bytes.id()),
            Value::Host(token) => Addresses::Host(token.id()),
            Value::List(items) => Addresses::List(items.id()),
            Value::Set(items) => Addresses::Set(items.id()),
            Value::Dict(entries) => Addresses::Dict(entries.id()),
            Value::Tuple(tuple) => Addresses::Tuple(tuple.id()),
            Value::Record(record) => Addresses::Record(record.id()),
            Value::Variant(variant) => Addresses::Variant(variant.id()),
            Value::Unit
            | Value::Bool(_)
            | Value::Int(_)
            | Value::Decimal(_)
            | Value::Duration(_)
            | Value::Instant(_)
            | Value::Native(_)
            | Value::Task(_) => return None,
        };
        Some(Identity(addresses))
    }

    /// What the value records of its parts.
    pub(crate) fn meta(&self) -> Meta {
        match self {
            Value::List(items) => items.meta,
            Value::Dict(entries) => entries.meta(),
            Value::Set(items) => items.meta(),
            Value::Tuple(tuple) => tuple.meta,
            Value::Record(record) => record.meta(),
            Value::Variant(variant) => variant.meta(),
            Value::Native(_) | Value::Task(_) => Meta::HANDLE,
            Value::Unit
            | Value::Bool(_)
            | Value::Int(_)
            | Value::Decimal(_)
            | Value::Text(_)
            | Value::Bytes(_)
            | Value::Duration(_)
            | Value::Instant(_)
            | Value::Host(_) => Meta::SCALAR,
        }
    }
}

/// What tells a value apart from the values alive that were made separately
/// ([`Value::identity`]): the kind of value, and the addresses of the shared
/// parts it is made of.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Identity(Addresses);

/// The shared parts each kind of value is made of, by address. The kind is
/// part of the answer, so that values of two kinds with no parts of their
/// own, such as an empty list and an empty dictionary, never answer alike.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
enum Addresses {
    Text(usize),
    Bytes(usize),
    Host(usize),
    /// Its front, its tree, its window onto the tree (where it starts and
    /// how many elements it takes) and its back.
    List([usize; 5]),
    Set(usize),
    Dict(usize),
    Tuple(usize),
    /// Its shape and its fields.
    Record([usize; 2]),
    /// Its shape, its constructor's index and its payload.
    Variant([usize; 3]),
}

/// What an aggregate records of its parts when it is made: how deeply it
/// nests, and whether any part may be a task handle or a native value. Both
/// are read in constant time ([`Value::depth_bound`],
/// [`Value::may_hold_tasks`]) and kept in one word, the depth saturating
/// far beyond any nesting a host allows.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Meta(u32);

impl Meta {
    /// The bit that says a part may be a task handle or a native value.
    const HOLDS: u32 = 1 << 31;

    /// The bits that hold the depth, which saturates at their largest value.
    const DEPTH: u32 = !Meta::HOLDS;

    /// A scalar: 0 deep, holding neither.
    const SCALAR: Meta = Meta(0);

    /// A task handle or a native value: 0 deep, and one of them.
    const HANDLE: Meta = Meta(Meta::HOLDS);

    /// The measure of an aggregate whose parts are `parts`.
    pub(crate) fn around<'a>(parts: impl IntoIterator<Item = &'a Value>) -> Meta {
        parts.into_iter().fold(Meta::EMPTY, Meta::with)
    }

    /// This aggregate's measure with `part` among its parts.
    #[must_use]
    pub(crate) fn with(self, part: &Value) -> Meta {
        self.join(part.meta().deepened())
    }

    /// The measure one level above: what an aggregate holding only this
    /// value measures.
    fn deepened(self) -> Meta {
        let depth = (self.0 & Meta::DEPTH).saturating_add(1).min(Meta::DEPTH);
        Meta(depth + (self.0 & Meta::HOLDS))
    }

    fn depth(self) -> usize {
        usize::try_from(self.0 & Meta::DEPTH).expect("a depth of 31 bits fits usize")
    }

    fn holds(self) -> bool {
        self.0 & Meta::HOLDS != 0
    }
}

impl Measure for Meta {
    /// An aggregate with no parts: 1 deep.
    const EMPTY: Meta = Meta(1);

    /// The measure of an aggregate holding the parts both `self` and
    /// `other` measure.
    fn join(self, other: Meta) -> Meta {
        let depth = (self.0 & Meta::DEPTH).max(other.0 & Meta::DEPTH);
        // The two parts are disjoint bits.
        Meta(depth + ((self.0 | other.0) & Meta::HOLDS))
    }
}

/// A tuple's parts, in order.
#[derive(Clone, Debug)]
pub struct Tuple {
    parts: Arc<[Value]>,
    meta: Meta,
}

impl Tuple {
    /// Returns the tuple of `parts`.
    pub fn new(parts: impl IntoIterator<Item = Value>) -> Self {
        let parts: Arc<[Value]> = parts.into_iter().collect();
        Tuple {
            meta: Meta::around(parts.iter()),
            parts,
        }
    }

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

    /// The parts, when nothing else holds them.
    fn parts_mut(&mut self) -> Option<&mut [Value]> {
        Arc::get_mut(&mut self.parts)
    }

    /// What tells this tuple apart from every other alive: its parts.
    fn id(&self) -> usize {
        Arc::as_ptr(&self.parts).cast::<Value>().addr()
    }
}

impl Drop for Tuple {
    fn drop(&mut self) {
        if let Some(parts) = self.parts_mut() {
            dismantle(parts.iter_mut());
        }
    }
}

/// Drops `parts`, the parts of an aggregate being dropped that nothing else
/// holds, without recursing through them.
///
/// Each part that has parts of its own is moved out, leaving `()` behind, so
/// the aggregate itself drops shallowly; then each moved-out part's own
/// unshared parts are moved out the same way before it drops. The parts
/// waiting to drop are a stack on the heap, so dropping a value nested deeper
/// than the native stack takes constant native depth. A part another value
/// still holds only loses a reference.
pub(crate) fn dismantle<'a>(parts: impl Iterator<Item = &'a mut Value>) {
    let mut pending: Vec<Value> = Vec::new();
    take_nested(parts, &mut pending);
    while let Some(mut value) = pending.pop() {
        value.take_unshared_parts(&mut pending);
        // `value` drops here, holding no part with parts of its own.
    }
}

/// Moves each of `parts` that may have parts of its own onto `into`,
/// leaving `()` in its place: an aggregate, or a [`Native`] value, whose
/// parts its depth does not count. Every scalar and task stays where it is.
fn take_nested<'a>(parts: impl Iterator<Item = &'a mut Value>, into: &mut Vec<Value>) {
    for part in parts {
        if part.depth_bound() > 0 || matches!(part, Value::Native(_)) {
            into.push(std::mem::replace(part, Value::Unit));
        }
    }
}

impl Value {
    /// Returns the parts the value holds, in the order equality and order
    /// read them: a list's elements, a dictionary's keys and values as key,
    /// value, key, value in key order, a set's members, a tuple's, record's
    /// or enum value's parts, and the values a [`Native`] value holds. A
    /// scalar has none.
    ///
    /// This is the one place that knows what an aggregate holds; every walk
    /// over a value's parts reads it, so none recurses once per level.
    pub fn parts(&self) -> Parts<'_> {
        Parts(match self {
            Value::List(items) => Of::List(items.elements()),
            Value::Dict(entries) => Of::Dict(entries.entries(), None),
            Value::Set(items) => Of::Set(items.members()),
            Value::Tuple(tuple) => Of::Slice(tuple.parts().iter()),
            Value::Record(record) => Of::Slice(record.fields().iter()),
            Value::Variant(variant) => Of::Slice(variant.payload().iter()),
            Value::Native(native) => Of::Slice(native.held().iter()),
            Value::Unit
            | Value::Bool(_)
            | Value::Int(_)
            | Value::Decimal(_)
            | Value::Text(_)
            | Value::Bytes(_)
            | Value::Duration(_)
            | Value::Instant(_)
            | Value::Task(_)
            | Value::Host(_) => Of::Slice([].iter()),
        })
    }

    /// Returns the part at `index` in [`Value::parts`] order, if there is
    /// one: a dictionary's entry `i` is its parts `2i`, the key, and
    /// `2i + 1`, the value.
    pub fn part(&self, index: usize) -> Option<&Value> {
        match self {
            Value::List(items) => items.get(index),
            Value::Dict(entries) => {
                let (key, value) = entries.entry(index / 2)?;
                Some(if index.is_multiple_of(2) { key } else { value })
            }
            Value::Set(items) => items.member(index),
            Value::Tuple(tuple) => tuple.parts().get(index),
            Value::Record(record) => record.fields().get(index),
            Value::Variant(variant) => variant.payload().get(index),
            Value::Native(native) => native.held().get(index),
            Value::Unit
            | Value::Bool(_)
            | Value::Int(_)
            | Value::Decimal(_)
            | Value::Text(_)
            | Value::Bytes(_)
            | Value::Duration(_)
            | Value::Instant(_)
            | Value::Task(_)
            | Value::Host(_) => None,
        }
    }

    /// Returns the value and every part inside it, each before its own
    /// parts, keeping the parts still to visit on a stack on the heap, so a
    /// value nested deeper than the native stack is walked like any other.
    /// [`Walk::skip_current`] passes over the parts of the value last
    /// returned.
    pub fn walk(&self) -> Walk<'_> {
        Walk {
            first: Some(self),
            last: None,
            open: Vec::new(),
        }
    }

    /// Moves the parts of this value that nothing else holds and that may
    /// have parts of their own onto `into`, leaving `()` in their place, so
    /// that the value drops shallowly.
    fn take_unshared_parts(&mut self, into: &mut Vec<Value>) {
        match self {
            Value::List(items) => take_nested(items.unshared_parts(), into),
            Value::Dict(entries) => take_nested(entries.unshared_parts(), into),
            Value::Set(items) => take_nested(items.unshared_parts(), into),
            Value::Tuple(tuple) => take_nested(tuple.parts_mut().into_iter().flatten(), into),
            Value::Record(record) => take_nested(record.fields_mut().into_iter().flatten(), into),
            Value::Variant(variant) => {
                take_nested(variant.payload_mut().into_iter().flatten(), into);
            }
            Value::Native(native) => take_nested(native.held_mut().into_iter().flatten(), into),
            Value::Unit
            | Value::Bool(_)
            | Value::Int(_)
            | Value::Decimal(_)
            | Value::Text(_)
            | Value::Bytes(_)
            | Value::Duration(_)
            | Value::Instant(_)
            | Value::Task(_)
            | Value::Host(_) => {}
        }
    }

    /// Returns whether the two values are the same: equal as data, where
    /// both are, and otherwise built alike, with the same host tokens, the
    /// same task handles, and native values their carriers call the same
    /// ([`Carry::same`]). A value shares its identity with itself and its
    /// clones, which answers at once. Two values of different shapes are not
    /// the same.
    ///
    /// This is how a run's history tells a value it recorded from one it
    /// meets again; it is an equivalence and orders nothing. The walk keeps
    /// its place on the heap.
    pub fn same(&self, other: &Value) -> bool {
        zip(Rule::Recorded, self, other).is_ok()
    }

    /// Where `self` and `other` first differ by [`Value::same`], in the order
    /// their parts are compared: the path to the two parts that differ, and
    /// those parts. `None` when they are the same.
    ///
    /// Two aggregates of different lengths differ as wholes, at the path to
    /// them.
    pub fn first_difference<'a>(&'a self, other: &'a Value) -> Option<Difference<'a>> {
        zip(Rule::Recorded, self, other)
            .err()
            .map(Stopped::difference)
    }
}

/// Where two values first differ ([`Value::first_difference`]).
#[derive(Debug)]
pub struct Difference<'a> {
    /// The steps from the whole value to the parts that differ.
    pub path: Path<'a>,
    /// The part of the first value.
    pub left: &'a Value,
    /// The part of the second value.
    pub right: &'a Value,
}

/// Steps into a value from the whole of it, outermost first.
#[derive(Debug, Default)]
pub struct Path<'a>(pub Vec<Step<'a>>);

/// One step into a value from the aggregate that holds it.
#[derive(Debug)]
pub enum Step<'a> {
    /// A record field, or a named payload field, by name.
    Field(&'a str),
    /// The payload of the enum constructor of this name.
    Constructor(&'a str),
    /// The element at this index, from 0, of a list, set, tuple or
    /// positional payload, or the key of a dictionary's entry at this index.
    Element(usize),
    /// The value under this key of a dictionary.
    Key(&'a Value),
}

/// The bound on a key's text in a shown path.
const SHOWN_KEY: usize = 40;

impl fmt::Display for Path<'_> {
    /// As std's `json.show_path` writes a path: a field or constructor as
    /// its name, after a `.` unless it comes first, an element as `[i]`, and
    /// a key as `[`, its text form, `]`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (index, step) in self.0.iter().enumerate() {
            match step {
                Step::Field(name) | Step::Constructor(name) => {
                    if index > 0 {
                        f.write_str(".")?;
                    }
                    f.write_str(name)?;
                }
                Step::Element(at) => write!(f, "[{at}]")?,
                Step::Key(key) => match crate::render::text_form_within(key, SHOWN_KEY) {
                    Ok(Some(text)) => write!(f, "[{text}]")?,
                    _ => f.write_str("[…]")?,
                },
            }
        }
        Ok(())
    }
}

/// The parts of a value ([`Value::parts`]), in order.
#[derive(Debug)]
pub struct Parts<'a>(Of<'a>);

/// Where the parts of a value lie.
#[derive(Debug)]
enum Of<'a> {
    /// A slice of parts.
    Slice(std::slice::Iter<'a, Value>),
    /// A list's elements.
    List(crate::collection::Elements<'a>),
    /// A set's members.
    Set(crate::tree::Iter<'a, Member>),
    /// A dictionary's entries, and the value of the last key read while it
    /// is still to come.
    Dict(crate::tree::Iter<'a, (Value, Value)>, Option<&'a Value>),
}

impl<'a> Iterator for Parts<'a> {
    type Item = &'a Value;

    #[inline]
    fn next(&mut self) -> Option<&'a Value> {
        match &mut self.0 {
            Of::Slice(parts) => parts.next(),
            Of::List(items) => items.next(),
            Of::Set(members) => members.next().map(Member::value),
            Of::Dict(entries, value) => value.take().or_else(|| {
                let (key, next) = entries.next()?;
                *value = Some(next);
                Some(key)
            }),
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let left = match &self.0 {
            Of::Slice(parts) => parts.len(),
            Of::List(items) => items.len(),
            Of::Set(members) => members.len(),
            Of::Dict(entries, value) => 2 * entries.len() + usize::from(value.is_some()),
        };
        (left, Some(left))
    }
}

impl ExactSizeIterator for Parts<'_> {}

/// A value and every part inside it, each before its own parts
/// ([`Value::walk`]).
#[derive(Debug)]
pub struct Walk<'a> {
    /// The value the walk starts at, until it is returned.
    first: Option<&'a Value>,
    /// The value last returned, whose parts are still to be opened.
    last: Option<&'a Value>,
    /// The parts of each value being walked through, innermost last.
    open: Vec<Parts<'a>>,
}

impl Walk<'_> {
    /// Passes over the parts of the value last returned.
    pub fn skip_current(&mut self) {
        self.last = None;
    }
}

impl<'a> Iterator for Walk<'a> {
    type Item = &'a Value;

    fn next(&mut self) -> Option<&'a Value> {
        if let Some(last) = self.last.take() {
            self.open.push(last.parts());
        }
        if let Some(first) = self.first.take() {
            self.last = Some(first);
            return Some(first);
        }
        loop {
            let parts = self.open.last_mut()?;
            if let Some(part) = parts.next() {
                self.last = Some(part);
                return Some(part);
            }
            self.open.pop();
        }
    }
}

/// A value the evaluator owns, carried opaquely.
///
/// This crate cannot depend on the evaluator, so a function value or any
/// other evaluator-made value is carried as a [`Carry`] and recovered by the
/// evaluator with [`Native::downcast`]. Nothing here compares, orders or
/// prints one.
///
/// The values a carried value holds, such as what a closure captured, are
/// among the native value's parts ([`Value::parts`]), and dropping it hands
/// them to `dismantle` like the parts of any other aggregate: a chain of
/// closures each capturing the last drops without deep recursion.
#[derive(Clone)]
pub struct Native(Arc<dyn Carry>);

/// What a [`Native`] value carries, and what it can say of itself.
pub trait Carry: Any + Send + Sync {
    /// The values it holds.
    fn held(&self) -> &[Value];

    /// The values [`Carry::held`] returns, to be moved out as it drops, or
    /// none when another carrier shares them and drops them in its turn.
    /// Neither has a default, so a carrier that holds values says how to
    /// move them out and its drop stays shallow.
    fn held_mut(&mut self) -> &mut [Value];

    /// Whether `other` is the same as this one, as [`Value::same`] asks.
    fn same(&self, _other: &dyn Carry) -> bool {
        false
    }
}

impl Native {
    /// Returns a handle to `inner`.
    pub fn new<T: Carry>(inner: T) -> Self {
        Native(Arc::new(inner))
    }

    /// Returns the inner value, when it is a `T`.
    pub fn downcast<T: Any>(&self) -> Option<&T> {
        let inner: &dyn Any = &*self.0;
        inner.downcast_ref()
    }

    /// The values the inner value holds.
    pub(crate) fn held(&self) -> &[Value] {
        self.0.held()
    }

    /// The values the inner value holds, when nothing else holds it.
    fn held_mut(&mut self) -> Option<&mut [Value]> {
        Arc::get_mut(&mut self.0).map(Carry::held_mut)
    }

    /// Whether the two carry one value, or what their carrier calls the
    /// same.
    fn same(&self, other: &Native) -> bool {
        Arc::ptr_eq(&self.0, &other.0) || self.0.same(&*other.0)
    }
}

impl Drop for Native {
    fn drop(&mut self) {
        if let Some(held) = self.held_mut() {
            dismantle(held.iter_mut());
        }
    }
}

impl fmt::Debug for Native {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("<native>")
    }
}

/// Which task a task handle names. What the number means is the evaluator's,
/// which makes each one with [`TaskId::next`] from [`TaskId::FIRST`].
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct TaskId(u64);

impl TaskId {
    /// The first task's id.
    pub const FIRST: TaskId = TaskId(0);

    /// The id after this one.
    ///
    /// # Panics
    ///
    /// When it is the last id a `u64` holds, which no run makes.
    #[must_use]
    pub fn next(self) -> TaskId {
        TaskId(self.0.checked_add(1).expect("fewer than 2^64 tasks"))
    }
}

/// Its number, which says which task it is and nothing more.
impl fmt::Display for TaskId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// The token a host chose for a host type value. Flow stores it, compares
/// nothing about it, and hands it back unchanged (`abi.md`).
#[derive(Clone, Debug)]
pub struct HostToken(Arc<str>);

impl HostToken {
    /// Returns the token `text` is.
    pub fn new(text: &str) -> Self {
        HostToken(Arc::from(text))
    }

    /// Returns the token's text.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// What tells this token apart from every other alive.
    fn id(&self) -> usize {
        Arc::as_ptr(&self.0).cast::<u8>().addr()
    }
}

/// Returns how `left` orders against `right`.
///
/// The order is `types.md`'s, structural and total over each data type:
/// numbers by value, text by code point and bytes by byte, `false` before
/// `true`; lists, tuples and records element by element in order, with a
/// proper prefix first; enum values by their constructors' declaration order,
/// then by payload; dictionaries as their entry lists in key order would, and
/// sets as their sorted elements would; durations and instants
/// chronologically.
///
/// The two values must be of one type. Reaching a value that is not data is
/// [`DataError::NotData`], and two values of different shapes is
/// [`DataError::Mismatch`]; a checked program reaches neither.
///
/// Two records or two enum values of different declarations are of
/// different shapes. The walk keeps the aggregates it is inside on a stack on
/// the heap, so a value nested deeper than the native stack is compared like
/// any other.
///
/// # Errors
///
/// [`DataError::NotData`] on reaching a value that is not data, and
/// [`DataError::Mismatch`] on two values of different shapes.
pub fn compare(left: &Value, right: &Value) -> Result<Ordering, DataError> {
    match zip(Rule::Data, left, right).map_err(|stopped| stopped.stop) {
        Ok(()) => Ok(Ordering::Equal),
        Err(Stop::Unequal(order)) => Ok(order),
        Err(Stop::Mismatch) => Err(DataError::Mismatch),
        Err(Stop::NotData) => Err(DataError::NotData),
    }
}

/// Returns whether `left == right`: structural equality, which holds exactly
/// when [`compare`] answers `Equal`.
///
/// # Errors
///
/// As [`compare`].
pub fn equal(left: &Value, right: &Value) -> Result<bool, DataError> {
    Ok(compare(left, right)? == Ordering::Equal)
}

/// Which rule a walk over two values compares them by.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Rule {
    /// `types.md`'s equality and order over data ([`compare`]).
    Data,
    /// Whether the two are the same ([`Value::same`]).
    Recorded,
}

/// Why a walk over two values stopped before finding them equal.
enum Stop {
    /// They differ, ordered so.
    Unequal(Ordering),
    /// They are of different shapes.
    Mismatch,
    /// One part is not data.
    NotData,
}

/// An aggregate pair a walk is inside: the two aggregates, their parts
/// still to compare, how many parts of each it has taken, and the parts of
/// `left` it took last and before that.
struct Level<'a> {
    left: &'a Value,
    right: &'a Value,
    parts: (Parts<'a>, Parts<'a>),
    taken: usize,
    current: Option<&'a Value>,
    last: Option<&'a Value>,
}

/// Where a walk over two values stopped, and why.
struct Stopped<'a> {
    stop: Stop,
    open: Vec<Level<'a>>,
    left: &'a Value,
    right: &'a Value,
}

impl<'a> Stopped<'a> {
    /// The path through the open aggregates to the parts the walk stopped at.
    fn difference(self) -> Difference<'a> {
        let mut path = Vec::new();
        for level in &self.open {
            let at = level.taken - 1;
            match level.left {
                Value::Record(record) => {
                    path.push(
                        record
                            .shape()
                            .field(at)
                            .map_or(Step::Element(at), Step::Field),
                    );
                }
                Value::Variant(variant) => {
                    let constructor = variant.constructor();
                    path.push(Step::Constructor(constructor.name()));
                    path.push(match constructor.payload() {
                        Payload::Named(fields) => Step::Field(&fields[at]),
                        Payload::None | Payload::Positional(_) => Step::Element(at),
                    });
                }
                Value::Dict(_) if at % 2 == 1 => {
                    path.push(level.last.map_or(Step::Element(at / 2), Step::Key));
                }
                Value::Dict(_) => path.push(Step::Element(at / 2)),
                Value::List(_)
                | Value::Set(_)
                | Value::Tuple(_)
                | Value::Unit
                | Value::Bool(_)
                | Value::Int(_)
                | Value::Decimal(_)
                | Value::Text(_)
                | Value::Bytes(_)
                | Value::Duration(_)
                | Value::Instant(_)
                | Value::Native(_)
                | Value::Task(_)
                | Value::Host(_) => path.push(Step::Element(at)),
            }
        }
        Difference {
            path: Path(path),
            left: self.left,
            right: self.right,
        }
    }
}

/// Walks `left` and `right` side by side under `rule`, keeping the
/// aggregates it is inside on a stack on the heap; `Ok` when they are equal
/// throughout, and otherwise where it stopped.
fn zip<'a>(rule: Rule, left: &'a Value, right: &'a Value) -> Result<(), Stopped<'a>> {
    let mut open: Vec<Level<'a>> = Vec::new();
    let (mut left, mut right) = (left, right);
    loop {
        match step(rule, left, right) {
            Ok(Some(parts)) => open.push(Level {
                left,
                right,
                parts,
                taken: 0,
                current: None,
                last: None,
            }),
            Ok(None) => {}
            Err(stop) => {
                return Err(Stopped {
                    stop,
                    open,
                    left,
                    right,
                });
            }
        }
        // The next pair of parts, closing each aggregate whose parts were all
        // equal; a proper prefix orders first.
        loop {
            let Some(level) = open.last_mut() else {
                return Ok(());
            };
            let (a, b) = (level.parts.0.next(), level.parts.1.next());
            let order = match (a, b) {
                (Some(a), Some(b)) => {
                    level.taken += 1;
                    level.last = level.current.replace(a);
                    (left, right) = (a, b);
                    break;
                }
                (Some(_), None) => Ordering::Greater,
                (None, Some(_)) => Ordering::Less,
                (None, None) => {
                    open.pop();
                    continue;
                }
            };
            let whole = open.pop().expect("the level just read");
            return Err(Stopped {
                stop: Stop::Unequal(order),
                open,
                left: whole.left,
                right: whole.right,
            });
        }
    }
}

/// Compares two values at their own level under `rule`: `None` when they
/// are equal whatever their parts, or the two sequences of parts to compare
/// element by element.
///
/// A record or an enum value of one declaration is never equal to one of
/// another: their shapes are compared before their parts, which is the
/// guard [`compare`] documents for values no checked program makes.
fn step<'a>(
    rule: Rule,
    left: &'a Value,
    right: &'a Value,
) -> Result<Option<(Parts<'a>, Parts<'a>)>, Stop> {
    if rule == Rule::Recorded
        && let (Some(a), Some(b)) = (left.identity(), right.identity())
        && a == b
    {
        return Ok(None);
    }
    let order = match (left, right) {
        (Value::Unit, Value::Unit) => Ordering::Equal,
        (Value::Bool(a), Value::Bool(b)) => a.cmp(b),
        (Value::Int(a), Value::Int(b)) => a.cmp(b),
        (Value::Decimal(a), Value::Decimal(b)) => a.cmp(b),
        (Value::Text(a), Value::Text(b)) => a.cmp(b),
        (Value::Bytes(a), Value::Bytes(b)) => a.cmp(b),
        (Value::Duration(a), Value::Duration(b)) => a.cmp(b),
        (Value::Instant(a), Value::Instant(b)) => a.cmp(b),
        (Value::Record(a), Value::Record(b)) if !same_shape(a.shape(), b.shape()) => {
            return Err(Stop::Mismatch);
        }
        (Value::Variant(a), Value::Variant(b)) if !same_shape(a.shape(), b.shape()) => {
            return Err(Stop::Mismatch);
        }
        (Value::Variant(a), Value::Variant(b)) if a.index() != b.index() => {
            a.index().cmp(&b.index())
        }
        (Value::List(_), Value::List(_))
        | (Value::Dict(_), Value::Dict(_))
        | (Value::Set(_), Value::Set(_))
        | (Value::Tuple(_), Value::Tuple(_))
        | (Value::Record(_), Value::Record(_))
        | (Value::Variant(_), Value::Variant(_)) => {
            return Ok(Some((left.parts(), right.parts())));
        }
        (Value::Host(a), Value::Host(b)) if rule == Rule::Recorded => a.as_str().cmp(b.as_str()),
        (Value::Task(a), Value::Task(b)) if rule == Rule::Recorded => a.0.cmp(&b.0),
        (Value::Native(a), Value::Native(b)) if rule == Rule::Recorded => {
            if a.same(b) {
                Ordering::Equal
            } else {
                return Err(Stop::Mismatch);
            }
        }
        (Value::Native(_) | Value::Task(_) | Value::Host(_), _)
        | (_, Value::Native(_) | Value::Task(_) | Value::Host(_)) => return Err(Stop::NotData),
        _ => return Err(Stop::Mismatch),
    };
    match order {
        Ordering::Equal => Ok(None),
        unequal => Err(Stop::Unequal(unequal)),
    }
}

/// Whether two declarations' shapes are one: the same description, or two
/// equal ones.
fn same_shape<T: PartialEq>(left: &Arc<T>, right: &Arc<T>) -> bool {
    Arc::ptr_eq(left, right) || left == right
}