flow-lang-value 0.1.0

The Flow runtime value model: data values, their equality, order and text, and the operations std's built-in types declare.
Documentation
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
//! 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};

/// 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 `@tool 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))
    }
}

impl Value {
    /// How deeply the value nests, or more: a scalar is 0 deep and an
    /// aggregate one deeper than its deepest part, so `[[1]]` is 2 deep.
    ///
    /// It costs constant time, since every aggregate records it when it is
    /// made. It is exact but for a list, a dictionary or a set that kept the
    /// measure of a larger one it was cut from — a part of a list, or a
    /// dictionary an entry was removed from — which may report more than it
    /// holds; [`Value::deeper_than`] is exact.
    pub fn depth_bound(&self) -> usize {
        self.meta().depth()
    }

    /// Whether some part of the value may be a task handle or a [`Native`]
    /// value, which may itself hold one; `false` means no part is either.
    ///
    /// It costs constant time, and like [`Value::depth_bound`] may answer
    /// `true` for a list, dictionary or set that kept the measure of a
    /// larger one.
    pub fn may_hold_tasks(&self) -> bool {
        self.meta().holds()
    }

    /// Whether the value nests more than `bound` levels deep.
    ///
    /// The answer is exact. It costs constant time when the measure each
    /// aggregate records settles it, and otherwise walks only the parts
    /// whose measures do not: those of a part cut from a deeper list. The
    /// walk is iterative, so a value nested deeper than the native stack is
    /// measured too.
    pub fn deeper_than(&self, bound: usize) -> bool {
        let mut pending: Vec<(&Value, usize)> = vec![(self, bound)];
        while let Some((value, room)) = pending.pop() {
            if value.depth_bound() <= room {
                continue;
            }
            // Only an aggregate measures more than 0, so it is too deep
            // here when no room is left for its parts.
            let Some(room) = room.checked_sub(1) else {
                return true;
            };
            let at = |part| (part, room);
            match value {
                Value::List(items) => pending.extend(items.iter().map(at)),
                Value::Set(items) => pending.extend(items.iter().map(at)),
                Value::Tuple(tuple) => pending.extend(tuple.parts().iter().map(at)),
                Value::Record(record) => pending.extend(record.fields().iter().map(at)),
                Value::Variant(variant) => pending.extend(variant.payload().iter().map(at)),
                Value::Dict(entries) => {
                    pending.extend(entries.iter().flat_map(|(key, item)| [at(key), at(item)]));
                }
                _ => unreachable!("only an aggregate measures more than 0"),
            }
        }
        false
    }

    /// 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 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(crate) 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);

    /// An aggregate with no parts: 1 deep.
    pub(crate) const EMPTY: Meta = Meta(1);

    /// 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 of an aggregate holding the parts both `self` and
    /// `other` measure.
    #[must_use]
    pub(crate) 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))
    }

    /// 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 {
        (self.0 & Meta::DEPTH) as usize
    }

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

/// 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
    }
}

impl Drop for Tuple {
    fn drop(&mut self) {
        if let Some(parts) = Arc::get_mut(&mut self.parts) {
            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<Nested> = Vec::new();
    move_nested(parts, &mut pending);
    while let Some(mut nested) = pending.pop() {
        match &mut nested {
            Nested::List(items) => {
                if let Some(buffer) = items.buffer_mut() {
                    move_nested(buffer.iter_mut(), &mut pending);
                }
            }
            Nested::Dict(entries) => {
                if let Some(entries) = entries.entries_mut() {
                    let parts = entries.iter_mut().flat_map(|(key, item)| [key, item]);
                    move_nested(parts, &mut pending);
                }
            }
            Nested::Set(items) => move_unshared(items.items_mut(), &mut pending),
            Nested::Tuple(tuple) => move_unshared(Arc::get_mut(&mut tuple.parts), &mut pending),
            Nested::Record(record) => move_unshared(record.fields_mut(), &mut pending),
            Nested::Variant(variant) => move_unshared(variant.payload_mut(), &mut pending),
            Nested::Native(native) => move_unshared(native.held_mut(), &mut pending),
        }
        // `nested` drops here, holding no part with parts of its own.
    }
}

/// A value that has parts of its own, moved out of the aggregate that held
/// it to be dropped by `dismantle`.
enum Nested {
    List(List),
    Dict(Dict),
    Set(Set),
    Tuple(Tuple),
    Record(Record),
    Variant(Variant),
    Native(Native),
}

/// Moves `parts`, when nothing else holds them, as [`move_nested`] does.
fn move_unshared(parts: Option<&mut [Value]>, pending: &mut Vec<Nested>) {
    if let Some(parts) = parts {
        move_nested(parts.iter_mut(), pending);
    }
}

/// Moves each of `parts` that has parts of its own onto `pending`, leaving
/// `()` in its place, and leaves every other part where it is.
fn move_nested<'a>(parts: impl Iterator<Item = &'a mut Value>, pending: &mut Vec<Nested>) {
    for part in parts {
        let nested = match std::mem::replace(part, Value::Unit) {
            Value::List(items) => Nested::List(items),
            Value::Dict(entries) => Nested::Dict(entries),
            Value::Set(items) => Nested::Set(items),
            Value::Tuple(tuple) => Nested::Tuple(tuple),
            Value::Record(record) => Nested::Record(record),
            Value::Variant(variant) => Nested::Variant(variant),
            Value::Native(native) => Nested::Native(native),
            other => {
                *part = other;
                continue;
            }
        };
        pending.push(nested);
    }
}

/// 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 held as `dyn Any` and recovered by the
/// evaluator with [`Native::downcast`]. Nothing here compares, orders or
/// prints one.
///
/// One that holds values of its own, such as a closure holding what it
/// captured, is made with [`Native::holding`], so that dropping it hands those
/// values 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<Carried<dyn Any + Send + Sync>>);

/// A value that a [`Native`] carries and that holds values of its own.
pub trait Holding: Any + Send + Sync {
    /// The values it holds, when nothing else holds them with it.
    fn held_mut(&mut self) -> Option<&mut [Value]>;
}

/// What a [`Native`] carries: the evaluator's value, and how to reach the
/// values it holds, if it holds any.
struct Carried<T: ?Sized> {
    held: Option<Held>,
    inner: T,
}

/// Reaches the values a carried value holds.
type Held = fn(&mut (dyn Any + Send + Sync)) -> Option<&mut [Value]>;

/// The values `inner`, a `T`, holds.
fn held_by<T: Holding>(inner: &mut (dyn Any + Send + Sync)) -> Option<&mut [Value]> {
    inner.downcast_mut::<T>().and_then(T::held_mut)
}

impl Native {
    /// Returns a handle to `inner`, which holds no values.
    pub fn new<T: Any + Send + Sync>(inner: T) -> Self {
        Native(Arc::new(Carried { held: None, inner }))
    }

    /// Returns a handle to `inner`, which holds values.
    pub fn holding<T: Holding>(inner: T) -> Self {
        Native(Arc::new(Carried {
            held: Some(held_by::<T>),
            inner,
        }))
    }

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

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

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.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct TaskId(pub u64);

/// The token a host chose for a `@tool 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
    }
}

/// 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.
///
/// 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.
pub fn compare(left: &Value, right: &Value) -> Result<Ordering, DataError> {
    let mut open: Vec<(Parts<'_>, Parts<'_>)> = Vec::new();
    let (mut left, mut right) = (left, right);
    loop {
        match step(left, right)? {
            Step::Decided(Ordering::Equal) => {}
            Step::Decided(unequal) => return Ok(unequal),
            Step::Within(a, b) => open.push((a, b)),
        }
        // The next pair of parts, closing each aggregate whose parts were all
        // equal; a proper prefix orders first.
        loop {
            let Some((a, b)) = open.last_mut() else {
                return Ok(Ordering::Equal);
            };
            match (a.next(), b.next()) {
                (Some(a), Some(b)) => {
                    (left, right) = (a, b);
                    break;
                }
                (Some(_), None) => return Ok(Ordering::Greater),
                (None, Some(_)) => return Ok(Ordering::Less),
                (None, None) => {
                    open.pop();
                }
            }
        }
    }
}

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

/// What comparing two values comes to at their own level.
enum Step<'a> {
    /// Their order, whatever their parts.
    Decided(Ordering),
    /// The order of these two sequences of parts, element by element.
    Within(Parts<'a>, Parts<'a>),
}

fn step<'a>(left: &'a Value, right: &'a Value) -> Result<Step<'a>, DataError> {
    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::Variant(a), Value::Variant(b)) if a.index() != b.index() => {
            a.index().cmp(&b.index())
        }
        (Value::List(a), Value::List(b)) => {
            return Ok(Step::Within(
                Parts::List(a.elements()),
                Parts::List(b.elements()),
            ));
        }
        (Value::Set(a), Value::Set(b)) => return Ok(within(a.as_slice(), b.as_slice())),
        (Value::Tuple(a), Value::Tuple(b)) => return Ok(within(a.parts(), b.parts())),
        (Value::Record(a), Value::Record(b)) => return Ok(within(a.fields(), b.fields())),
        (Value::Variant(a), Value::Variant(b)) => return Ok(within(a.payload(), b.payload())),
        // Entry lists compared pair by pair are the flattened key, value,
        // key, value sequences compared element by element: each pair has
        // exactly two parts, so the first difference and the shorter list
        // fall at the same place in both.
        (Value::Dict(a), Value::Dict(b)) => {
            let (a, b) = (a.entries().iter(), b.entries().iter());
            return Ok(Step::Within(Parts::Dict(a, None), Parts::Dict(b, None)));
        }
        (Value::Native(_) | Value::Task(_) | Value::Host(_), _)
        | (_, Value::Native(_) | Value::Task(_) | Value::Host(_)) => {
            return Err(DataError::NotData);
        }
        _ => return Err(DataError::Mismatch),
    };
    Ok(Step::Decided(order))
}

/// Two slices of parts to compare element by element.
fn within<'a>(left: &'a [Value], right: &'a [Value]) -> Step<'a> {
    Step::Within(Parts::Slice(left.iter()), Parts::Slice(right.iter()))
}

/// The parts of an aggregate, in the order equality and order read them: a
/// dictionary's as key, value, key, value in key order.
enum Parts<'a> {
    /// A slice of parts.
    Slice(std::slice::Iter<'a, Value>),
    /// A list's elements.
    List(std::collections::vec_deque::Iter<'a, Value>),
    /// A dictionary's entries, and the value of the last key read while it
    /// is still to come.
    Dict(std::slice::Iter<'a, (Value, Value)>, Option<&'a Value>),
}

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

    fn next(&mut self) -> Option<&'a Value> {
        match self {
            Parts::Slice(parts) => parts.next(),
            Parts::List(items) => items.next(),
            Parts::Dict(entries, value) => value.take().or_else(|| {
                let (key, next) = entries.next()?;
                *value = Some(next);
                Some(key)
            }),
        }
    }
}