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
//! Equality, order, text and dropping hold for a value of any depth: none of
//! them is bounded by the native stack (`data.md`; `execution.md`, *Limits*,
//! lets a host allow nesting far beyond the minimum).

mod common;

use std::cmp::Ordering;

use common::*;
use flow_testing::on_a_small_stack;
use flow_value::{Carry, Dict, Set, Value};

/// Deep enough that a walk recursing once per level overflows the small
/// stack these tests run on.
const DEPTH: usize = 100_000;

/// `value` inside one aggregate of the kind `kind` names: a list, an enum
/// value, a record, a tuple, a dictionary or a set.
fn wrap(kind: usize, value: Value) -> Value {
    match kind {
        0 => Value::list([value]),
        1 => some(value),
        2 => record("Box", &[("inner", value)]),
        3 => Value::tuple([Value::Unit, value]),
        4 => Value::Dict(Dict::from_entries([(Value::int(0), value)]).expect("an int key is data")),
        _ => Value::Set(Set::from_items([value]).expect("one element needs no comparison")),
    }
}

/// A value `DEPTH` levels deep around `leaf`, going through every kind of
/// aggregate in turn.
fn deep(leaf: i64) -> Value {
    let mut value = Value::int(leaf);
    for level in 0..DEPTH {
        value = wrap(level % 6, value);
    }
    value
}

#[test]
fn a_value_deeper_than_the_native_stack_compares_equal_to_its_copy() {
    on_a_small_stack(|| {
        assert!(same(&deep(1), &deep(1)));
    });
}

#[test]
fn a_value_deeper_than_the_native_stack_orders_by_its_innermost_difference() {
    on_a_small_stack(|| {
        assert_eq!(order(&deep(1), &deep(2)), Ordering::Less);
        assert_eq!(order(&deep(2), &deep(1)), Ordering::Greater);
    });
}

#[test]
fn a_value_deeper_than_the_native_stack_has_a_text_form() {
    on_a_small_stack(|| {
        let mut nested = Value::int(7);
        for _ in 0..DEPTH {
            nested = Value::list([nested]);
        }
        let text = flow_value::text_form(&nested).unwrap();
        assert_eq!(text.len(), 2 * DEPTH + 1);
        assert_eq!(text, format!("{}7{}", "[".repeat(DEPTH), "]".repeat(DEPTH)));
        assert!(
            flow_value::text_form(&deep(3))
                .unwrap()
                .contains("Box { inner: ")
        );
    });
}

#[test]
fn a_value_deeper_than_the_native_stack_drops_whatever_kind_it_is() {
    on_a_small_stack(|| drop(deep(1)));
    for kind in 0..6 {
        on_a_small_stack(move || {
            let mut value = Value::int(0);
            for _ in 0..DEPTH {
                value = wrap(kind, value);
            }
            drop(value);
        });
    }
}

#[test]
fn a_value_deeper_than_the_native_stack_is_the_same_as_its_copy() {
    on_a_small_stack(|| {
        assert!(deep(1).same(&deep(1)));
        assert!(!deep(1).same(&deep(2)));
    });
}

#[test]
fn dropping_a_deep_value_leaves_the_parts_another_value_holds() {
    on_a_small_stack(|| {
        let inner = deep(5);
        let outer = Value::list([inner.clone(), Value::tuple([inner.clone(), Value::Unit])]);
        drop(outer);
        assert!(same(&inner, &deep(5)));
        // A list keeps its whole tree when a part of it is held.
        let items: flow_value::List = [deep(1), deep(2)].into_iter().collect();
        let first = items.slice(0, 1).unwrap();
        drop(items);
        assert!(same(&Value::List(first), &Value::list([deep(1)])));
    });
}

/// A stand-in for the evaluator's closure: a value that holds the values it
/// captured.
struct Captures(Box<[Value]>);

impl Carry for Captures {
    fn held(&self) -> &[Value] {
        &self.0
    }

    fn held_mut(&mut self) -> &mut [Value] {
        &mut self.0
    }
}

/// A closure capturing `value`.
fn capturing(value: Value) -> Value {
    Value::Native(flow_value::Native::new(Captures(
        [Value::Unit, value].into_iter().collect(),
    )))
}

#[test]
fn a_chain_of_closures_each_capturing_the_last_drops_whatever_its_length() {
    on_a_small_stack(|| {
        let mut chain = Value::int(0);
        for level in 0..DEPTH {
            // Through an aggregate now and then, and straight on otherwise.
            chain = if level % 3 == 0 {
                Value::list([capturing(chain)])
            } else {
                capturing(chain)
            };
        }
        drop(chain);
    });
    on_a_small_stack(|| {
        let mut chain = Value::int(0);
        for _ in 0..DEPTH {
            chain = capturing(chain);
        }
        drop(chain);
    });
}

#[test]
fn dropping_a_closure_leaves_what_another_value_still_holds() {
    on_a_small_stack(|| {
        let inner = deep(4);
        let closure = capturing(inner.clone());
        let copy = closure.clone();
        drop(closure);
        drop(capturing(Value::list([inner.clone()])));
        assert!(same(&inner, &deep(4)));
        let Value::Native(native) = &copy else {
            unreachable!("a closure is a native value")
        };
        let captures = native.downcast::<Captures>().expect("the closure");
        assert!(same(&captures.0[1], &deep(4)), "a copy keeps its captures");
    });
}

// === What a value records of its parts ======================================

/// `value` inside `levels` lists.
fn listed(levels: usize, value: Value) -> Value {
    (0..levels).fold(value, |inner, _| Value::list([inner]))
}

#[test]
fn a_scalar_is_no_levels_deep_and_holds_no_task() {
    for scalar in [
        Value::Unit,
        Value::int(1),
        Value::text("a"),
        Value::Bool(true),
    ] {
        assert_eq!(scalar.depth_bound(), 0);
        assert!(!scalar.may_hold_tasks());
        assert!(!scalar.deeper_than(0));
    }
}

#[test]
fn an_empty_aggregate_is_one_level_deep() {
    for empty in [
        Value::list([]),
        Value::Dict(Dict::default()),
        Value::Set(Set::default()),
        Value::List(flow_value::List::default()),
    ] {
        assert_eq!(empty.depth_bound(), 1);
        assert!(empty.deeper_than(0));
        assert!(!empty.deeper_than(1));
    }
}

#[test]
fn every_kind_of_aggregate_is_one_level_deeper_than_its_deepest_part() {
    for kind in 0..6 {
        let value = wrap(kind, listed(2, Value::int(1)));
        assert_eq!(value.depth_bound(), 3, "kind {kind}");
        assert!(value.deeper_than(2), "kind {kind}");
        assert!(!value.deeper_than(3), "kind {kind}");
    }
    let mixed = Value::tuple([Value::int(1), listed(4, Value::Unit)]);
    assert_eq!(mixed.depth_bound(), 5);
}

#[test]
fn a_value_says_it_may_hold_a_task_when_a_part_is_a_task_or_a_native_value() {
    let task = Value::Task(flow_value::TaskId::FIRST);
    let native = Value::Native(flow_value::Native::new(Captures(Box::new([]))));
    for handle in [task, native] {
        assert!(handle.may_hold_tasks());
        assert_eq!(handle.depth_bound(), 0);
        for kind in 0..4 {
            assert!(wrap(kind, listed(3, handle.clone())).may_hold_tasks());
        }
        let beside = Value::tuple([Value::int(1), listed(2, handle.clone())]);
        assert!(beside.may_hold_tasks());
        let both = Value::tuple([handle.clone(), listed(1, handle.clone())]);
        assert!(both.may_hold_tasks());
        assert_eq!(both.depth_bound(), 2);
    }
    assert!(!wrap(2, listed(3, Value::text("data"))).may_hold_tasks());
}

#[test]
fn growing_or_joining_a_list_measures_what_it_adds() {
    let list: flow_value::List = [Value::int(1)].into_iter().collect();
    let grown = list.clone().push_back(listed(3, Value::Unit));
    assert_eq!(Value::List(grown.clone()).depth_bound(), 4);
    let front = list
        .clone()
        .push_front(Value::Task(flow_value::TaskId::FIRST));
    assert!(Value::List(front.clone()).may_hold_tasks());
    assert_eq!(Value::List(front.clone()).depth_bound(), 1);
    let joined = Value::List(front.concat(grown));
    assert_eq!(joined.depth_bound(), 4);
    assert!(joined.may_hold_tasks());
    // Joined onto the right list as well as the left.
    let right = list.concat([listed(2, Value::Unit), Value::Unit].into_iter().collect());
    assert_eq!(Value::List(right).depth_bound(), 3);
}

#[test]
fn a_part_of_a_list_is_measured_exactly() {
    let items: flow_value::List = [listed(5, Value::int(0)), Value::int(1), Value::int(2)]
        .into_iter()
        .collect();
    let rest = Value::List(items.slice(1, 3).unwrap());
    assert_eq!(rest.depth_bound(), 1, "what the part holds");
    assert!(!rest.deeper_than(1));
    assert!(rest.deeper_than(0));
    // A part of a list inside another aggregate is measured exactly too.
    let outer = Value::tuple([rest, Value::Unit]);
    assert!(!outer.deeper_than(2));
    assert!(outer.deeper_than(1));
    let deeper: flow_value::List = [listed(3, Value::Unit), listed(5, Value::Unit)]
        .into_iter()
        .collect();
    let first = Value::List(deeper.slice(0, 1).unwrap());
    assert_eq!(first.depth_bound(), 4);
    assert!(!first.deeper_than(4));
    assert!(first.deeper_than(3));
    // A part cut from inside the tree, past the list's front.
    let long: flow_value::List = std::iter::repeat_n(Value::int(0), 40)
        .chain([listed(5, Value::Unit)])
        .collect();
    assert_eq!(Value::List(long.slice(0, 1).unwrap()).depth_bound(), 1);
    assert_eq!(Value::List(long.slice(20, 30).unwrap()).depth_bound(), 1);
    assert_eq!(Value::List(long.slice(20, 41).unwrap()).depth_bound(), 6);
}

#[test]
fn a_dictionary_measures_its_keys_and_values_as_it_changes() {
    let dict = Dict::from_entries([(listed(1, Value::Unit), Value::Unit)]).unwrap();
    assert_eq!(Value::Dict(dict.clone()).depth_bound(), 2);
    let grown = dict
        .insert(Value::list([]), listed(2, Value::Unit))
        .unwrap();
    assert_eq!(Value::Dict(grown.clone()).depth_bound(), 3);
    let key = listed(1, listed(0, Value::Unit));
    let valued = grown.insert(key.clone(), listed(3, Value::Unit)).unwrap();
    assert_eq!(Value::Dict(valued.clone()).depth_bound(), 4);
    let shrunk = Value::Dict(valued.remove(&key).unwrap());
    assert_eq!(shrunk.depth_bound(), 3, "measured exactly once shrunk");
    assert!(!shrunk.deeper_than(3));
    assert!(shrunk.deeper_than(2));
    let set = Value::Set(Set::from_items([listed(1, Value::Unit)]).unwrap());
    assert_eq!(set.depth_bound(), 2);
    assert!(set.deeper_than(1));
}

#[test]
fn a_value_deeper_than_the_native_stack_is_measured_exactly() {
    on_a_small_stack(|| {
        let value = deep(1);
        assert_eq!(value.depth_bound(), DEPTH);
        assert!(value.deeper_than(DEPTH - 1));
        assert!(!value.deeper_than(DEPTH));
        let items: flow_value::List = [deep(1), Value::int(0)].into_iter().collect();
        let part = Value::List(items.slice(1, 2).unwrap());
        assert_eq!(part.depth_bound(), 1);
        assert!(!part.deeper_than(1));
    });
}