Thing 2.0 cut 4: bind (the Binder binds resolved trees to provider state by name) #13

Merged
eureka merged 7 commits from hands/thing2-bind into main 2026-11-28 03:15:14 +00:00
8 changed files with 1728 additions and 0 deletions
Showing only changes of commit 5e5f67978c - Show all commits

Thing 2.0 cut 4: bind (Binder, BoundTree, keyed Repeat instances, Format) with text goldens

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Meta Vens 2026-11-28 03:19:30 +01:00

View file

@ -0,0 +1,172 @@
//! Format: total and locale-free. Each function takes the value the site read and returns the
//! text, or the reason the value does not fit (a detail that never carries the value).
use thing_contract::{AffixFormat, NumberFormat, is_stored_at_stamp};
/// Fixed-point text of `n` at `format.precision`, scaled by 100 for a percent, with the percent
/// sign and the unit. Non-finite numbers print as NaN, inf, -inf; negative zero prints as zero.
pub fn number(n: f64, format: &NumberFormat) -> String {
let scaled = if format.percent { n * 100.0 } else { n };
let mut text = if scaled.is_nan() {
"NaN".to_string()
} else if scaled.is_infinite() {
if scaled > 0.0 { "inf" } else { "-inf" }.to_string()
} else {
format!("{scaled:.*}", format.precision.get() as usize)
};
if text.starts_with('-') && text[1..].bytes().all(|byte| byte == b'0' || byte == b'.') {
text.remove(0);
}
if format.percent {
text.push('%');
}
if let Some(unit) = &format.unit {
text.push(' ');
text.push_str(unit);
}
text
}
/// Seconds rounded half away from zero, printed by the largest unit present with the later
/// units at two digits: `5s`, `1m 05s`, `1h 00m 05s`, `1d 01h 00m 00s`, a leading `-` when negative.
pub fn duration(seconds: f64) -> Result<String, &'static str> {
if !seconds.is_finite() {
return Err("a duration is not finite");
}
let total = seconds.round() as i128;
let t = total.unsigned_abs();
let (days, hours, minutes, secs) = (t / 86_400, t % 86_400 / 3_600, t % 3_600 / 60, t % 60);
let body = if days > 0 {
format!("{days}d {hours:02}h {minutes:02}m {secs:02}s")
} else if hours > 0 {
format!("{hours}h {minutes:02}m {secs:02}s")
} else if minutes > 0 {
format!("{minutes}m {secs:02}s")
} else {
format!("{secs}s")
};
Ok(if total < 0 { format!("-{body}") } else { body })
}
const FIRST_SECOND: i128 = -62_135_596_800; // 0001-01-01T00:00:00Z
const LAST_SECOND: i128 = 253_402_300_799; // 9999-12-31T23:59:59Z
/// Unix seconds, floored, as `YYYY-MM-DDTHH:MM:SSZ` in UTC, years 0001 to 9999.
pub fn timestamp(seconds: f64) -> Result<String, &'static str> {
if !seconds.is_finite() {
return Err("a timestamp is not finite");
}
let floored = seconds.floor() as i128;
if !(FIRST_SECOND..=LAST_SECOND).contains(&floored) {
return Err("a timestamp is outside years 0001 to 9999");
}
let (days, rest) = (floored.div_euclid(86_400), floored.rem_euclid(86_400));
let (year, month, day) = civil(days as i64);
Ok(format!("{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", rest / 3_600, rest % 3_600 / 60, rest % 60))
}
/// Days since 1970-01-01 as a proleptic Gregorian date.
fn civil(days: i64) -> (i64, i64, i64) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let day_of_era = z.rem_euclid(146_097);
let year_of_era = (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_index = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * month_index + 2) / 5 + 1;
let month = if month_index < 10 { month_index + 3 } else { month_index - 9 };
(year_of_era + era * 400 + i64::from(month <= 2), month, day)
}
/// Text that is already a `stored_at` stamp, as written.
pub fn stamp(text: &str) -> Result<String, &'static str> {
if is_stored_at_stamp(text) { Ok(text.to_string()) } else { Err("the text is not a timestamp") }
}
pub fn affix(text: &str, format: &AffixFormat) -> String {
format!("{}{text}{}", format.prefix, format.suffix)
}
#[cfg(test)]
mod tests {
use thing_contract::Count;
use super::*;
fn fmt(precision: i32, percent: bool, unit: Option<&str>) -> NumberFormat {
NumberFormat { precision: Count::new(precision).unwrap(), percent, unit: unit.map(Into::into) }
}
#[test]
fn number_table() {
let table = [
(0.42, fmt(1, true, None), "42.0%"),
(3.14159, fmt(2, false, None), "3.14"),
(2.5, fmt(0, false, None), "2"),
(1234.5, fmt(1, false, Some("MB")), "1234.5 MB"),
(0.5, fmt(0, true, Some("of cap")), "50% of cap"),
(-0.0, fmt(1, false, None), "0.0"),
(-0.04, fmt(1, false, None), "0.0"),
(-1.25, fmt(1, false, None), "-1.2"),
(f64::NAN, fmt(2, true, None), "NaN%"),
(f64::INFINITY, fmt(2, false, Some("x")), "inf x"),
(f64::NEG_INFINITY, fmt(0, false, None), "-inf"),
];
for (n, format, expected) in table {
assert_eq!(number(n, &format), expected, "{n} {format:?}");
}
}
#[test]
fn duration_table() {
let table = [
(0.0, "0s"),
(5.0, "5s"),
(59.4, "59s"),
(59.5, "1m 00s"),
(65.0, "1m 05s"),
(3605.0, "1h 00m 05s"),
(90_000.0, "1d 01h 00m 00s"),
(-65.0, "-1m 05s"),
(-0.4, "0s"),
(-0.5, "-1s"),
];
for (seconds, expected) in table {
assert_eq!(duration(seconds).unwrap(), expected, "{seconds}");
}
assert!(duration(f64::NAN).is_err() && duration(f64::INFINITY).is_err());
}
#[test]
fn timestamp_table() {
let table = [
(0.0, "1970-01-01T00:00:00Z"),
(0.9, "1970-01-01T00:00:00Z"),
(-0.1, "1969-12-31T23:59:59Z"),
(951_782_400.0, "2000-02-29T00:00:00Z"),
(1_767_225_600.0, "2026-01-01T00:00:00Z"),
(-62_135_596_800.0, "0001-01-01T00:00:00Z"),
(253_402_300_799.0, "9999-12-31T23:59:59Z"),
];
for (seconds, expected) in table {
assert_eq!(timestamp(seconds).unwrap(), expected, "{seconds}");
}
assert!(timestamp(253_402_300_800.0).is_err());
assert!(timestamp(-62_135_596_801.0).is_err());
assert!(timestamp(f64::NAN).is_err());
}
#[test]
fn stamp_text_is_printed_as_written() {
assert_eq!(stamp("2026-01-01T00:00:00Z").unwrap(), "2026-01-01T00:00:00Z");
assert_eq!(stamp("2026-01-01T02:00:00.5+02:00").unwrap(), "2026-01-01T02:00:00.5+02:00");
assert!(stamp("yesterday").is_err());
assert!(stamp("2026-01-01 00:00:00Z").is_err());
}
#[test]
fn affix_wraps_text() {
let format = AffixFormat { prefix: "[".into(), suffix: "]".into() };
assert_eq!(affix("ok", &format), "[ok]");
}
}

View file

@ -0,0 +1,342 @@
//! Bind: a `ResolvedTree` and provider state become a `BoundTree`, the value of every source
//! site of every node, the instances of every Repeat and the typed faults between. The Binder is
//! handed trees and the changes the frame owner drained; it never drains, never decodes and keeps
//! no state value beside the port: a changed address is read again. The state interests it holds
//! are exactly the ones the bound trees read, held through the shared `Ledger`.
//!
//! A bound tree is a side table over the resolved document, not a second node tree.
mod format;
mod repeat;
mod walk;
use std::collections::{BTreeMap, HashMap, HashSet};
use thing_contract::{NodeId, SelectOption};
use crate::diagnostic::{Code, Diagnostic};
use crate::port::{Address, Change, Interest, Ledger, StatePort};
use crate::resolve::{Limits, ResolvedTree};
use walk::{Unit, Walker};
/// Every source site a node can carry. Closed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Field {
Visible,
A11yLabel,
Content,
Alt,
Enabled,
Checked,
Value,
Placeholder,
Initial,
Selected,
Options,
Series,
}
impl Field {
pub fn name(self) -> &'static str {
match self {
Field::Visible => "visible",
Field::A11yLabel => "a11y_label",
Field::Content => "content",
Field::Alt => "alt",
Field::Enabled => "enabled",
Field::Checked => "checked",
Field::Value => "value",
Field::Placeholder => "placeholder",
Field::Initial => "initial",
Field::Selected => "selected",
Field::Options => "options",
Field::Series => "series",
}
}
}
/// Why a site or a Repeat has no value. `detail` names the fault and never carries a state value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BindError {
pub code: Code,
pub detail: String,
}
/// What one site shows. A value is never coerced into another site type.
#[derive(Clone, Debug, PartialEq)]
pub enum Bound {
Text(String),
Number(f64),
Bool(bool),
Series(Vec<f64>),
Options(Vec<SelectOption>),
/// The record or the member is not there (or is nil).
Absent,
Error(BindError),
}
/// One instance of a Repeat's template: its key, and the template with derived ids, whose sites
/// are in the same table. A refused item's key is `!` and its record key.
#[derive(Clone, Debug, PartialEq)]
pub struct Instance {
pub key: String,
pub root: thing_contract::Node,
}
/// The values of one resolved document.
#[derive(Clone, Debug, PartialEq)]
pub struct BoundTree {
tree: ResolvedTree,
values: HashMap<(NodeId, Field), Bound>,
instances: HashMap<NodeId, Vec<Instance>>,
repeat_errors: HashMap<NodeId, BindError>,
}
impl BoundTree {
pub fn resolved(&self) -> &ResolvedTree {
&self.tree
}
pub fn value(&self, node: &NodeId, field: Field) -> Option<&Bound> {
self.values.get(&(node.clone(), field))
}
/// The instances of a Repeat, in collection order; none when the Repeat is in error.
pub fn instances(&self, repeat: &NodeId) -> &[Instance] {
self.instances.get(repeat).map_or(&[], Vec::as_slice)
}
/// Why a Repeat has no instances, when it is in error.
pub fn repeat_error(&self, repeat: &NodeId) -> Option<&BindError> {
self.repeat_errors.get(repeat)
}
/// Every bound site, instances' included, sorted by node id and field.
pub fn sites(&self) -> Vec<(&NodeId, Field, &Bound)> {
let mut sites: Vec<_> = self.values.iter().map(|((node, field), bound)| (node, *field, bound)).collect();
sites.sort_by(|a, b| (a.0.as_str(), a.1).cmp(&(b.0.as_str(), b.1)));
sites
}
}
/// What one bind or apply changed: per surface key, the node ids whose value changed (appeared,
/// vanished or differed) or whose Repeat instance set changed; and the diagnostics of sites that
/// entered an error or changed error code.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Applied {
pub dirty: BTreeMap<String, Vec<NodeId>>,
pub diagnostics: Vec<Diagnostic>,
}
/// What a surface's unit read and owns, so a unit can be replaced alone.
struct Owned {
values: Vec<(NodeId, Field)>,
repeats: Vec<NodeId>,
ids: Vec<NodeId>,
nodes: usize,
interests: HashSet<Interest>,
}
struct Surface {
key: String,
bound: BoundTree,
tree_ids: HashSet<NodeId>,
parts: HashMap<Unit, Owned>,
}
pub struct Binder {
limits: Limits,
surfaces: HashMap<String, Surface>,
}
fn tree_ids(tree: &ResolvedTree) -> HashSet<NodeId> {
fn visit(node: &thing_contract::Node, out: &mut HashSet<NodeId>) {
crate::resolve::grow(|| {
out.extend(walk::common(node).map(|common| common.id.clone()));
if let thing_contract::Node::Repeat(repeat) = node {
visit(&repeat.template, out);
}
walk::children(node).iter().for_each(|child| visit(child, out));
})
}
let mut ids = HashSet::new();
visit(&tree.document().root, &mut ids);
ids
}
impl Surface {
fn interests(&self) -> HashSet<Interest> {
self.parts.values().flat_map(|owned| owned.interests.iter().cloned()).collect()
}
/// Bind the units `only` selects (all when `None`), replace what they owned, and report what
/// changed against what they held.
fn run(
&mut self,
limits: &Limits,
port: &mut dyn StatePort,
ledger: &mut Ledger,
only: Option<&HashSet<Unit>>,
) -> (Vec<NodeId>, Vec<Diagnostic>) {
let before = self.interests();
let mut old_values: HashMap<(NodeId, Field), Bound> = HashMap::new();
let mut old_keys: HashMap<NodeId, Vec<String>> = HashMap::new();
let mut old_errors: HashMap<NodeId, Code> = HashMap::new();
let retired: Vec<Unit> = match only {
None => self.parts.keys().cloned().collect(),
Some(only) => only.iter().filter(|unit| self.parts.contains_key(*unit)).cloned().collect(),
};
for unit in retired {
let Some(owned) = self.parts.remove(&unit) else { continue };
for key in owned.values {
if let Some(bound) = self.bound.values.remove(&key) {
old_values.insert(key, bound);
}
}
for repeat in owned.repeats {
if let Some(instances) = self.bound.instances.remove(&repeat) {
old_keys.insert(repeat.clone(), instances.into_iter().map(|instance| instance.key).collect());
}
if let Some(error) = self.bound.repeat_errors.remove(&repeat) {
old_errors.insert(repeat, error.code);
}
}
}
let mut taken = self.tree_ids.clone();
let mut spent = 0;
for owned in self.parts.values() {
taken.extend(owned.ids.iter().cloned());
spent += owned.nodes;
}
let provider = self.bound.tree.document().provider_id.clone();
let parts = Walker::new(&*port, &provider, limits, taken, limits.max_nodes.saturating_sub(spent), only)
.run(&self.bound.tree.document().root);
let mut diagnostics = Vec::new();
let mut dirty: Vec<NodeId> = Vec::new();
let mut note = |node: &NodeId, code: Code, detail: &str, was: Option<Code>| {
if was != Some(code) {
diagnostics.push(Diagnostic { code, surface: self.key.clone(), node: Some(node.clone()), detail: detail.to_string() });
}
};
for (unit, part) in parts {
let mut owned = Owned {
values: Vec::new(),
repeats: Vec::new(),
ids: part.ids,
nodes: part.nodes,
interests: part.interests,
};
for (key, bound) in part.values {
let old = old_values.remove(&key);
if old.as_ref() != Some(&bound) {
dirty.push(key.0.clone());
}
if let Bound::Error(error) = &bound {
note(&key.0, error.code, &error.detail, match &old {
Some(Bound::Error(was)) => Some(was.code),
_ => None,
});
}
owned.values.push(key.clone());
self.bound.values.insert(key, bound);
}
for (repeat, error) in part.errors {
note(&repeat, error.code, &error.detail, old_errors.get(&repeat).copied());
self.bound.repeat_errors.insert(repeat, error);
}
for (repeat, instances) in part.instances {
let keys: Vec<String> = instances.iter().map(|instance| instance.key.clone()).collect();
if old_keys.remove(&repeat).as_ref() != Some(&keys) {
dirty.push(repeat.clone());
}
owned.repeats.push(repeat.clone());
self.bound.instances.insert(repeat, instances);
}
self.parts.insert(unit, owned);
}
// What the retired units held and the new ones no longer do has vanished.
dirty.extend(old_values.into_keys().map(|(node, _)| node));
dirty.extend(old_keys.into_keys());
ledger.diff(port, &before, &self.interests());
let mut seen = HashSet::new();
dirty.retain(|node| seen.insert(node.clone()));
dirty.sort_by(|a, b| a.as_str().cmp(b.as_str()));
(dirty, diagnostics)
}
fn matching(&self, address: &Address) -> HashSet<Unit> {
self.parts
.iter()
.filter(|(_, owned)| owned.interests.iter().any(|interest| interest.matches(address)))
.map(|(unit, _)| unit.clone())
.collect()
}
}
impl Binder {
pub fn new(limits: Limits) -> Self {
Self { limits, surfaces: HashMap::new() }
}
/// Bind a resolved tree. A tree for a surface already held replaces its tree: the walk, the
/// diff against what was bound and the interest diff are the same as an apply's.
pub fn bind(&mut self, tree: ResolvedTree, port: &mut dyn StatePort, ledger: &mut Ledger) -> Applied {
let key = tree.document().record_key();
let ids = tree_ids(&tree);
let surface = self.surfaces.entry(key.clone()).or_insert_with(|| Surface {
key: key.clone(),
bound: BoundTree {
tree: tree.clone(),
values: HashMap::new(),
instances: HashMap::new(),
repeat_errors: HashMap::new(),
},
tree_ids: HashSet::new(),
parts: HashMap::new(),
});
surface.bound.tree = tree;
surface.tree_ids = ids;
let (dirty, diagnostics) = surface.run(&self.limits, port, ledger, None);
Applied { dirty: BTreeMap::from([(key, dirty)]).into_iter().filter(|(_, ids)| !ids.is_empty()).collect(), diagnostics }
}
/// One drained change: nothing is read unless a held interest matches its address; then each
/// unit that read it is bound again from the port.
pub fn apply(&mut self, change: &Change, port: &mut dyn StatePort, ledger: &mut Ledger) -> Applied {
let address = match change {
Change::Upsert(entry) => &entry.address,
Change::Delete(address) => address,
Change::Refused(refusal) => &refusal.address,
};
let mut applied = Applied::default();
let mut keys: Vec<String> = self.surfaces.keys().cloned().collect();
keys.sort();
for key in keys {
let surface = self.surfaces.get_mut(&key).expect("key listed");
let units = surface.matching(address);
if units.is_empty() {
continue;
}
let (dirty, diagnostics) = surface.run(&self.limits, port, ledger, Some(&units));
if !dirty.is_empty() {
applied.dirty.insert(key, dirty);
}
applied.diagnostics.extend(diagnostics);
}
applied
}
/// Drop a surface: its interests are released.
pub fn forget(&mut self, surface: &str, port: &mut dyn StatePort, ledger: &mut Ledger) {
if let Some(surface) = self.surfaces.remove(surface) {
ledger.diff(port, &surface.interests(), &HashSet::new());
}
}
pub fn tree(&self, surface: &str) -> Option<&BoundTree> {
self.surfaces.get(surface).map(|surface| &surface.bound)
}
}

View file

@ -0,0 +1,199 @@
//! Repeat: a collection's items become instances of the template, keyed so identity follows the
//! item. An instance's ids derive from (repeat id, key, template id) by one scheme:
//! `<repeat>#<key byte length>:<key>/<template id>`; an item the port refused has no key to read,
//! so its identity is its record key in the distinct form `<repeat>!<length>:<record key>/<template id>`.
//! A Repeat that cannot be instantiated is an error of that Repeat alone.
use std::collections::HashSet;
use thing_contract::*;
use super::walk::{Item, Walker, children, common, fault, walk};
use super::{BindError, Instance};
use crate::diagnostic::Code;
use crate::port::{Lookup, Prefix, Record, StateValue};
use crate::resolve::grow;
/// One item of a collection. `record_key` is set for an item that is a record of its own.
pub(super) struct Entry {
pub record_key: Option<String>,
pub item: Item,
}
/// The key of an item: Text as it is, an Int in decimal.
fn key_of(value: &StateValue, path: &MemberPath) -> Result<String, BindError> {
match walk(value, path)? {
Some(StateValue::Text(text)) => Ok(text.clone()),
Some(StateValue::Int(n)) => Ok(n.to_string()),
Some(_) => Err(fault(Code::BindTypeMismatch, "an item key is not Text or Int")),
None => Err(fault(Code::BindTypeMismatch, "an item key is nil")),
}
}
fn collect_ids(node: &Node, out: &mut Vec<NodeId>) {
grow(|| {
out.extend(common(node).map(|common| common.id.clone()));
if let Node::Repeat(repeat) = node {
collect_ids(&repeat.template, out);
}
children(node).iter().for_each(|child| collect_ids(child, out));
})
}
/// Give every id of the template, and every anchor that names one of them, the instance prefix.
fn rewrite(node: &mut Node, prefix: &str, inside: &HashSet<NodeId>) {
grow(|| {
let derive = |id: &mut NodeId| *id = NodeId::new(format!("{prefix}{}", id.as_str()));
match node {
Node::Box(n) => {
derive(&mut n.common.id);
n.children.iter_mut().for_each(|child| rewrite(child, prefix, inside));
}
Node::Button(n) => {
derive(&mut n.common.id);
n.content.iter_mut().for_each(|child| rewrite(child, prefix, inside));
}
Node::Overlay(n) => {
derive(&mut n.common.id);
if let Anchor::Node(anchor) = &mut n.anchor {
if inside.contains(&anchor.node) {
derive(&mut anchor.node);
}
}
n.children.iter_mut().for_each(|child| rewrite(child, prefix, inside));
}
Node::Repeat(n) => {
derive(&mut n.common.id);
rewrite(&mut n.template, prefix, inside);
}
Node::Text(n) => derive(&mut n.common.id),
Node::Image(n) => derive(&mut n.common.id),
Node::Toggle(n) => derive(&mut n.common.id),
Node::Slider(n) => derive(&mut n.common.id),
Node::TextInput(n) => derive(&mut n.common.id),
Node::Select(n) => derive(&mut n.common.id),
Node::Plot(n) => derive(&mut n.common.id),
Node::Embed(n) => derive(&mut n.common.id),
Node::Use(n) => derive(&mut n.common.id),
Node::Slot(_) => {}
}
})
}
impl Walker<'_> {
/// The items of a collection, each a value or the fault that stands for it. Records read the
/// prefix, a Member reads the list of its holder; both leave their interest.
pub(super) fn collection(&mut self, source: &CollectionSource, item: Option<&Item>) -> Result<Vec<Entry>, BindError> {
match source {
CollectionSource::Records(records) => {
let provider = records.provider.clone().unwrap_or_else(|| self.provider.clone());
let prefix = Prefix { provider, schema: records.schema.clone(), key_prefix: records.key_prefix.clone() };
self.part.interests.insert(crate::port::Interest::Prefix(prefix.clone()));
Ok(self
.port
.list(&prefix)
.into_iter()
.filter_map(|lookup| match lookup {
Lookup::Present(entry) => {
let record_key = Some(entry.address.key.as_str().to_string());
Some(match entry.record {
Record::State { schema, value } if schema == records.schema => {
Entry { record_key, item: Item::Value(value) }
}
_ => Entry {
record_key,
item: Item::Fault(fault(
Code::BindSchemaMismatch,
format!("the record is not held under {}", records.schema.as_str()),
)),
},
})
}
Lookup::Refused(refusal) => Some(Entry {
record_key: Some(refusal.address.key.as_str().to_string()),
item: Item::Fault(fault(Code::DecodeRefused, refusal.detail)),
}),
Lookup::Absent => None,
})
.collect())
}
CollectionSource::Member(bind) => self.with_source(&bind.source, item, |held| match held? {
None => Ok(Vec::new()),
Some(holder) => match walk(holder, &bind.member)? {
None => Ok(Vec::new()),
Some(StateValue::List(items)) => Ok(items
.iter()
.map(|value| Entry { record_key: None, item: Item::Value(value.clone()) })
.collect()),
Some(_) => Err(fault(Code::BindTypeMismatch, "a collection member is not a list")),
},
}),
CollectionSource::Param(_) => {
Err(fault(Code::BindTypeMismatch, "a parameter that resolve left in the tree"))
}
}
}
/// Bind the instances of one Repeat, whole or not at all.
pub(super) fn repeat(&mut self, repeat: &RepeatNode, outer: Option<&Item>) {
let id = repeat.common.id.clone();
match self.instances(repeat, outer) {
Ok(instances) => self.part.instances.push((id, instances)),
Err(error) => {
self.part.errors.push((id.clone(), error));
self.part.instances.push((id, Vec::new()));
}
}
}
fn instances(&mut self, repeat: &RepeatNode, outer: Option<&Item>) -> Result<Vec<Instance>, BindError> {
let entries = self.collection(&repeat.collection, outer)?;
let id = repeat.common.id.as_str();
let mut template_ids = Vec::new();
collect_ids(&repeat.template, &mut template_ids);
let inside: HashSet<NodeId> = template_ids.into_iter().collect();
let mut keys = HashSet::new();
let mut built: Vec<(Instance, Item)> = Vec::with_capacity(entries.len());
for entry in entries {
let (key, prefix) = match &entry.item {
Item::Fault(_) => {
let record = entry.record_key.clone().unwrap_or_default();
(format!("!{record}"), format!("{id}!{}:{record}/", record.len()))
}
Item::Value(value) => {
let key = key_of(value, &repeat.key_member)?;
if !keys.insert(key.clone()) {
return Err(fault(Code::RepeatKeyDuplicate, format!("two items of {id} share one key")));
}
let prefix = format!("{id}#{}:{key}/", key.len());
(key, prefix)
}
};
let mut root = (*repeat.template).clone();
rewrite(&mut root, &prefix, &inside);
built.push((Instance { key, root }, entry.item));
}
let mut ids = Vec::new();
for (instance, _) in &built {
collect_ids(&instance.root, &mut ids);
}
if ids.len() > self.budget.min(self.limits.max_nodes) {
return Err(fault(Code::ExpansionLimit, format!("the instances of {id} are past the node limit")));
}
let mut local = HashSet::new();
if ids.iter().any(|derived| self.taken.contains(derived) || !local.insert(derived)) {
return Err(fault(Code::DuplicateNodeId, format!("an instance id of {id} is already an id of the tree")));
}
self.budget -= ids.len();
self.part.nodes += ids.len();
self.taken.extend(ids.iter().cloned());
self.part.ids.extend(ids);
for (instance, item) in &built {
self.instance(&instance.root, item);
}
Ok(built.into_iter().map(|(instance, _)| instance).collect())
}
}

View file

@ -0,0 +1,370 @@
//! The walk: every source site of a node, read from the state port, a member path and a terminal
//! type. Nothing here keeps a value: the port is the truth.
use std::collections::HashSet;
use thing_contract::*;
use super::format;
use super::{BindError, Bound, Field, Instance};
use crate::diagnostic::Code;
use crate::port::{Address, Entry, Interest, Lookup, Record, StatePort, StateValue};
use crate::resolve::{Limits, grow};
/// What a surface's values are re-evaluated by: one site, or one outermost Repeat (`None`).
pub(super) type Unit = (NodeId, Option<Field>);
/// What one unit bound: its values, its instance lists, its Repeat faults, the ids and node count
/// its instances take, and the interests it read.
#[derive(Default)]
pub(super) struct Part {
pub values: Vec<((NodeId, Field), Bound)>,
pub instances: Vec<(NodeId, Vec<Instance>)>,
pub errors: Vec<(NodeId, BindError)>,
pub ids: Vec<NodeId>,
pub nodes: usize,
pub interests: HashSet<Interest>,
}
/// The value a Repeat's template reads through `Item`.
pub(super) enum Item {
Value(StateValue),
Fault(BindError),
}
pub(super) fn fault(code: Code, detail: impl Into<String>) -> BindError {
BindError { code, detail: detail.into() }
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Want {
Text,
Number,
Bool,
Series,
}
enum Site<'n> {
Bool(&'n BoolSource),
Text(&'n TextSource),
Number(&'n NumberSource),
Bind(&'n Bind, Want),
Options(&'n OptionList),
}
fn kind(value: &StateValue) -> &'static str {
match value {
StateValue::Nil => "nil",
StateValue::Bool(_) => "bool",
StateValue::Int(_) => "int",
StateValue::Float(_) => "float",
StateValue::Text(_) => "text",
StateValue::Bytes(_) => "bytes",
StateValue::List(_) => "list",
StateValue::Record(_) => "record",
}
}
fn number_of(value: &StateValue) -> Option<f64> {
match value {
StateValue::Int(n) => Some(*n as f64),
StateValue::Float(n) => Some(*n),
_ => None,
}
}
/// Walk `path` from `value`. `Ok(None)` is a Nil reached, which is absence.
pub(super) fn walk<'v>(mut value: &'v StateValue, path: &MemberPath) -> Result<Option<&'v StateValue>, BindError> {
for step in &path.steps {
if matches!(value, StateValue::Nil) {
return Ok(None);
}
value = match (step, value) {
(MemberStep::Name(step), StateValue::Record(_)) => value
.member(&step.name)
.ok_or_else(|| fault(Code::BindMemberMissing, format!("the record has no member {}", step.name)))?,
(MemberStep::Index(step), StateValue::List(items)) => items.get(step.index.get() as usize).ok_or_else(|| {
fault(Code::BindMemberMissing, format!("the list has no index {}", step.index.get()))
})?,
(MemberStep::Name(step), other) => {
return Err(fault(Code::BindTypeMismatch, format!("member {} asked of a {}", step.name, kind(other))));
}
(MemberStep::Index(step), other) => {
return Err(fault(Code::BindTypeMismatch, format!("index {} asked of a {}", step.index.get(), kind(other))));
}
};
}
Ok(if matches!(value, StateValue::Nil) { None } else { Some(value) })
}
/// A value at the type its site takes. No value is coerced; a Format is the only road from a
/// number to text.
fn terminal(value: &StateValue, want: Want, format: Option<&Format>) -> Result<Bound, BindError> {
let mismatch = |why: &str| Err(fault(Code::BindTypeMismatch, format!("{why}: a {} value", kind(value))));
if want != Want::Text && format.is_some() {
return mismatch("a Format on a site that is not text");
}
match want {
Want::Number => match number_of(value) {
Some(n) => Ok(Bound::Number(n)),
None => mismatch("a number site"),
},
Want::Bool => match value {
StateValue::Bool(b) => Ok(Bound::Bool(*b)),
_ => mismatch("a bool site"),
},
Want::Series => match value {
StateValue::List(items) => match items.iter().map(number_of).collect::<Option<Vec<f64>>>() {
Some(series) => Ok(Bound::Series(series)),
None => Err(fault(Code::BindTypeMismatch, "a series holds a member that is not a number")),
},
_ => mismatch("a series site"),
},
Want::Text => {
let text = match (value, format) {
(StateValue::Text(text), None) => Ok(text.clone()),
(StateValue::Text(text), Some(Format::Affix(affix))) => Ok(format::affix(text, affix)),
(StateValue::Text(text), Some(Format::Timestamp)) => format::stamp(text),
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Number(spec))) => {
Ok(format::number(number_of(value).unwrap(), spec))
}
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Duration)) => {
format::duration(number_of(value).unwrap())
}
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Timestamp)) => {
format::timestamp(number_of(value).unwrap())
}
_ => Err("the value does not fit the text site and its Format"),
};
text.map(Bound::Text).map_err(|why| fault(Code::BindTypeMismatch, format!("{why}: a {} value", kind(value))))
}
}
}
/// The Text at `path` of an item, for an option's value or label.
pub(super) fn item_text(value: &StateValue, path: &MemberPath) -> Result<String, BindError> {
match walk(value, path)? {
Some(StateValue::Text(text)) => Ok(text.clone()),
Some(other) => Err(fault(Code::BindTypeMismatch, format!("an option member is a {}", kind(other)))),
None => Err(fault(Code::BindTypeMismatch, "an option member is nil")),
}
}
/// The sites of one node, in Field order.
fn sites(node: &Node) -> Vec<(Field, Site<'_>)> {
let mut found = Vec::new();
let Some(common) = common(node) else { return found };
found.push((Field::Visible, Site::Bool(&common.visible)));
if let Some(label) = &common.a11y_label {
found.push((Field::A11yLabel, Site::Text(label)));
}
match node {
Node::Text(n) => found.push((Field::Content, Site::Text(&n.content))),
Node::Image(n) => found.push((Field::Alt, Site::Text(&n.alt))),
Node::Button(n) => found.push((Field::Enabled, Site::Bool(&n.enabled))),
Node::Toggle(n) => found.push((Field::Checked, Site::Bool(&n.checked))),
Node::Slider(n) => found.push((Field::Value, Site::Number(&n.value))),
Node::TextInput(n) => {
found.push((Field::Placeholder, Site::Text(&n.placeholder)));
found.push((Field::Initial, Site::Text(&n.initial)));
}
Node::Select(n) => {
found.push((Field::Options, Site::Options(&n.options)));
found.push((Field::Selected, Site::Bind(&n.value, Want::Text)));
}
Node::Plot(n) => found.push((Field::Series, Site::Bind(&n.series, Want::Series))),
_ => {}
}
found
}
pub(super) fn common(node: &Node) -> Option<&NodeCommon> {
Some(match node {
Node::Box(n) => &n.common,
Node::Text(n) => &n.common,
Node::Image(n) => &n.common,
Node::Button(n) => &n.common,
Node::Toggle(n) => &n.common,
Node::Slider(n) => &n.common,
Node::TextInput(n) => &n.common,
Node::Select(n) => &n.common,
Node::Repeat(n) => &n.common,
Node::Overlay(n) => &n.common,
Node::Plot(n) => &n.common,
Node::Embed(n) => &n.common,
Node::Use(n) => &n.common,
Node::Slot(_) => return None,
})
}
/// The children a walk visits: a Repeat's template is instantiated, never visited as itself.
pub(super) fn children(node: &Node) -> &[Node] {
match node {
Node::Box(n) => &n.children,
Node::Button(n) => &n.content,
Node::Overlay(n) => &n.children,
_ => &[],
}
}
pub(super) struct Walker<'a> {
pub(super) port: &'a dyn StatePort,
pub(super) provider: &'a ProviderId,
pub(super) limits: &'a Limits,
/// Every id of the bound tree outside the units being walked, and the ones walked so far.
pub(super) taken: HashSet<NodeId>,
/// Instance nodes still allowed.
pub(super) budget: usize,
only: Option<&'a HashSet<Unit>>,
pub(super) part: Part,
done: Vec<(Unit, Part)>,
}
impl<'a> Walker<'a> {
pub(super) fn new(
port: &'a dyn StatePort,
provider: &'a ProviderId,
limits: &'a Limits,
taken: HashSet<NodeId>,
budget: usize,
only: Option<&'a HashSet<Unit>>,
) -> Self {
Self { port, provider, limits, taken, budget, only, part: Part::default(), done: Vec::new() }
}
/// Walk the resolved root, binding every unit `only` selects (all when `None`).
pub(super) fn run(mut self, root: &Node) -> Vec<(Unit, Part)> {
self.top(root);
self.done
}
fn selects(&self, unit: &Unit) -> bool {
self.only.is_none_or(|only| only.contains(unit))
}
fn end(&mut self, unit: Unit) {
let part = std::mem::take(&mut self.part);
self.done.push((unit, part));
}
fn top(&mut self, node: &Node) {
grow(|| {
let Some(id) = common(node).map(|common| common.id.clone()) else { return };
for (field, site) in sites(node) {
let unit = (id.clone(), Some(field));
if self.selects(&unit) {
let value = self.eval(site, None);
self.part.values.push(((id.clone(), field), value));
self.end(unit);
}
}
if let Node::Repeat(repeat) = node {
let unit = (id, None);
if self.selects(&unit) {
self.repeat(repeat, None);
self.end(unit);
}
} else {
children(node).iter().for_each(|child| self.top(child));
}
})
}
/// An instance's nodes: every site binds, with `item` as the Item.
pub(super) fn instance(&mut self, node: &Node, item: &Item) {
grow(|| {
let Some(id) = common(node).map(|common| common.id.clone()) else { return };
for (field, site) in sites(node) {
let value = self.eval(site, Some(item));
self.part.values.push(((id.clone(), field), value));
}
if let Node::Repeat(repeat) = node {
self.repeat(repeat, Some(item));
} else {
children(node).iter().for_each(|child| self.instance(child, item));
}
})
}
fn eval(&mut self, site: Site<'_>, item: Option<&Item>) -> Bound {
let unresolved = || Bound::Error(fault(Code::BindTypeMismatch, "a parameter that resolve left in the tree"));
match site {
Site::Bool(BoolSource::Literal(literal)) => Bound::Bool(literal.value),
Site::Bool(BoolSource::Bound(bind)) => self.bind(bind, Want::Bool, item),
Site::Text(TextSource::Literal(literal)) => Bound::Text(literal.value.clone()),
Site::Text(TextSource::Bound(bind)) => self.bind(bind, Want::Text, item),
Site::Number(NumberSource::Literal(literal)) => Bound::Number(literal.value),
Site::Number(NumberSource::Bound(bind)) => self.bind(bind, Want::Number, item),
Site::Bool(BoolSource::Param(_)) | Site::Text(TextSource::Param(_)) | Site::Number(NumberSource::Param(_)) => {
unresolved()
}
Site::Bind(bind, want) => self.bind(bind, want, item),
Site::Options(OptionList::Literal(literal)) => Bound::Options(literal.options.clone()),
Site::Options(OptionList::Bound(bound)) => self.options(bound, item),
}
}
/// Hand `then` what `source` holds: a fault, absence, or the value. Records the interest a
/// Record source reads.
pub(super) fn with_source<R>(
&mut self,
source: &StateSource,
item: Option<&Item>,
then: impl FnOnce(Result<Option<&StateValue>, BindError>) -> R,
) -> R {
match source {
StateSource::Item => match item {
Some(Item::Value(value)) => then(Ok(Some(value))),
Some(Item::Fault(error)) => then(Err(error.clone())),
None => then(Err(fault(Code::BindTypeMismatch, "an Item source outside a Repeat"))),
},
StateSource::Record(reference) => {
let provider = reference.provider.clone().unwrap_or_else(|| self.provider.clone());
let address = Address { provider, schema: reference.schema.clone(), key: reference.key.clone() };
self.part.interests.insert(Interest::Record(address.clone()));
match self.port.read(&address) {
Lookup::Present(Entry { record: Record::State { schema, value }, .. }) if schema == reference.schema => {
then(Ok(Some(&value)))
}
Lookup::Present(_) => then(Err(fault(
Code::BindSchemaMismatch,
format!("the record is not held under {}", reference.schema.as_str()),
))),
Lookup::Absent => then(Ok(None)),
Lookup::Refused(refusal) => then(Err(fault(Code::DecodeRefused, refusal.detail))),
}
}
}
}
fn bind(&mut self, bind: &Bind, want: Want, item: Option<&Item>) -> Bound {
self.with_source(&bind.source, item, |held| match held {
Err(error) => Bound::Error(error),
Ok(None) => Bound::Absent,
Ok(Some(value)) => match walk(value, &bind.member) {
Err(error) => Bound::Error(error),
Ok(None) => Bound::Absent,
Ok(Some(value)) => terminal(value, want, bind.format.as_ref()).unwrap_or_else(Bound::Error),
},
})
}
fn options(&mut self, bound: &BoundOptions, item: Option<&Item>) -> Bound {
let entries = match self.collection(&bound.collection, item) {
Ok(entries) => entries,
Err(error) => return Bound::Error(error),
};
let mut options = Vec::with_capacity(entries.len());
for entry in entries {
let value = match entry.item {
Item::Value(value) => value,
Item::Fault(error) => return Bound::Error(error),
};
match (item_text(&value, &bound.value_member), item_text(&value, &bound.label_member)) {
(Ok(value), Ok(label)) => options.push(SelectOption { value, label }),
(Err(error), _) | (_, Err(error)) => return Bound::Error(error),
}
}
Bound::Options(options)
}
}

View file

@ -1,6 +1,7 @@
//! Thing's core: a function of documents, state, input and time. It touches the world only
//! through ports; it reads no clock, spawns nothing and awaits nothing.
pub mod bind;
pub mod diagnostic;
pub mod port;
pub mod resolve;

View file

@ -0,0 +1,619 @@
//! Bind: the values of every site, keyed Repeat instances, typed faults, the interests a bound tree
//! holds and the dirty set of a change. `THING_BLESS=1` on `f01_by_name_store` and `f04_form`
//! rewrites their goldens through `golden::check`.
use std::path::PathBuf;
use thing_contract::*;
use thing_core::bind::{Applied, Binder, Bound, BoundTree, Field};
use thing_core::diagnostic::Code;
use thing_core::port::{Address, Change, Interest, Ledger, Prefix, StatePort};
use thing_core::resolve::{Limits, resolve};
use thing_testkit::build::*;
use thing_testkit::fixture::Fixture;
use thing_testkit::golden;
use thing_testkit::mem_state::{Call, MemState};
use thing_testkit::state::{self, Item, Series, Swarm, SwarmRenamed};
const SWARM: &str = "provider.swarm";
const SWARM_SCHEMA: &str = "gamecult.thing.test.swarm.v1";
struct Rig {
state: MemState,
binder: Binder,
ledger: Ledger,
}
fn merge(into: &mut Applied, from: Applied) {
for (surface, ids) in from.dirty {
let held = into.dirty.entry(surface).or_default();
for id in ids {
if !held.contains(&id) {
held.push(id);
}
}
}
into.diagnostics.extend(from.diagnostics);
}
impl Rig {
fn new(state: MemState) -> Self {
Self { state, binder: Binder::new(Limits::default()), ledger: Ledger::new() }
}
fn fixture(fixture: Fixture) -> (Self, SurfaceDocument) {
let mut state = MemState::from_fixture(fixture);
state::script(fixture, &mut state);
(Self::new(state), fixture.load().surfaces.remove(0))
}
fn bind(&mut self, document: &SurfaceDocument) -> Applied {
let resolution = resolve(document, &self.state, &Limits::default());
let tree = resolution.tree.unwrap_or_else(|| panic!("not resolved: {:?}", resolution.diagnostics));
self.binder.bind(tree, &mut self.state, &mut self.ledger)
}
/// Drain the port and apply each change, as the frame owner does.
fn settle(&mut self) -> Applied {
let mut applied = Applied::default();
for change in self.state.drain() {
merge(&mut applied, self.binder.apply(&change, &mut self.state, &mut self.ledger));
}
applied
}
fn tree(&self, document: &SurfaceDocument) -> &BoundTree {
self.binder.tree(&document.record_key()).expect("bound")
}
}
fn nodes(applied: &Applied, document: &SurfaceDocument) -> Vec<String> {
applied.dirty.get(&document.record_key()).map(|ids| ids.iter().map(|id| id.as_str().to_string()).collect()).unwrap_or_default()
}
fn show(bound: &Bound) -> String {
match bound {
Bound::Text(text) => format!("text {text:?}"),
Bound::Number(n) => format!("number {n}"),
Bound::Bool(b) => format!("bool {b}"),
Bound::Series(series) => format!("series {series:?}"),
Bound::Options(options) => {
format!("options [{}]", options.iter().map(|o| format!("{}={}", o.value, o.label)).collect::<Vec<_>>().join(", "))
}
Bound::Absent => "absent".to_string(),
Bound::Error(error) => format!("error {:?}", error.code),
}
}
/// The sorted (node id, field, value) listing the goldens hold: bind output has no wire form.
fn listing(tree: &BoundTree) -> String {
tree.sites().into_iter().map(|(node, field, bound)| format!("{} {} {}\n", node.as_str(), field.name(), show(bound))).collect()
}
fn goldens() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
}
fn value<'t>(tree: &'t BoundTree, node: &str, field: Field) -> &'t Bound {
tree.value(&nid(node), field).unwrap_or_else(|| panic!("no value at {node} {field:?}"))
}
fn code(bound: &Bound) -> Code {
match bound {
Bound::Error(error) => error.code,
other => panic!("not an error: {other:?}"),
}
}
fn address(key: &str) -> Address {
Address { provider: ProviderId::new(SWARM), schema: SchemaId::new(SWARM_SCHEMA), key: RecordKey::new(key) }
}
fn swarm_bind(key: &str, steps: Vec<MemberStep>, format: Option<Format>) -> Bind {
bind_at(SWARM_SCHEMA, key, steps, format)
}
fn prices_bind(steps: Vec<MemberStep>, format: Option<Format>) -> Bind {
bind_at("gamecult.thing.test.series.v1", "prices", steps, format)
}
fn bind_at(schema: &str, key: &str, steps: Vec<MemberStep>, format: Option<Format>) -> Bind {
Bind {
source: StateSource::Record(StateRef {
provider: Some(ProviderId::new(SWARM)),
schema: SchemaId::new(schema),
key: RecordKey::new(key),
}),
member: MemberPath { steps },
format,
}
}
fn name(member: &str) -> MemberStep {
MemberStep::Name(MemberName { name: member.into() })
}
fn index(at: i32) -> MemberStep {
MemberStep::Index(MemberIndex { index: count(at) })
}
fn bound_text(id: &str, bind: Bind) -> Node {
Node::Text(TextNode {
common: common(id),
content: TextSource::Bound(bind),
style_token: "body".into(),
wrap: false,
max_lines: None,
selectable: false,
})
}
fn page(label: &str, children: Vec<Node>) -> SurfaceDocument {
SurfaceDocument {
provider_id: ProviderId::new(SWARM),
label: seg(label),
version: ver(1),
title: label.into(),
root: boxed("root", children),
commands: vec![],
}
}
fn swarm_state() -> MemState {
let mut state = MemState::new();
state::script(Fixture::F01SwarmDashboard, &mut state);
state
}
fn count_calls(state: &MemState, wanted: impl Fn(&Call) -> bool) -> usize {
state.calls().iter().filter(|call| wanted(call)).count()
}
fn swarm(id: &str, name: &str, load: f64) -> Swarm {
Swarm { id: id.into(), name: name.into(), load }
}
#[test]
fn f01_by_name_store() {
let mut state = MemState::new();
state.load_store(&ProviderId::new(SWARM), &Fixture::dir().join(state::SWARM_STORE));
let mut rig = Rig::new(state);
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
let applied = rig.bind(&document);
assert_eq!(applied.diagnostics, vec![]);
let tree = rig.tree(&document);
assert_eq!(value(tree, "load", Field::Content), &Bound::Text("42.0%".into()));
let instances = tree.instances(&nid("minds"));
assert_eq!(instances.iter().map(|i| i.key.as_str()).collect::<Vec<_>>(), ["mind-1", "mind-2", "mind-3"]);
for (instance, name) in instances.iter().zip(["Eureka", "Libby", "Kiko"]) {
let id = format!("minds#6:{}/mind-name", instance.key);
assert_eq!(value(tree, &id, Field::Content), &Bound::Text(name.into()));
}
golden::check(&goldens(), "bind-f01-swarm-dashboard.txt", listing(tree).as_bytes());
}
#[test]
fn members_empty_store_refuses_every_record() {
let mut state = MemState::new();
state.load_store(&ProviderId::new(SWARM), &Fixture::dir().join(state::SWARM_STORE_MEMBERS_EMPTY));
let mut rig = Rig::new(state);
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
let applied = rig.bind(&document);
let tree = rig.tree(&document);
assert_eq!(code(value(tree, "load", Field::Content)), Code::DecodeRefused);
let instances = tree.instances(&nid("minds"));
assert_eq!(instances.iter().map(|i| i.key.as_str()).collect::<Vec<_>>(), ["!mind-1", "!mind-2", "!mind-3"]);
for instance in instances {
let id = format!("minds!{}:{}/mind-name", instance.key.len() - 1, &instance.key[1..]);
assert_eq!(code(value(tree, &id, Field::Content)), Code::DecodeRefused);
}
assert_eq!(applied.diagnostics.len(), 4);
assert!(applied.diagnostics.iter().all(|d| d.code == Code::DecodeRefused));
assert!(!listing(tree).contains("Eureka") && !listing(tree).contains("0.42"));
}
#[test]
fn schema_mismatch_missing_member_and_absence() {
// f10's schema-mismatch surface asks nowhere.v1 of a key that holds a swarm.
let hostile = Fixture::F10Hostile.load();
let surface = hostile.surfaces.iter().find(|s| s.label.as_str() == "schema-mismatch").unwrap();
let (mut rig, _) = Rig::fixture(Fixture::F10Hostile);
let applied = rig.bind(surface);
assert_eq!(code(value(rig.tree(surface), "mismatch", Field::Content)), Code::BindSchemaMismatch);
assert_eq!(applied.diagnostics.len(), 1);
assert_eq!(applied.diagnostics[0].code, Code::BindSchemaMismatch);
// Without the record: absent, and nothing to say.
let mut bare = Rig::new(MemState::from_fixture(Fixture::F10Hostile));
let applied = bare.bind(surface);
assert_eq!(value(bare.tree(surface), "mismatch", Field::Content), &Bound::Absent);
assert_eq!(applied.diagnostics, vec![]);
// f01 with Load renamed in the record: a member that is not there is loud.
let mut state = MemState::new();
state.put_state(&ProviderId::new(SWARM), "summary", &SwarmRenamed { id: "summary".into(), name: "Swarm".into(), burden: 0.42 });
let mut rig = Rig::new(state);
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
let applied = rig.bind(&document);
assert_eq!(code(value(rig.tree(&document), "load", Field::Content)), Code::BindMemberMissing);
assert_eq!(applied.diagnostics.iter().filter(|d| d.code == Code::BindMemberMissing).count(), 1);
}
#[test]
fn no_value_is_coerced() {
let mut state = swarm_state();
state.put_state(&ProviderId::new(SWARM), "prices", &Series { values: vec![3.0, 5.5] });
let mut rig = Rig::new(state);
let document = page(
"coerce",
vec![
bound_text("number-as-text", swarm_bind("summary", vec![name("Load")], None)),
bound_text("text-as-number", swarm_bind("summary", vec![name("Name")], Some(Format::Number(NumberFormat { precision: count(1), percent: false, unit: None })))),
bound_text("index-on-record", swarm_bind("summary", vec![index(0)], None)),
bound_text("name-on-list", prices_bind(vec![name("Values"), name("x")], None)),
bound_text("affix-on-number", swarm_bind("summary", vec![name("Load")], Some(Format::Affix(AffixFormat { prefix: "<".into(), suffix: ">".into() })))),
Node::Toggle(ToggleNode {
common: common("number-as-bool"),
checked: BoolSource::Bound(swarm_bind("summary", vec![name("Load")], None)),
on_change: command("x"),
}),
Node::Slider(SliderNode {
common: common("text-as-slider"),
min: 0.0,
max: 1.0,
step: 0.1,
value: NumberSource::Bound(swarm_bind("summary", vec![name("Name")], None)),
commit: command("x"),
}),
Node::Slider(SliderNode {
common: common("formatted-slider"),
min: 0.0,
max: 1.0,
step: 0.1,
value: NumberSource::Bound(swarm_bind("summary", vec![name("Load")], Some(Format::Duration))),
commit: command("x"),
}),
],
);
let mut document = document;
document.commands = ["x"]
.iter()
.map(|id| CommandDecl { id: CommandId::new(*id), payload_schema: SchemaId::new("gamecult.thing.test.x.v1"), captures: vec![], confirm: None })
.collect();
rig.bind(&document);
let tree = rig.tree(&document);
for (id, field) in [
("number-as-text", Field::Content),
("text-as-number", Field::Content),
("index-on-record", Field::Content),
("name-on-list", Field::Content),
("affix-on-number", Field::Content),
("number-as-bool", Field::Checked),
("text-as-slider", Field::Value),
("formatted-slider", Field::Value),
] {
assert_eq!(code(value(tree, id, field)), Code::BindTypeMismatch, "{id}");
}
}
#[test]
fn formats_and_indexes_through_the_walk() {
let mut state = swarm_state();
state.put_state(&ProviderId::new(SWARM), "prices", &Series { values: vec![3.0, 5.5, 3_605.0] });
let mut rig = Rig::new(state);
let document = page(
"formats",
vec![
bound_text("index", prices_bind(vec![name("Values"), index(1)], Some(Format::Number(NumberFormat { precision: count(2), percent: false, unit: Some("pt".into()) })))),
bound_text("duration", prices_bind(vec![name("Values"), index(2)], Some(Format::Duration))),
bound_text("timestamp", prices_bind(vec![name("Values"), index(0)], Some(Format::Timestamp))),
bound_text("affix", swarm_bind("summary", vec![name("Name")], Some(Format::Affix(AffixFormat { prefix: "[".into(), suffix: "]".into() })))),
bound_text("past-the-end", prices_bind(vec![name("Values"), index(9)], None)),
],
);
rig.bind(&document);
let tree = rig.tree(&document);
assert_eq!(value(tree, "index", Field::Content), &Bound::Text("5.50 pt".into()));
assert_eq!(value(tree, "duration", Field::Content), &Bound::Text("1h 00m 05s".into()));
assert_eq!(value(tree, "timestamp", Field::Content), &Bound::Text("1970-01-01T00:00:03Z".into()));
assert_eq!(value(tree, "affix", Field::Content), &Bound::Text("[Swarm]".into()));
assert_eq!(code(value(tree, "past-the-end", Field::Content)), Code::BindMemberMissing);
}
#[test]
fn f04_form() {
let (mut rig, document) = Rig::fixture(Fixture::F04Form);
let applied = rig.bind(&document);
assert_eq!(applied.diagnostics, vec![]);
let tree = rig.tree(&document);
assert_eq!(value(tree, "enabled", Field::Checked), &Bound::Bool(true));
assert_eq!(value(tree, "volume", Field::Value), &Bound::Number(40.0));
assert_eq!(value(tree, "theme", Field::Selected), &Bound::Text("dark".into()));
golden::check(&goldens(), "bind-f04-form.txt", listing(tree).as_bytes());
}
#[test]
fn f07_series_and_f06_options() {
let (mut rig, document) = Rig::fixture(Fixture::F07Plot);
rig.bind(&document);
assert_eq!(value(rig.tree(&document), "line", Field::Series), &Bound::Series(vec![3.0, 5.5, 4.25, 8.0, 6.5]));
// A select whose options are the records of a collection.
let mut state = MemState::new();
state::script(Fixture::F06ScrollList, &mut state);
let select = Node::Select(SelectNode {
common: common("pick"),
options: OptionList::Bound(BoundOptions {
collection: CollectionSource::Records(RecordsSource {
provider: Some(ProviderId::new("provider.feed")),
schema: SchemaId::new("gamecult.thing.test.item.v1"),
key_prefix: "item-000".into(),
}),
value_member: path(&["Id"]),
label_member: path(&["Title"]),
}),
value: swarm_bind("none", vec![name("Id")], None),
on_change: command("x"),
});
let mut document = page("options", vec![select]);
document.commands = vec![CommandDecl { id: CommandId::new("x"), payload_schema: SchemaId::new("gamecult.thing.test.x.v1"), captures: vec![], confirm: None }];
let mut rig = Rig::new(state);
rig.bind(&document);
let Bound::Options(options) = value(rig.tree(&document), "pick", Field::Options) else { panic!("not options") };
assert_eq!(options.len(), 10);
assert_eq!((options[3].value.as_str(), options[3].label.as_str()), ("item-0003", "Item 3"));
assert_eq!(value(rig.tree(&document), "pick", Field::Selected), &Bound::Absent);
}
#[test]
fn repeat_identity_follows_the_key() {
let (mut rig, document) = Rig::fixture(Fixture::F06ScrollList);
rig.bind(&document);
let feed = ProviderId::new("provider.feed");
let ids = |rig: &Rig| -> Vec<String> {
let mut ids: Vec<String> = rig.tree(&document).instances(&nid("items")).iter().map(|i| format!("{:?}", i.root)).collect();
ids.sort();
ids
};
let keys = |rig: &Rig| -> Vec<String> { rig.tree(&document).instances(&nid("items")).iter().map(|i| i.key.clone()).collect() };
let before_ids = ids(&rig);
let before_keys = keys(&rig);
assert_eq!(before_keys.len(), 1000);
let id_of = |key: &str| format!("items#{}:{key}/item-row", key.len());
assert!(rig.tree(&document).value(&nid(&id_of("item-0042")), Field::Visible).is_some());
assert!(rig.tree(&document).value(&nid(&"items#9:item-0042/item-title".to_string()), Field::Content).is_some());
// Reorder: two records swap which Id they hold. The instance id set is the same.
rig.state.put_state(&feed, "item-0000", &Item { id: "item-0001".into(), title: "Item 1".into() });
rig.state.put_state(&feed, "item-0001", &Item { id: "item-0000".into(), title: "Item 0".into() });
let applied = rig.settle();
assert_eq!(ids(&rig), before_ids);
let after = keys(&rig);
assert_eq!(&after[..2], ["item-0001", "item-0000"]);
assert!(nodes(&applied, &document).contains(&"items".to_string()));
// Insert one.
rig.state.put_state(&feed, "item-0500a", &Item { id: "extra".into(), title: "Extra".into() });
let applied = rig.settle();
assert_eq!(keys(&rig).len(), 1001);
assert!(nodes(&applied, &document).contains(&"items".to_string()));
assert!(rig.tree(&document).value(&nid(&id_of("extra")), Field::Visible).is_some());
// Remove one.
rig.state.delete(&Address { provider: feed, schema: SchemaId::new("gamecult.thing.test.item.v1"), key: RecordKey::new("item-0500a") });
let applied = rig.settle();
assert_eq!(keys(&rig).len(), 1000);
assert!(nodes(&applied, &document).contains(&"items".to_string()));
assert!(rig.tree(&document).value(&nid(&id_of("extra")), Field::Visible).is_none());
}
#[test]
fn a_duplicate_key_is_local_to_its_repeat() {
let mut state = swarm_state();
state.put_state(&ProviderId::new(SWARM), "mind-2", &swarm("mind-1", "Twin", 0.0));
let mut rig = Rig::new(state);
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
let applied = rig.bind(&document);
let tree = rig.tree(&document);
assert_eq!(tree.repeat_error(&nid("minds")).map(|e| e.code), Some(Code::RepeatKeyDuplicate));
assert!(tree.instances(&nid("minds")).is_empty());
assert_eq!(value(tree, "load", Field::Content), &Bound::Text("42.0%".into()));
assert_eq!(applied.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [Code::RepeatKeyDuplicate]);
}
#[test]
fn an_instance_id_that_is_already_an_id_refuses_that_repeat() {
// The authored id is exactly the id the first instance would derive.
let items = Node::Repeat(RepeatNode {
common: common("rows"),
collection: CollectionSource::Records(RecordsSource { provider: None, schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "mind-".into() }),
key_member: path(&["Id"]),
template: std::boxed::Box::new(text("t", "row")),
});
let document = page("clash", vec![items, text("rows#6:mind-1/t", "taken")]);
let mut rig = Rig::new(swarm_state());
let applied = rig.bind(&document);
assert_eq!(rig.tree(&document).repeat_error(&nid("rows")).map(|e| e.code), Some(Code::DuplicateNodeId));
assert_eq!(applied.diagnostics.len(), 1);
// And past the node limit.
let resolution = resolve(&document, &rig.state, &Limits::default());
let mut small = Binder::new(Limits { max_nodes: 2, ..Limits::default() });
let mut ledger = Ledger::new();
let roomy = page("limit", vec![Node::Repeat(RepeatNode {
common: common("rows"),
collection: CollectionSource::Records(RecordsSource { provider: None, schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "mind-".into() }),
key_member: path(&["Id"]),
template: std::boxed::Box::new(text("t", "row")),
})]);
drop(resolution);
let tree = resolve(&roomy, &rig.state, &Limits::default()).tree.unwrap();
small.bind(tree, &mut rig.state, &mut ledger);
assert_eq!(small.tree(&roomy.record_key()).unwrap().repeat_error(&nid("rows")).map(|e| e.code), Some(Code::ExpansionLimit));
}
#[test]
fn nested_repeats_derive_ids_from_ids() {
// Rows of swarm records, and under each a Repeat over the same records.
let inner = Node::Repeat(RepeatNode {
common: common("inner"),
collection: CollectionSource::Records(RecordsSource { provider: None, schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "mind-1".into() }),
key_member: path(&["Id"]),
template: std::boxed::Box::new(Node::Text(TextNode {
common: common("cell"),
content: TextSource::Bound(item_bind(path(&["Name"]))),
style_token: "body".into(),
wrap: false,
max_lines: None,
selectable: false,
})),
});
let outer = Node::Repeat(RepeatNode {
common: common("outer"),
collection: CollectionSource::Records(RecordsSource { provider: None, schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "mind-".into() }),
key_member: path(&["Id"]),
template: std::boxed::Box::new(boxed("row", vec![inner])),
});
let document = page("nested", vec![outer]);
let mut rig = Rig::new(swarm_state());
let applied = rig.bind(&document);
assert_eq!(applied.diagnostics, vec![]);
let tree = rig.tree(&document);
assert_eq!(tree.instances(&nid("outer")).len(), 3);
let inner_id = "outer#6:mind-2/inner";
let cells = tree.instances(&nid(inner_id));
assert_eq!(cells.len(), 1);
assert_eq!(value(tree, &format!("{inner_id}#6:mind-1/outer#6:mind-2/cell"), Field::Content), &Bound::Text("Eureka".into()));
}
#[test]
fn dirty_is_only_what_changed() {
let (mut rig, document) = Rig::fixture(Fixture::F01SwarmDashboard);
rig.bind(&document);
let before = rig.state.calls().len();
rig.state.put_state(&ProviderId::new(SWARM), "summary", &swarm("summary", "Swarm", 0.5));
let applied = rig.settle();
assert_eq!(nodes(&applied, &document), ["load"]);
assert_eq!(value(rig.tree(&document), "load", Field::Content), &Bound::Text("50.0%".into()));
let calls: Vec<Call> = rig.state.calls()[before..].iter().filter(|call| **call != Call::Drain).cloned().collect();
assert_eq!(calls, [Call::Read(address("summary"))]);
// A record nothing holds an interest in is never queued, and a change handed over anyway reads nothing.
rig.state.put_state(&ProviderId::new(SWARM), "zzz", &swarm("zzz", "Nobody", 0.0));
assert!(rig.state.drain().is_empty());
let calls_before = rig.state.calls().len();
let applied = rig.binder.apply(&Change::Delete(address("zzz")), &mut rig.state, &mut rig.ledger);
assert_eq!(applied, Applied::default());
assert_eq!(rig.state.calls().len(), calls_before);
// A mind changing re-lists its Repeat only.
rig.state.put_state(&ProviderId::new(SWARM), "mind-3", &swarm("mind-3", "Renamed", 0.0));
let applied = rig.settle();
assert_eq!(nodes(&applied, &document), ["minds#6:mind-3/mind-name"]);
}
#[test]
fn a_fault_is_said_once() {
let mut state = swarm_state();
state.put_state(&ProviderId::new(SWARM), "summary", &SwarmRenamed { id: "summary".into(), name: "Swarm".into(), burden: 0.4 });
let mut rig = Rig::new(state);
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
assert_eq!(rig.bind(&document).diagnostics.len(), 1);
rig.state.put_state(&ProviderId::new(SWARM), "summary", &SwarmRenamed { id: "summary".into(), name: "Swarm".into(), burden: 0.5 });
assert_eq!(rig.settle().diagnostics, vec![]);
rig.state.put_state(&ProviderId::new(SWARM), "summary", &swarm("summary", "Swarm", 0.5));
let applied = rig.settle();
assert_eq!(applied.diagnostics, vec![]);
assert_eq!(value(rig.tree(&document), "load", Field::Content), &Bound::Text("50.0%".into()));
}
#[test]
fn interests_follow_the_tree() {
let (mut rig, document) = Rig::fixture(Fixture::F01SwarmDashboard);
let subscribes = |rig: &Rig| count_calls(&rig.state, |call| matches!(call, Call::Subscribe(_)));
let unsubscribes = |rig: &Rig| count_calls(&rig.state, |call| matches!(call, Call::Unsubscribe(_)));
rig.bind(&document);
assert_eq!(subscribes(&rig), 2);
let summary = Interest::Record(address("summary"));
let minds = Interest::Prefix(Prefix { provider: ProviderId::new(SWARM), schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "mind-".into() });
assert_eq!((rig.ledger.readers(&summary), rig.ledger.readers(&minds)), (1, 1));
// Applies do not resubscribe.
rig.state.put_state(&ProviderId::new(SWARM), "summary", &swarm("summary", "Swarm", 0.1));
rig.settle();
rig.state.put_state(&ProviderId::new(SWARM), "mind-1", &swarm("mind-1", "Eureka", 0.1));
rig.settle();
assert_eq!((subscribes(&rig), unsubscribes(&rig)), (2, 0));
// A rebind on a tree that drops the Repeat releases its prefix, and nothing else.
let mut slimmer = document.clone();
let Node::Box(root) = &mut slimmer.root else { panic!("root is a Box") };
root.children.retain(|child| !matches!(child, Node::Repeat(_)));
rig.bind(&slimmer);
assert_eq!((subscribes(&rig), unsubscribes(&rig)), (2, 1));
assert_eq!((rig.ledger.readers(&summary), rig.ledger.readers(&minds)), (1, 0));
// An unsubscribed record's arrival changes nothing.
rig.state.put_state(&ProviderId::new(SWARM), "mind-9", &swarm("mind-9", "Late", 0.0));
assert_eq!(rig.settle(), Applied::default());
}
#[test]
fn two_surfaces_share_one_subscription() {
let mut rig = Rig::new(swarm_state());
let one = page("one", vec![bound_text("a", swarm_bind("summary", vec![name("Name")], None))]);
let two = page("two", vec![bound_text("b", swarm_bind("summary", vec![name("Name")], None))]);
rig.bind(&one);
rig.bind(&two);
let summary = Interest::Record(address("summary"));
assert_eq!(count_calls(&rig.state, |call| matches!(call, Call::Subscribe(_))), 1);
assert_eq!(rig.ledger.readers(&summary), 2);
rig.binder.forget(&one.record_key(), &mut rig.state, &mut rig.ledger);
assert_eq!(count_calls(&rig.state, |call| matches!(call, Call::Unsubscribe(_))), 0);
rig.binder.forget(&two.record_key(), &mut rig.state, &mut rig.ledger);
assert_eq!(count_calls(&rig.state, |call| matches!(call, Call::Unsubscribe(_))), 1);
assert_eq!(rig.ledger.readers(&summary), 0);
// A change reaches both holders through the one subscription.
let mut rig = Rig::new(swarm_state());
rig.bind(&one);
rig.bind(&two);
rig.state.put_state(&ProviderId::new(SWARM), "summary", &swarm("summary", "Moved", 0.0));
let applied = rig.settle();
assert_eq!(nodes(&applied, &one), ["a"]);
assert_eq!(nodes(&applied, &two), ["b"]);
}
#[test]
fn binding_twice_is_the_same() {
let (mut rig, document) = Rig::fixture(Fixture::F01SwarmDashboard);
rig.bind(&document);
let first = rig.tree(&document).clone();
let calls = rig.state.calls().len();
let applied = rig.bind(&document);
assert_eq!(rig.tree(&document), &first);
assert_eq!(applied, Applied::default());
let new: Vec<Call> = rig.state.calls()[calls..].to_vec();
assert!(new.iter().all(|call| matches!(call, Call::Read(_) | Call::List(_))), "{new:?}");
}
#[test]
fn pipeline_smoke_f09() {
let mut state = MemState::from_fixture(Fixture::F09CompositionStack);
state::script(Fixture::F01SwarmDashboard, &mut state);
// The card's rows are the surface provider's records.
for (key, record) in state::swarm_records() {
state.put_state(&ProviderId::new("provider.stack"), key, &record);
}
let mut rig = Rig::new(state);
let document = Fixture::F09CompositionStack.load().surfaces.remove(0);
let applied = rig.bind(&document);
let tree = rig.tree(&document);
let rows = tree.instances(&nid("outer-card/card-rows"));
assert_eq!(rows.len(), 3);
assert_eq!(value(tree, "outer-card/card-rows#6:mind-2/outer-card/card-row", Field::Content), &Bound::Text("Libby".into()));
// The std stat's Bind argument is bound at its expanded id: Load is a number and the stat
// gives it no Format, so the site says so rather than coercing.
assert_eq!(code(value(tree, "std-stat/stat-value", Field::Content)), Code::BindTypeMismatch);
assert_eq!(applied.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [Code::BindTypeMismatch]);
}

View file

@ -0,0 +1,14 @@
load visible bool true
load content text "42.0%"
minds visible bool true
minds#6:mind-1/mind-name visible bool true
minds#6:mind-1/mind-name content text "Eureka"
minds#6:mind-2/mind-name visible bool true
minds#6:mind-2/mind-name content text "Libby"
minds#6:mind-3/mind-name visible bool true
minds#6:mind-3/mind-name content text "Kiko"
restart visible bool true
restart enabled bool true
restart-label visible bool true
restart-label content text "Restart"
root visible bool true

View file

@ -0,0 +1,11 @@
enabled visible bool true
enabled checked bool true
port visible bool true
port placeholder text "port"
port initial text "8080"
root visible bool true
theme visible bool true
theme selected text "dark"
theme options options [dark=Dark, light=Light]
volume visible bool true
volume value number 40