diff --git a/Cargo.lock b/Cargo.lock index c9fe90f..42c4049 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -386,6 +386,7 @@ name = "thing-core" version = "0.1.0" dependencies = [ "thing-contract", + "thing-testkit", ] [[package]] diff --git a/crates/thing-contract/src/lib.rs b/crates/thing-contract/src/lib.rs index 9f9d544..2edc6ed 100644 --- a/crates/thing-contract/src/lib.rs +++ b/crates/thing-contract/src/lib.rs @@ -32,6 +32,7 @@ pub use result::*; pub use source::*; pub use style::*; +pub use cultcache_rs::DatabaseEntry; use cultcache_rs::{CultCache, CultCacheRegistry}; /// Registers the five kinds with a cache. diff --git a/crates/thing-contract/src/node.rs b/crates/thing-contract/src/node.rs index 7a0d169..b121722 100644 --- a/crates/thing-contract/src/node.rs +++ b/crates/thing-contract/src/node.rs @@ -315,6 +315,13 @@ pub struct CompositionRef { pub version: Version, } +impl CompositionRef { + /// The record key of the composition this names, from the one key function. + pub fn record_key(&self) -> String { + composition_key(&self.publisher, &self.name, self.version) + } +} + #[derive(Clone, Debug, PartialEq, CultSlots)] pub struct UseNode { #[cultcache(key = 0)] diff --git a/crates/thing-core/Cargo.toml b/crates/thing-core/Cargo.toml index d5fb718..36ce641 100644 --- a/crates/thing-core/Cargo.toml +++ b/crates/thing-core/Cargo.toml @@ -7,3 +7,6 @@ publish = false [dependencies] thing-contract = { path = "../thing-contract" } + +[dev-dependencies] +thing-testkit = { path = "../thing-testkit" } diff --git a/crates/thing-core/src/diagnostic.rs b/crates/thing-core/src/diagnostic.rs new file mode 100644 index 0000000..7d8f174 --- /dev/null +++ b/crates/thing-core/src/diagnostic.rs @@ -0,0 +1,45 @@ +//! What core says about a document it could not take whole. The code set is closed: a later +//! cut adds its codes as reviewed changes, never as free strings. + +use thing_contract::NodeId; + +/// Why a document, or one node of it, was not taken as authored. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Code { + /// The port refused the composition's bytes. A refusal is never absence. + DecodeRefused, + /// No composition is published at the named address. + UnresolvedUse, + /// A composition that uses itself through others, or a chain deeper than the limit. + CompositionCycle, + /// An argument, a body or a composition record that does not fit its Use. + CompositionInvalid, + /// A command no surface declaration names. + UndeclaredCommand, + /// Two nodes of the expanded tree share an id. + DuplicateNodeId, + /// A Param or a Slot outside any composition. + UnboundParam, + /// The expanded tree has too many nodes or is deeper than the depth rule. + ExpansionLimit, + /// The input nests deeper than the expander can recurse. A stack bound, not the depth rule: the depth + /// rule is judged on the finished tree and reports ExpansionLimit. + TooDeepToResolve, +} + +impl Code { + /// Whether the fault leaves no tree (the whole document is refused) or only a placeholder. + pub fn refuses_document(self) -> bool { + matches!(self, Code::UndeclaredCommand | Code::DuplicateNodeId | Code::UnboundParam | Code::ExpansionLimit | Code::TooDeepToResolve) + } +} + +/// One fault. `detail` names the fault and never carries a state value. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Diagnostic { + pub code: Code, + /// The record key of the surface the fault is in. + pub surface: String, + pub node: Option, + pub detail: String, +} diff --git a/crates/thing-core/src/lib.rs b/crates/thing-core/src/lib.rs index 5b2775a..345c2dd 100644 --- a/crates/thing-core/src/lib.rs +++ b/crates/thing-core/src/lib.rs @@ -1,4 +1,6 @@ //! 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 diagnostic; pub mod port; +pub mod resolve; diff --git a/crates/thing-core/src/resolve/expand.rs b/crates/thing-core/src/resolve/expand.rs new file mode 100644 index 0000000..a6174fb --- /dev/null +++ b/crates/thing-core/src/resolve/expand.rs @@ -0,0 +1,557 @@ +//! The substitution: depth first, order preserving. A surface and a composition body go through +//! the same functions; the scope says whether a Param is bound. +//! +//! Expanded ids: inside the expansion of Use `u`, the body root takes `u`'s id and every other +//! body id `b` becomes `u/b`. Arguments are expanded in the caller's scope before the body sees +//! them, so a Slot argument's nodes keep the ids they had in the caller. + +use std::collections::{HashMap, HashSet}; + +use thing_contract::*; + +use crate::diagnostic::{Code, Diagnostic}; +use crate::port::{Address, Lookup, Record, StatePort}; + +use super::{Limits, std as thing_std, validate}; + +/// The deepest input the expander recurses into. This is a stack bound and not the depth rule: the +/// rule (`Limits::max_tree_depth`) is judged by validate on the finished tree, where a slot argument +/// the body never places does not count. It exists because an in-memory tree from a Rust caller can +/// be deeper than any decoded document (CultCache bounds decoded nesting at 256), and recursion +/// over it would overflow the stack. A level costs a few tens of KiB of stack in a debug build, so a +/// caller resolving untrusted in-memory trees needs a stack sized for this many levels. +const STACK_BOUND: usize = 1024; + +/// A fault the nearest enclosing Use turns into a placeholder (`Invalid`), or one that ends the +/// whole expansion (`Limit`, or `Stack` for input too deep to recurse into). +pub(super) enum Fault { + Invalid(String), + Limit(String), + Stack(String), +} + +type Res = Result; + +fn invalid(detail: String) -> Res { + Err(Fault::Invalid(detail)) +} + +/// The expansion of one composition body: the Use's id and common, and the finished arguments. +struct Scope { + use_id: NodeId, + root_id: NodeId, + use_visible: BoolSource, + use_a11y: Option, + args: HashMap, +} + +pub(super) struct Expander<'a> { + port: &'a dyn StatePort, + limits: &'a Limits, + surface: String, + provider: &'a ProviderId, + commands: HashSet<&'a CommandId>, + pub diagnostics: Vec, + pub reads: HashSet
, + nodes: usize, + stack: Vec, + current: Option, +} + +fn arm_name(value: &ArgValue) -> &'static str { + match value { + ArgValue::Text(_) => "Text", + ArgValue::Number(_) => "Number", + ArgValue::Bool(_) => "Bool", + ArgValue::Bind(_) => "Bind", + ArgValue::Collection(_) => "Collection", + ArgValue::Command(_) => "Command", + ArgValue::Slot(_) => "Slot", + } +} + +fn kind_name(kind: &ParamKind) -> &'static str { + match kind { + ParamKind::Text => "Text", + ParamKind::Number => "Number", + ParamKind::Bool => "Bool", + ParamKind::Bind => "Bind", + ParamKind::Collection => "Collection", + ParamKind::Command => "Command", + ParamKind::Slot => "Slot", + } +} + +fn wrong_kind(name: &ParamName, value: &ArgValue, position: &str) -> Res { + invalid(format!("param '{}' is a {} argument, used as {position}", name.name, arm_name(value))) +} + +impl<'a> Expander<'a> { + pub fn new(document: &'a SurfaceDocument, port: &'a dyn StatePort, limits: &'a Limits) -> Self { + Self { + port, + limits, + surface: document.record_key(), + provider: &document.provider_id, + commands: document.commands.iter().map(|declared| &declared.id).collect(), + diagnostics: Vec::new(), + reads: HashSet::new(), + nodes: 0, + stack: Vec::new(), + current: None, + } + } + + pub fn diag(&mut self, code: Code, node: Option, detail: impl Into) { + self.diagnostics.push(Diagnostic { code, surface: self.surface.clone(), node, detail: detail.into() }); + } + + fn unbound(&mut self, what: &str) { + let node = self.current.clone(); + self.diag(Code::UnboundParam, node, format!("{what} outside a composition")); + } + + /// The surface root: no scope, no Use above it. + pub fn root(&mut self, root: &Node) -> Res { + self.node(root, None, 1, false) + } + + // ---- positions ---------------------------------------------------------------------- + + fn id(&self, id: &NodeId, scope: Option<&Scope>) -> NodeId { + match scope { + None => id.clone(), + Some(scope) if *id == scope.root_id => scope.use_id.clone(), + Some(scope) => NodeId::new(format!("{}/{}", scope.use_id.as_str(), id.as_str())), + } + } + + fn fill(&self, provider: &Option) -> Option { + Some(provider.clone().unwrap_or_else(|| self.provider.clone())) + } + + fn bind(&self, bind: &Bind) -> Bind { + let source = match &bind.source { + StateSource::Record(state) => StateSource::Record(StateRef { + provider: self.fill(&state.provider), + schema: state.schema.clone(), + key: state.key.clone(), + }), + StateSource::Item => StateSource::Item, + }; + Bind { source, member: bind.member.clone(), format: bind.format.clone() } + } + + fn arg_of<'s>(name: &ParamName, scope: &'s Scope) -> Res<&'s ArgValue> { + match scope.args.get(&name.name) { + Some(value) => Ok(value), + None => invalid(format!("the body names param '{}', which the composition does not declare", name.name)), + } + } + + fn text(&mut self, source: &TextSource, scope: Option<&Scope>) -> Res { + Ok(match (source, scope) { + (TextSource::Literal(_), _) => source.clone(), + (TextSource::Bound(bind), _) => TextSource::Bound(self.bind(bind)), + (TextSource::Param(name), None) => { + self.unbound(&format!("param '{}'", name.name)); + source.clone() + } + (TextSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? { + ArgValue::Text(arg) => TextSource::Literal(TextLiteral { value: arg.value.clone() }), + ArgValue::Bind(bind) => TextSource::Bound(bind.clone()), + other => return wrong_kind(name, other, "text"), + }, + }) + } + + fn number(&mut self, source: &NumberSource, scope: Option<&Scope>) -> Res { + Ok(match (source, scope) { + (NumberSource::Literal(_), _) => source.clone(), + (NumberSource::Bound(bind), _) => NumberSource::Bound(self.bind(bind)), + (NumberSource::Param(name), None) => { + self.unbound(&format!("param '{}'", name.name)); + source.clone() + } + (NumberSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? { + ArgValue::Number(arg) => NumberSource::Literal(NumberLiteral { value: arg.value }), + ArgValue::Bind(bind) => NumberSource::Bound(bind.clone()), + other => return wrong_kind(name, other, "a number"), + }, + }) + } + + fn boolean(&mut self, source: &BoolSource, scope: Option<&Scope>) -> Res { + Ok(match (source, scope) { + (BoolSource::Literal(_), _) => source.clone(), + (BoolSource::Bound(bind), _) => BoolSource::Bound(self.bind(bind)), + (BoolSource::Param(name), None) => { + self.unbound(&format!("param '{}'", name.name)); + source.clone() + } + (BoolSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? { + ArgValue::Bool(arg) => BoolSource::Literal(BoolLiteral { value: arg.value }), + ArgValue::Bind(bind) => BoolSource::Bound(bind.clone()), + other => return wrong_kind(name, other, "a bool"), + }, + }) + } + + /// Substitution only: the form an argument takes, before any position judges it. + fn subst_collection(&mut self, source: &CollectionSource, scope: Option<&Scope>) -> Res { + Ok(match (source, scope) { + (CollectionSource::Records(records), _) => CollectionSource::Records(RecordsSource { + provider: self.fill(&records.provider), + schema: records.schema.clone(), + key_prefix: records.key_prefix.clone(), + }), + (CollectionSource::Member(bind), _) => CollectionSource::Member(self.bind(bind)), + (CollectionSource::Param(_), None) => source.clone(), + (CollectionSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? { + ArgValue::Collection(arg) => arg.source.clone(), + other => return wrong_kind(name, other, "a collection"), + }, + }) + } + + fn collection(&mut self, source: &CollectionSource, scope: Option<&Scope>) -> Res { + let found = self.subst_collection(source, scope)?; + if let CollectionSource::Param(name) = &found { + self.unbound(&format!("param '{}'", name.name)); + } + Ok(found) + } + + fn subst_command(&mut self, command: &CommandRef, scope: Option<&Scope>) -> Res { + Ok(match (command, scope) { + (_, None) => command.clone(), + (CommandRef::Id(id), Some(_)) => { + return invalid(format!( + "the body names command '{}'; a composition takes its commands as params", + id.id.as_str() + )); + } + (CommandRef::Param(name), Some(scope)) => match Self::arg_of(name, scope)? { + ArgValue::Command(arg) => arg.command.clone(), + other => return wrong_kind(name, other, "a command"), + }, + }) + } + + /// A command at its final position: declared by the surface, and no Param. + fn command(&mut self, command: &CommandRef, scope: Option<&Scope>) -> Res { + let found = self.subst_command(command, scope)?; + match &found { + CommandRef::Id(id) if !self.commands.contains(&id.id) => { + let node = self.current.clone(); + self.diag(Code::UndeclaredCommand, node, format!("command '{}' is not declared", id.id.as_str())); + } + CommandRef::Param(name) => self.unbound(&format!("param '{}'", name.name)), + CommandRef::Id(_) => {} + } + Ok(found) + } + + fn common(&mut self, common: &NodeCommon, scope: Option<&Scope>, root: bool) -> Res { + let id = self.id(&common.id, scope); + self.current = Some(id.clone()); + match scope { + // A body root is the Use: its id, and its visibility and label unless the body labels it. + Some(scope) if root => { + if common.visible != BoolSource::Literal(BoolLiteral { value: true }) { + return invalid("the body root's visible is not the literal true; visibility is the Use's".into()); + } + let a11y_label = match (&scope.use_a11y, &common.a11y_label) { + (Some(label), _) => Some(label.clone()), + (None, Some(label)) => Some(self.text(label, Some(scope))?), + (None, None) => None, + }; + Ok(NodeCommon { id, visible: scope.use_visible.clone(), a11y_label }) + } + _ => { + let visible = self.boolean(&common.visible, scope)?; + let a11y_label = common.a11y_label.as_ref().map(|label| self.text(label, scope)).transpose()?; + Ok(NodeCommon { id, visible, a11y_label }) + } + } + } + + // ---- nodes -------------------------------------------------------------------------- + + fn count(&mut self, added: usize) -> Res<()> { + self.nodes += added; + if self.nodes > self.limits.max_nodes { + return Err(Fault::Limit(format!("the expansion passed {} nodes", self.limits.max_nodes))); + } + Ok(()) + } + + /// A child list. In a composition body a Slot is replaced by the nodes passed for it. + fn children(&mut self, list: &[Node], scope: Option<&Scope>, depth: usize) -> Res> { + let mut out = Vec::with_capacity(list.len()); + for node in list { + match (node, scope) { + (Node::Slot(slot), Some(scope)) => match Self::arg_of(&slot.param, scope)? { + ArgValue::Slot(arg) => { + self.count(arg.nodes.iter().map(validate::size).sum())?; + out.extend(arg.nodes.iter().cloned()); + } + other => return wrong_kind(&slot.param, other, "a slot"), + }, + _ => out.push(self.node(node, scope, depth, false)?), + } + } + Ok(out) + } + + fn node(&mut self, node: &Node, scope: Option<&Scope>, depth: usize, root: bool) -> Res { + if depth > STACK_BOUND { + return Err(Fault::Stack(format!("the input nests deeper than {STACK_BOUND} levels"))); + } + self.count(1)?; + // Each arm settles its own positions first and its child lists last: a diagnostic names the + // node being expanded, and a child list moves `current` on. + Ok(match node { + Node::Slot(slot) => match scope { + Some(_) => { + return invalid(format!( + "Slot '{}' is not in a child list of the body; a slot stands only in Box.children, \ + Button.content or Overlay.children", + slot.param.name + )); + } + None => { + self.current = None; + self.unbound(&format!("Slot '{}'", slot.param.name)); + node.clone() + } + }, + Node::Use(used) => self.expand_use(used, scope, depth, root)?, + Node::Box(b) => { + let common = self.common(&b.common, scope, root)?; + let children = self.children(&b.children, scope, depth + 1)?; + Node::Box(BoxNode { common, style: b.style.clone(), paint: b.paint.clone(), role: b.role.clone(), children }) + } + Node::Text(t) => { + let common = self.common(&t.common, scope, root)?; + let content = self.text(&t.content, scope)?; + Node::Text(TextNode { common, content, ..t.clone() }) + } + Node::Image(i) => { + let common = self.common(&i.common, scope, root)?; + let alt = self.text(&i.alt, scope)?; + Node::Image(ImageNode { common, alt, ..i.clone() }) + } + Node::Button(b) => { + let common = self.common(&b.common, scope, root)?; + let on_activate = self.command(&b.on_activate, scope)?; + let enabled = self.boolean(&b.enabled, scope)?; + let content = self.children(&b.content, scope, depth + 1)?; + Node::Button(ButtonNode { common, content, on_activate, enabled }) + } + Node::Toggle(t) => { + let common = self.common(&t.common, scope, root)?; + let checked = self.boolean(&t.checked, scope)?; + let on_change = self.command(&t.on_change, scope)?; + Node::Toggle(ToggleNode { common, checked, on_change }) + } + Node::Slider(s) => { + let common = self.common(&s.common, scope, root)?; + let value = self.number(&s.value, scope)?; + let commit = self.command(&s.commit, scope)?; + Node::Slider(SliderNode { common, value, commit, ..s.clone() }) + } + Node::TextInput(t) => { + let common = self.common(&t.common, scope, root)?; + let placeholder = self.text(&t.placeholder, scope)?; + let initial = self.text(&t.initial, scope)?; + let submit = self.command(&t.submit, scope)?; + Node::TextInput(TextInputNode { common, placeholder, initial, submit, ..t.clone() }) + } + Node::Select(s) => { + let common = self.common(&s.common, scope, root)?; + let options = match &s.options { + OptionList::Literal(_) => s.options.clone(), + OptionList::Bound(bound) => OptionList::Bound(BoundOptions { + collection: self.collection(&bound.collection, scope)?, + value_member: bound.value_member.clone(), + label_member: bound.label_member.clone(), + }), + }; + let value = self.bind(&s.value); + let on_change = self.command(&s.on_change, scope)?; + Node::Select(SelectNode { common, options, value, on_change }) + } + Node::Repeat(r) => { + let common = self.common(&r.common, scope, root)?; + let collection = self.collection(&r.collection, scope)?; + let template = std::boxed::Box::new(self.node(&r.template, scope, depth + 1, false)?); + Node::Repeat(RepeatNode { common, collection, key_member: r.key_member.clone(), template }) + } + Node::Overlay(o) => { + let common = self.common(&o.common, scope, root)?; + let anchor = match &o.anchor { + Anchor::Viewport => Anchor::Viewport, + Anchor::Node(anchor) => Anchor::Node(AnchorNode { node: self.id(&anchor.node, scope) }), + }; + let dismiss = self.command(&o.dismiss, scope)?; + let children = self.children(&o.children, scope, depth + 1)?; + Node::Overlay(OverlayNode { common, anchor, modal: o.modal, dismiss, children }) + } + Node::Plot(p) => { + let common = self.common(&p.common, scope, root)?; + Node::Plot(PlotNode { common, series: self.bind(&p.series), ..p.clone() }) + } + Node::Embed(e) => { + let common = self.common(&e.common, scope, root)?; + Node::Embed(EmbedNode { common, ..e.clone() }) + } + }) + } + + // ---- compositions ------------------------------------------------------------------- + + fn load(&mut self, reference: &CompositionRef) -> Result { + let name = format!("{}.{}.v{}", reference.publisher, reference.name.as_str(), reference.version.get()); + if reference.publisher == thing_std::PUBLISHER { + return thing_std::lookup(reference.name.as_str(), reference.version) + .ok_or((Code::UnresolvedUse, format!("no compiled-in composition {name}"))); + } + let address = Address { + provider: ProviderId::new(reference.publisher.clone()), + schema: SchemaId::new(CompositionDocument::SCHEMA_NAME), + key: RecordKey::new(reference.record_key()), + }; + self.reads.insert(address.clone()); + match self.port.read(&address) { + Lookup::Present(entry) => match entry.record { + Record::Composition(composition) => Ok(composition), + _ => Err((Code::CompositionInvalid, format!("the record at {name} is not a composition"))), + }, + Lookup::Absent => Err((Code::UnresolvedUse, format!("no composition published at {name}"))), + Lookup::Refused(refusal) => Err((Code::DecodeRefused, format!("{name}: {}", refusal.detail))), + } + } + + /// The first thing wrong with the composition against its Use, if anything. + fn misfit(reference: &CompositionRef, composition: &CompositionDocument, args: &[Arg]) -> Option { + if composition.publisher != reference.publisher + || composition.name != reference.name + || composition.version != reference.version + { + return Some("the composition record's publisher, name or version differs from the Use's reference".into()); + } + let mut declared: HashMap<&str, &ParamKind> = HashMap::new(); + for param in &composition.params { + if declared.insert(¶m.name, ¶m.kind).is_some() { + return Some(format!("the composition declares param '{}' twice", param.name)); + } + } + let mut given: HashSet<&str> = HashSet::new(); + for arg in args { + if !given.insert(&arg.name) { + return Some(format!("argument '{}' is given twice", arg.name)); + } + match declared.get(arg.name.as_str()) { + None => return Some(format!("argument '{}' names no param of the composition", arg.name)), + Some(kind) if kind_name(kind) != arm_name(&arg.value) => { + return Some(format!( + "argument '{}' is a {} but the param is a {}", + arg.name, + arm_name(&arg.value), + kind_name(kind) + )); + } + Some(_) => {} + } + } + composition + .params + .iter() + .find(|param| !given.contains(param.name.as_str())) + .map(|param| format!("param '{}' has no argument", param.name)) + } + + /// An argument in the caller's scope: the form the body will place. + fn arg(&mut self, value: &ArgValue, scope: Option<&Scope>, depth: usize) -> Res { + Ok(match value { + ArgValue::Text(_) | ArgValue::Number(_) | ArgValue::Bool(_) => value.clone(), + ArgValue::Bind(bind) => ArgValue::Bind(self.bind(bind)), + ArgValue::Collection(arg) => { + ArgValue::Collection(CollectionArg { source: self.subst_collection(&arg.source, scope)? }) + } + ArgValue::Command(arg) => ArgValue::Command(CommandArg { command: self.subst_command(&arg.command, scope)? }), + ArgValue::Slot(arg) => ArgValue::Slot(SlotArg { nodes: self.children(&arg.nodes, scope, depth + 1)? }), + }) + } + + fn expand_use(&mut self, used: &UseNode, scope: Option<&Scope>, depth: usize, root: bool) -> Res { + let common = self.common(&used.common, scope, root)?; + let here = common.id.clone(); + let reference = &used.composition; + let placeholder = |common: NodeCommon| Node::Use(UseNode { common, composition: reference.clone(), args: vec![] }); + + let repeats = self.stack.contains(reference); + if repeats || self.stack.len() >= self.limits.max_use_depth { + let why = if repeats { "uses itself" } else { "is nested too deep" }; + self.diag(Code::CompositionCycle, Some(here), format!("the composition {why}")); + return Ok(placeholder(common)); + } + let composition = match self.load(reference) { + Ok(composition) => composition, + Err((code, detail)) => { + self.diag(code, Some(here), detail); + return Ok(placeholder(common)); + } + }; + if let Some(detail) = Self::misfit(reference, &composition, &used.args) { + self.diag(Code::CompositionInvalid, Some(here), detail); + return Ok(placeholder(common)); + } + + let mark = self.diagnostics.len(); + let mut args = HashMap::new(); + for arg in &used.args { + args.insert(arg.name.clone(), self.arg(&arg.value, scope, depth)?); + } + let inner = Scope { + use_id: here.clone(), + root_id: body_id(&composition.body), + use_visible: common.visible.clone(), + use_a11y: common.a11y_label.clone(), + args, + }; + self.stack.push(reference.clone()); + let expanded = self.node(&composition.body, Some(&inner), depth, true); + self.stack.pop(); + match expanded { + Ok(node) => Ok(node), + Err(Fault::Invalid(detail)) => { + self.diagnostics.truncate(mark); + self.diag(Code::CompositionInvalid, Some(here), detail); + Ok(placeholder(common)) + } + Err(limit) => Err(limit), + } + } +} + +/// The id of a body root. A Slot has none, and the body fails on it before an id is read. +fn body_id(node: &Node) -> NodeId { + match node { + Node::Box(n) => n.common.id.clone(), + Node::Text(n) => n.common.id.clone(), + Node::Image(n) => n.common.id.clone(), + Node::Button(n) => n.common.id.clone(), + Node::Toggle(n) => n.common.id.clone(), + Node::Slider(n) => n.common.id.clone(), + Node::TextInput(n) => n.common.id.clone(), + Node::Select(n) => n.common.id.clone(), + Node::Repeat(n) => n.common.id.clone(), + Node::Overlay(n) => n.common.id.clone(), + Node::Plot(n) => n.common.id.clone(), + Node::Embed(n) => n.common.id.clone(), + Node::Use(n) => n.common.id.clone(), + Node::Slot(_) => NodeId::new(""), + } +} diff --git a/crates/thing-core/src/resolve/mod.rs b/crates/thing-core/src/resolve/mod.rs new file mode 100644 index 0000000..13d827e --- /dev/null +++ b/crates/thing-core/src/resolve/mod.rs @@ -0,0 +1,87 @@ +//! Resolve: the pure expansion of a surface document into a tree with no composition left in it. +//! This is the only code that reads Thing Script structure (Use, Param, CommandRef, node ids). +//! It reads compositions through `StatePort::read` and `thing.std` from a compiled-in table, +//! holds no state, subscribes to nothing and never drains. + +mod expand; +pub mod std; +mod validate; + +use thing_contract::SurfaceDocument; + +use crate::diagnostic::{Code, Diagnostic}; +use crate::port::{Address, StatePort}; + +/// The bounds of one expansion. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Limits { + /// Compositions nested in one another; a Use deeper than this is a placeholder. + pub max_use_depth: usize, + /// The contract's decode bound; a deeper expanded tree is refused. + pub max_tree_depth: usize, + /// Nodes in the expanded tree; more is refused. + pub max_nodes: usize, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_use_depth: 32, max_tree_depth: 256, max_nodes: 65_536 } + } +} + +/// A surface document expanded: no Param of any kind remains, every command is declared, every +/// state reference names its provider, node ids are unique, and a Use remains only as a +/// placeholder leaf (its arguments emptied) beside a diagnostic. Only `resolve` builds one. +#[derive(Clone, Debug, PartialEq)] +pub struct ResolvedTree { + document: SurfaceDocument, +} + +impl ResolvedTree { + pub fn document(&self) -> &SurfaceDocument { + &self.document + } +} + +/// What one expansion found. `tree` is `None` when a fault refuses the whole document. +#[derive(Clone, Debug, PartialEq)] +pub struct Resolution { + pub tree: Option, + /// Expansion faults in expansion pre-order, then the finished tree's faults (duplicate ids, depth) + /// in tree pre-order. + pub diagnostics: Vec, + /// Every non-std composition address consulted, whether present, absent or refused, once each, ordered + /// by provider, schema and key. + pub reads: Vec
, +} + +pub fn resolve(document: &SurfaceDocument, port: &dyn StatePort, limits: &Limits) -> Resolution { + let mut expander = expand::Expander::new(document, port, limits); + let root = match expander.root(&document.root) { + Ok(root) => Some(root), + Err(expand::Fault::Limit(detail)) => { + expander.diag(Code::ExpansionLimit, None, detail); + None + } + Err(expand::Fault::Stack(detail)) => { + expander.diag(Code::TooDeepToResolve, None, detail); + None + } + Err(expand::Fault::Invalid(detail)) => { + expander.diag(Code::CompositionInvalid, None, detail); + None + } + }; + let mut diagnostics = ::std::mem::take(&mut expander.diagnostics); + let mut reads: Vec
= ::std::mem::take(&mut expander.reads).into_iter().collect(); + reads.sort_by(|a, b| { + let key = |address: &Address| (address.provider.as_str().to_string(), address.schema.as_str().to_string(), address.key.as_str().to_string()); + key(a).cmp(&key(b)) + }); + let tree = root.and_then(|root| { + diagnostics.extend(validate::check(&root, limits, &document.record_key())); + let refused = diagnostics.iter().any(|diagnostic| diagnostic.code.refuses_document()); + (!refused).then(|| ResolvedTree { document: SurfaceDocument { root, ..document.clone() } }) + }); + Resolution { tree, diagnostics, reads } +} diff --git a/crates/thing-core/src/resolve/std.rs b/crates/thing-core/src/resolve/std.rs new file mode 100644 index 0000000..e5b6f1c --- /dev/null +++ b/crates/thing-core/src/resolve/std.rs @@ -0,0 +1,95 @@ +//! `thing.std`: the compositions compiled into core. The port is never asked for this +//! publisher, so no provider can shadow one. + +use thing_contract::*; + +/// The publisher whose compositions are compiled in. +pub const PUBLISHER: &str = "thing.std"; + +/// Every compiled-in composition. +pub fn all() -> Vec { + vec![stat(), card()] +} + +pub(super) fn lookup(name: &str, version: Version) -> Option { + all().into_iter().find(|composition| composition.name.as_str() == name && composition.version == version) +} + +fn segment(name: &str) -> Segment { + Segment::new(name).expect("a std name is a segment") +} + +fn common(id: &str) -> NodeCommon { + NodeCommon { id: NodeId::new(id), visible: BoolSource::Literal(BoolLiteral { value: true }), a11y_label: None } +} + +fn text(id: &str, content: TextSource, style_token: &str) -> Node { + Node::Text(TextNode { + common: common(id), + content, + style_token: style_token.into(), + wrap: true, + max_lines: None, + selectable: false, + }) +} + +fn param(name: &str) -> ParamName { + ParamName { name: name.into() } +} + +fn column(id: &str, children: Vec) -> Node { + let zero = || Dimension::Px(Scalar { value: 0.0 }); + let auto = || Dimension::Auto; + let size = |width, height| Size2 { width, height }; + let edges = |all: Dimension| Edges { top: all.clone(), right: all.clone(), bottom: all.clone(), left: all }; + let style = BoxStyle { + display: Display::Flex, + direction: Direction::Column, + wrap: Wrap::NoWrap, + gap: size(zero(), Dimension::Px(Scalar { value: 4.0 })), + padding: edges(zero()), + margin: edges(zero()), + size: size(auto(), Dimension::Content), + min_size: size(zero(), zero()), + max_size: size(auto(), auto()), + position: Position::Relative, + inset: edges(auto()), + overflow: Overflow::Visible, + align_items: ItemAlign::Stretch, + align_self: ItemAlign::Auto, + align_content: ContentAlign::Start, + justify_content: ContentAlign::Start, + grow: 0.0, + shrink: 1.0, + basis: Dimension::Auto, + grid_columns: vec![], + grid_rows: vec![], + }; + let paint = Paint { background: None, border: None, radius: 0.0 }; + Node::Box(BoxNode { common: common(id), style, paint, role: Role::Group, children }) +} + +fn composition(name: &str, params: &[(&str, ParamKind)], body: Node) -> CompositionDocument { + CompositionDocument { + publisher: PUBLISHER.into(), + name: segment(name), + version: Version::new(1).expect("version 1"), + params: params.iter().map(|(name, kind)| ParamDecl { name: (*name).into(), kind: kind.clone() }).collect(), + body, + } +} + +/// A label over a bound value. +fn stat() -> CompositionDocument { + let label = text("stat-label", TextSource::Param(param("label")), "caption"); + let value = text("stat-value", TextSource::Param(param("value")), "title"); + composition("stat", &[("label", ParamKind::Text), ("value", ParamKind::Bind)], column("stat-root", vec![label, value])) +} + +/// A title over the nodes passed for `body`. +fn card() -> CompositionDocument { + let title = text("card-title", TextSource::Param(param("title")), "title"); + let slot = Node::Slot(SlotNode { param: param("body") }); + composition("card", &[("title", ParamKind::Text), ("body", ParamKind::Slot)], column("card-root", vec![title, slot])) +} diff --git a/crates/thing-core/src/resolve/validate.rs b/crates/thing-core/src/resolve/validate.rs new file mode 100644 index 0000000..1357cde --- /dev/null +++ b/crates/thing-core/src/resolve/validate.rs @@ -0,0 +1,75 @@ +//! The one pass over the finished tree: ids unique, and the tree within its depth limit (a slot's +//! nodes are placed deeper than expand saw them). Commands, Params and Slots are judged where they +//! land and the node count is expand's alone (it must stop before it builds a tree it would refuse). + +use std::collections::HashSet; + +use thing_contract::{Node, NodeId}; + +use super::Limits; +use crate::diagnostic::{Code, Diagnostic}; + +/// The child nodes of a node, in order. +fn children(node: &Node) -> &[Node] { + match node { + Node::Box(b) => &b.children, + Node::Button(b) => &b.content, + Node::Overlay(o) => &o.children, + Node::Repeat(r) => std::slice::from_ref(&*r.template), + _ => &[], + } +} + +fn id(node: &Node) -> Option<&NodeId> { + match node { + Node::Box(n) => Some(&n.common.id), + Node::Text(n) => Some(&n.common.id), + Node::Image(n) => Some(&n.common.id), + Node::Button(n) => Some(&n.common.id), + Node::Toggle(n) => Some(&n.common.id), + Node::Slider(n) => Some(&n.common.id), + Node::TextInput(n) => Some(&n.common.id), + Node::Select(n) => Some(&n.common.id), + Node::Repeat(n) => Some(&n.common.id), + Node::Overlay(n) => Some(&n.common.id), + Node::Plot(n) => Some(&n.common.id), + Node::Embed(n) => Some(&n.common.id), + Node::Use(n) => Some(&n.common.id), + Node::Slot(_) => None, + } +} + +/// Nodes in the subtree, the node itself included. +pub(super) fn size(node: &Node) -> usize { + 1 + children(node).iter().map(size).sum::() +} + +/// Faults of the finished tree, in pre-order: duplicate ids, then depth. A tree deeper than the limit is not walked further. +pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec { + let mut found = Vec::new(); + let fault = |code, node: Option<&NodeId>, detail: String| Diagnostic { + code, + surface: surface.to_string(), + node: node.cloned(), + detail, + }; + let mut seen: HashSet<&NodeId> = HashSet::new(); + let mut too_deep = false; + let mut stack = vec![(root, 1usize)]; + while let Some((node, depth)) = stack.pop() { + if depth > limits.max_tree_depth { + too_deep = true; + continue; + } + if let Some(id) = id(node) { + if !seen.insert(id) { + found.push(fault(Code::DuplicateNodeId, Some(id), format!("node id '{}' occurs twice", id.as_str()))); + } + } + stack.extend(children(node).iter().rev().map(|child| (child, depth + 1))); + } + if too_deep { + found.push(fault(Code::ExpansionLimit, None, format!("the tree is deeper than {} levels", limits.max_tree_depth))); + } + found +} diff --git a/crates/thing-core/tests/goldens/README.md b/crates/thing-core/tests/goldens/README.md new file mode 100644 index 0000000..af12c1d --- /dev/null +++ b/crates/thing-core/tests/goldens/README.md @@ -0,0 +1,6 @@ +# thing-core goldens + +`resolve-*.bin` is a CultCache single-file store holding one resolved surface document under the +pinned clock; `resolve-*.txt` is the `{:#?}` text of the same document. The binary is the oracle and +the text is compared beside it. `THING_BLESS=1` through `thing_testkit::golden::check_with_text` is +the only way either changes. diff --git a/crates/thing-core/tests/goldens/resolve-f09-composition-stack.bin b/crates/thing-core/tests/goldens/resolve-f09-composition-stack.bin new file mode 100644 index 0000000..259dc2c Binary files /dev/null and b/crates/thing-core/tests/goldens/resolve-f09-composition-stack.bin differ diff --git a/crates/thing-core/tests/goldens/resolve-f09-composition-stack.txt b/crates/thing-core/tests/goldens/resolve-f09-composition-stack.txt new file mode 100644 index 0000000..671d184 --- /dev/null +++ b/crates/thing-core/tests/goldens/resolve-f09-composition-stack.txt @@ -0,0 +1,864 @@ +SurfaceDocument { + provider_id: ProviderId( + "provider.stack", + ), + label: Segment( + "stack", + ), + version: Version( + 1, + ), + title: "Stack", + root: Box( + BoxNode { + common: NodeCommon { + id: NodeId( + "root", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + style: BoxStyle { + display: Flex, + direction: Column, + wrap: NoWrap, + gap: Size2 { + width: Px( + Scalar { + value: 4.0, + }, + ), + height: Px( + Scalar { + value: 8.0, + }, + ), + }, + padding: Edges { + top: Px( + Scalar { + value: 2.0, + }, + ), + right: Px( + Scalar { + value: 2.0, + }, + ), + bottom: Px( + Scalar { + value: 2.0, + }, + ), + left: Px( + Scalar { + value: 2.0, + }, + ), + }, + margin: Edges { + top: Auto, + right: Auto, + bottom: Auto, + left: Auto, + }, + size: Size2 { + width: Percent( + Scalar { + value: 100.0, + }, + ), + height: Content, + }, + min_size: Size2 { + width: Px( + Scalar { + value: 0.0, + }, + ), + height: Px( + Scalar { + value: 0.0, + }, + ), + }, + max_size: Size2 { + width: Auto, + height: Auto, + }, + position: Relative, + inset: Edges { + top: Auto, + right: Auto, + bottom: Auto, + left: Auto, + }, + overflow: Visible, + align_items: Stretch, + align_self: Auto, + align_content: Start, + justify_content: SpaceBetween, + grow: 1.0, + shrink: 0.0, + basis: Auto, + grid_columns: [], + grid_rows: [], + }, + paint: Paint { + background: None, + border: None, + radius: 0.0, + }, + role: Group, + children: [ + Box( + BoxNode { + common: NodeCommon { + id: NodeId( + "std-stat", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + style: BoxStyle { + display: Flex, + direction: Column, + wrap: NoWrap, + gap: Size2 { + width: Px( + Scalar { + value: 0.0, + }, + ), + height: Px( + Scalar { + value: 4.0, + }, + ), + }, + padding: Edges { + top: Px( + Scalar { + value: 0.0, + }, + ), + right: Px( + Scalar { + value: 0.0, + }, + ), + bottom: Px( + Scalar { + value: 0.0, + }, + ), + left: Px( + Scalar { + value: 0.0, + }, + ), + }, + margin: Edges { + top: Px( + Scalar { + value: 0.0, + }, + ), + right: Px( + Scalar { + value: 0.0, + }, + ), + bottom: Px( + Scalar { + value: 0.0, + }, + ), + left: Px( + Scalar { + value: 0.0, + }, + ), + }, + size: Size2 { + width: Auto, + height: Content, + }, + min_size: Size2 { + width: Px( + Scalar { + value: 0.0, + }, + ), + height: Px( + Scalar { + value: 0.0, + }, + ), + }, + max_size: Size2 { + width: Auto, + height: Auto, + }, + position: Relative, + inset: Edges { + top: Auto, + right: Auto, + bottom: Auto, + left: Auto, + }, + overflow: Visible, + align_items: Stretch, + align_self: Auto, + align_content: Start, + justify_content: Start, + grow: 0.0, + shrink: 1.0, + basis: Auto, + grid_columns: [], + grid_rows: [], + }, + paint: Paint { + background: None, + border: None, + radius: 0.0, + }, + role: Group, + children: [ + Text( + TextNode { + common: NodeCommon { + id: NodeId( + "std-stat/stat-label", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + content: Literal( + TextLiteral { + value: "Load", + }, + ), + style_token: "caption", + wrap: true, + max_lines: None, + selectable: false, + }, + ), + Text( + TextNode { + common: NodeCommon { + id: NodeId( + "std-stat/stat-value", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + content: Bound( + Bind { + source: Record( + StateRef { + provider: Some( + ProviderId( + "provider.swarm", + ), + ), + schema: SchemaId( + "gamecult.thing.test.swarm.v1", + ), + key: RecordKey( + "summary", + ), + }, + ), + member: MemberPath { + steps: [ + Name( + MemberName { + name: "load", + }, + ), + ], + }, + format: None, + }, + ), + style_token: "title", + wrap: true, + max_lines: None, + selectable: false, + }, + ), + ], + }, + ), + Box( + BoxNode { + common: NodeCommon { + id: NodeId( + "outer-card", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + style: BoxStyle { + display: Flex, + direction: Column, + wrap: NoWrap, + gap: Size2 { + width: Px( + Scalar { + value: 4.0, + }, + ), + height: Px( + Scalar { + value: 8.0, + }, + ), + }, + padding: Edges { + top: Px( + Scalar { + value: 2.0, + }, + ), + right: Px( + Scalar { + value: 2.0, + }, + ), + bottom: Px( + Scalar { + value: 2.0, + }, + ), + left: Px( + Scalar { + value: 2.0, + }, + ), + }, + margin: Edges { + top: Auto, + right: Auto, + bottom: Auto, + left: Auto, + }, + size: Size2 { + width: Percent( + Scalar { + value: 100.0, + }, + ), + height: Content, + }, + min_size: Size2 { + width: Px( + Scalar { + value: 0.0, + }, + ), + height: Px( + Scalar { + value: 0.0, + }, + ), + }, + max_size: Size2 { + width: Auto, + height: Auto, + }, + position: Relative, + inset: Edges { + top: Auto, + right: Auto, + bottom: Auto, + left: Auto, + }, + overflow: Visible, + align_items: Stretch, + align_self: Auto, + align_content: Start, + justify_content: SpaceBetween, + grow: 1.0, + shrink: 0.0, + basis: Auto, + grid_columns: [], + grid_rows: [], + }, + paint: Paint { + background: None, + border: None, + radius: 0.0, + }, + role: Group, + children: [ + Text( + TextNode { + common: NodeCommon { + id: NodeId( + "outer-card/card-title", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + content: Literal( + TextLiteral { + value: "Card", + }, + ), + style_token: "title", + wrap: true, + max_lines: None, + selectable: false, + }, + ), + Repeat( + RepeatNode { + common: NodeCommon { + id: NodeId( + "outer-card/card-rows", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + collection: Records( + RecordsSource { + provider: Some( + ProviderId( + "provider.stack", + ), + ), + schema: SchemaId( + "gamecult.thing.test.swarm.v1", + ), + key_prefix: "mind-", + }, + ), + key_member: MemberPath { + steps: [ + Name( + MemberName { + name: "id", + }, + ), + ], + }, + template: Text( + TextNode { + common: NodeCommon { + id: NodeId( + "outer-card/card-row", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + content: Bound( + Bind { + source: Item, + member: MemberPath { + steps: [ + Name( + MemberName { + name: "name", + }, + ), + ], + }, + format: None, + }, + ), + style_token: "body", + wrap: false, + max_lines: None, + selectable: false, + }, + ), + }, + ), + Button( + ButtonNode { + common: NodeCommon { + id: NodeId( + "outer-card/card-act", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + content: [ + Text( + TextNode { + common: NodeCommon { + id: NodeId( + "outer-card/card-act-label", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + content: Literal( + TextLiteral { + value: "Open", + }, + ), + style_token: "body", + wrap: true, + max_lines: None, + selectable: false, + }, + ), + ], + on_activate: Id( + CommandIdRef { + id: CommandId( + "open", + ), + }, + ), + enabled: Literal( + BoolLiteral { + value: true, + }, + ), + }, + ), + Box( + BoxNode { + common: NodeCommon { + id: NodeId( + "inner-card", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + style: BoxStyle { + display: Flex, + direction: Column, + wrap: NoWrap, + gap: Size2 { + width: Px( + Scalar { + value: 4.0, + }, + ), + height: Px( + Scalar { + value: 8.0, + }, + ), + }, + padding: Edges { + top: Px( + Scalar { + value: 2.0, + }, + ), + right: Px( + Scalar { + value: 2.0, + }, + ), + bottom: Px( + Scalar { + value: 2.0, + }, + ), + left: Px( + Scalar { + value: 2.0, + }, + ), + }, + margin: Edges { + top: Auto, + right: Auto, + bottom: Auto, + left: Auto, + }, + size: Size2 { + width: Percent( + Scalar { + value: 100.0, + }, + ), + height: Content, + }, + min_size: Size2 { + width: Px( + Scalar { + value: 0.0, + }, + ), + height: Px( + Scalar { + value: 0.0, + }, + ), + }, + max_size: Size2 { + width: Auto, + height: Auto, + }, + position: Relative, + inset: Edges { + top: Auto, + right: Auto, + bottom: Auto, + left: Auto, + }, + overflow: Visible, + align_items: Stretch, + align_self: Auto, + align_content: Start, + justify_content: SpaceBetween, + grow: 1.0, + shrink: 0.0, + basis: Auto, + grid_columns: [], + grid_rows: [], + }, + paint: Paint { + background: None, + border: None, + radius: 0.0, + }, + role: Group, + children: [ + Text( + TextNode { + common: NodeCommon { + id: NodeId( + "inner-card/card-title", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + content: Literal( + TextLiteral { + value: "Card", + }, + ), + style_token: "title", + wrap: true, + max_lines: None, + selectable: false, + }, + ), + Repeat( + RepeatNode { + common: NodeCommon { + id: NodeId( + "inner-card/card-rows", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + collection: Records( + RecordsSource { + provider: Some( + ProviderId( + "provider.stack", + ), + ), + schema: SchemaId( + "gamecult.thing.test.swarm.v1", + ), + key_prefix: "mind-", + }, + ), + key_member: MemberPath { + steps: [ + Name( + MemberName { + name: "id", + }, + ), + ], + }, + template: Text( + TextNode { + common: NodeCommon { + id: NodeId( + "inner-card/card-row", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + content: Bound( + Bind { + source: Item, + member: MemberPath { + steps: [ + Name( + MemberName { + name: "name", + }, + ), + ], + }, + format: None, + }, + ), + style_token: "body", + wrap: false, + max_lines: None, + selectable: false, + }, + ), + }, + ), + Button( + ButtonNode { + common: NodeCommon { + id: NodeId( + "inner-card/card-act", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + content: [ + Text( + TextNode { + common: NodeCommon { + id: NodeId( + "inner-card/card-act-label", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + content: Literal( + TextLiteral { + value: "Open", + }, + ), + style_token: "body", + wrap: true, + max_lines: None, + selectable: false, + }, + ), + ], + on_activate: Id( + CommandIdRef { + id: CommandId( + "open", + ), + }, + ), + enabled: Literal( + BoolLiteral { + value: true, + }, + ), + }, + ), + Text( + TextNode { + common: NodeCommon { + id: NodeId( + "inner-note", + ), + visible: Literal( + BoolLiteral { + value: true, + }, + ), + a11y_label: None, + }, + content: Literal( + TextLiteral { + value: "nested", + }, + ), + style_token: "body", + wrap: true, + max_lines: None, + selectable: false, + }, + ), + ], + }, + ), + ], + }, + ), + ], + }, + ), + commands: [ + CommandDecl { + id: CommandId( + "open", + ), + payload_schema: SchemaId( + "gamecult.thing.test.open.v1", + ), + captures: [], + confirm: None, + }, + ], +} diff --git a/crates/thing-core/tests/resolve.rs b/crates/thing-core/tests/resolve.rs new file mode 100644 index 0000000..949cd37 --- /dev/null +++ b/crates/thing-core/tests/resolve.rs @@ -0,0 +1,963 @@ +//! Resolve: expansion, refusal and placeholder, the closed diagnostics, `thing.std`, and the +//! f09 golden. `THING_BLESS=1` on `f09_expands` rewrites the golden through `golden::check`. + +use std::path::PathBuf; + +use thing_contract::*; +use thing_core::diagnostic::Code; +use thing_core::port::{Address, StatePort}; +use thing_core::resolve::{Limits, Resolution, resolve, std as thing_std}; +use thing_testkit::build::*; +use thing_testkit::fixture::Fixture; +use thing_testkit::golden; +use thing_testkit::mem_state::{Call, MemState}; +use thing_testkit::store; + +/// Resolving and decoding run on a 16 MiB thread, as the contract's own tests do. +fn big(work: impl FnOnce() -> T + Send + 'static) -> T { + std::thread::Builder::new().stack_size(16 * 1024 * 1024).spawn(work).unwrap().join().unwrap() +} + +const PUB: &str = "pub.t"; + +fn surface(root: Node, commands: &[&str]) -> SurfaceDocument { + SurfaceDocument { + provider_id: ProviderId::new("provider.t"), + label: seg("main"), + version: ver(1), + title: "t".into(), + root, + commands: commands + .iter() + .map(|id| CommandDecl { + id: CommandId::new(*id), + payload_schema: SchemaId::new("gamecult.thing.test.cmd.v1"), + captures: vec![], + confirm: None, + }) + .collect(), + } +} + +fn composition(name: &str, params: &[(&str, ParamKind)], body: Node) -> CompositionDocument { + CompositionDocument { + publisher: PUB.into(), + name: seg(name), + version: ver(1), + params: params.iter().map(|(name, kind)| ParamDecl { name: (*name).into(), kind: kind.clone() }).collect(), + body, + } +} + +fn reference(name: &str) -> CompositionRef { + CompositionRef { publisher: PUB.into(), name: seg(name), version: ver(1) } +} + +fn use_of(id: &str, name: &str, args: Vec) -> Node { + Node::Use(UseNode { common: common(id), composition: reference(name), args }) +} + +fn text_arg(name: &str, value: &str) -> Arg { + Arg { name: name.into(), value: ArgValue::Text(TextArg { value: value.into() }) } +} + +fn slot_arg(name: &str, nodes: Vec) -> Arg { + Arg { name: name.into(), value: ArgValue::Slot(SlotArg { nodes }) } +} + +fn command_arg(name: &str, id: &str) -> Arg { + Arg { name: name.into(), value: ArgValue::Command(CommandArg { command: command(id) }) } +} + +fn param_text(id: &str, name: &str) -> Node { + Node::Text(TextNode { + common: common(id), + content: TextSource::Param(param(name)), + style_token: "body".into(), + wrap: false, + max_lines: None, + selectable: false, + }) +} + +fn button(id: &str, on_activate: CommandRef) -> Node { + Node::Button(ButtonNode { common: common(id), content: vec![], on_activate, enabled: lit_bool(true) }) +} + +fn slot(name: &str) -> Node { + Node::Slot(SlotNode { param: param(name) }) +} + +fn repeat(id: &str, template: Node) -> Node { + Node::Repeat(RepeatNode { + common: common(id), + collection: CollectionSource::Records(RecordsSource { + provider: None, + schema: SchemaId::new("gamecult.thing.test.row.v1"), + key_prefix: "row-".into(), + }), + key_member: path(&["id"]), + template: std::boxed::Box::new(template), + }) +} + +fn state_with(compositions: &[CompositionDocument]) -> MemState { + let mut state = MemState::new(); + for composition in compositions { + state.put(&ProviderId::new(PUB), composition); + } + state +} + +fn run(document: &SurfaceDocument, state: &MemState) -> Resolution { + resolve(document, state, &Limits::default()) +} + +fn comp_address(name: &str) -> Address { + Address { + provider: ProviderId::new(PUB), + schema: SchemaId::new(CompositionDocument::SCHEMA_NAME), + key: RecordKey::new(reference(name).record_key()), + } +} + +fn kids(node: &Node) -> &[Node] { + match node { + Node::Box(b) => &b.children, + Node::Button(b) => &b.content, + Node::Overlay(o) => &o.children, + Node::Repeat(r) => std::slice::from_ref(&*r.template), + _ => &[], + } +} + +fn id_of(node: &Node) -> &str { + match node { + Node::Box(n) => n.common.id.as_str(), + Node::Text(n) => n.common.id.as_str(), + Node::Image(n) => n.common.id.as_str(), + Node::Button(n) => n.common.id.as_str(), + Node::Toggle(n) => n.common.id.as_str(), + Node::Slider(n) => n.common.id.as_str(), + Node::TextInput(n) => n.common.id.as_str(), + Node::Select(n) => n.common.id.as_str(), + Node::Repeat(n) => n.common.id.as_str(), + Node::Overlay(n) => n.common.id.as_str(), + Node::Plot(n) => n.common.id.as_str(), + Node::Embed(n) => n.common.id.as_str(), + Node::Use(n) => n.common.id.as_str(), + Node::Slot(_) => "", + } +} + +fn ids(node: &Node, out: &mut Vec) { + out.push(id_of(node).to_string()); + kids(node).iter().for_each(|child| ids(child, out)); +} + +fn all_ids(resolution: &Resolution) -> Vec { + let mut out = Vec::new(); + ids(&resolution.tree.as_ref().expect("a tree").document().root, &mut out); + out +} + +fn find<'a>(node: &'a Node, id: &str) -> Option<&'a Node> { + if id_of(node) == id { + return Some(node); + } + kids(node).iter().find_map(|child| find(child, id)) +} + +fn node_of<'a>(resolution: &'a Resolution, id: &str) -> &'a Node { + find(&resolution.tree.as_ref().expect("a tree").document().root, id).unwrap_or_else(|| panic!("no node {id}")) +} + +/// The one diagnostic, with its code, node and a word its detail must carry. +fn only(resolution: &Resolution, code: Code, node: Option<&str>, detail: &str) { + assert_eq!(resolution.diagnostics.len(), 1, "{:?}", resolution.diagnostics); + let found = &resolution.diagnostics[0]; + assert_eq!(found.code, code, "{found:?}"); + assert_eq!(found.node.as_ref().map(NodeId::as_str), node, "{found:?}"); + assert!(found.detail.contains(detail), "{found:?} lacks '{detail}'"); +} + +fn fixture_resolution(fixture: Fixture, label: &str) -> Resolution { + let (set, state) = (fixture.load(), MemState::from_fixture(fixture)); + let document = set.surfaces.iter().find(|surface| surface.label.as_str() == label).unwrap(); + run(document, &state) +} + +#[test] +fn f09_expands() { + big(|| { + let set = Fixture::F09CompositionStack.load(); + let state = MemState::from_fixture(Fixture::F09CompositionStack); + let resolution = run(&set.surfaces[0], &state); + assert_eq!(resolution.diagnostics, vec![]); + let document = resolution.tree.as_ref().unwrap().document(); + + // The std Use expands under its id; the outer card's root is the Use. + let Node::Box(stat) = node_of(&resolution, "std-stat") else { panic!("std-stat is not a Box") }; + assert_eq!(stat.children.len(), 2); + assert!(find(&document.root, "std-stat/stat-label").is_some()); + let Node::Box(outer) = node_of(&resolution, "outer-card") else { panic!("outer-card is not a Box") }; + assert_eq!(outer.common.visible, lit_bool(true)); + let Node::Text(title) = node_of(&resolution, "outer-card/card-title") else { panic!("not a Text") }; + assert_eq!(title.content, lit_text("Card")); + let Node::Button(act) = node_of(&resolution, "outer-card/card-act") else { panic!("not a Button") }; + assert_eq!(act.on_activate, command("open")); + assert_eq!(act.enabled, lit_bool(true)); + let Node::Repeat(rows) = node_of(&resolution, "outer-card/card-rows") else { panic!("not a Repeat") }; + let CollectionSource::Records(records) = &rows.collection else { panic!("not Records") }; + assert_eq!(records.provider, Some(ProviderId::new("provider.stack"))); + + // The slot argument is the caller's inner card, placed after the button, keeping its ids. + let ids = all_ids(&resolution); + let at = |id: &str| ids.iter().position(|found| found == id).unwrap_or_else(|| panic!("no {id} in {ids:?}")); + assert!(at("outer-card/card-act") < at("inner-card")); + assert!(at("inner-card") < at("inner-card/card-title") && at("inner-card/card-title") < at("inner-note")); + + // No Param, no Slot, no absent provider survives. + let debug = format!("{document:#?}"); + assert!(!debug.contains("Param(") && !debug.contains("Slot("), "a Param or Slot remains"); + assert!(!debug.contains("provider: None")); + + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens"); + let bytes = store::bytes(|cache| store::put_pinned(cache, &document.record_key(), document)); + golden::check_with_text(&dir, "resolve-f09-composition-stack", &bytes, &format!("{document:#?}\n")); + }); +} + +#[test] +fn an_undeclared_command_refuses_the_whole_document() { + big(|| { + let resolution = fixture_resolution(Fixture::F10Hostile, "undeclared-command"); + assert!(resolution.tree.is_none()); + only(&resolution, Code::UndeclaredCommand, Some("go"), "missing"); + + // A command passed through a Command argument is judged where it lands. + let body = composition("c", &[("act", ParamKind::Command)], button("b", CommandRef::Param(param("act")))); + let document = surface(boxed("root", vec![use_of("u", "c", vec![command_arg("act", "nope")])]), &["real"]); + let resolution = run(&document, &state_with(&[body])); + assert!(resolution.tree.is_none()); + only(&resolution, Code::UndeclaredCommand, Some("u"), "nope"); + }); +} + +#[test] +fn a_duplicate_id_after_expansion_refuses_the_whole_document() { + big(|| { + let resolution = fixture_resolution(Fixture::F10Hostile, "duplicate-id"); + assert!(resolution.tree.is_none()); + only(&resolution, Code::DuplicateNodeId, Some("dup-use/shared-id"), "twice"); + }); +} + +#[test] +fn an_unresolved_use_is_a_placeholder_and_a_read() { + big(|| { + let resolution = fixture_resolution(Fixture::F10Hostile, "unresolved-use"); + only(&resolution, Code::UnresolvedUse, Some("ghost-use"), "ghost"); + let Node::Use(ghost) = node_of(&resolution, "ghost-use") else { panic!("not a Use leaf") }; + assert!(ghost.args.is_empty()); + let wanted = Address { + provider: ProviderId::new("provider.hostile"), + schema: SchemaId::new(CompositionDocument::SCHEMA_NAME), + key: RecordKey::new(ghost.composition.record_key()), + }; + assert!(resolution.reads.contains(&wanted)); + }); +} + +#[test] +fn a_refused_composition_is_not_absence() { + big(|| { + let mut state = MemState::new(); + let bytes = store::payload(&surface(boxed("root", vec![]), &[])); + state.put_raw(comp_address("c"), bytes); + let document = surface(boxed("root", vec![use_of("u", "c", vec![])]), &[]); + let resolution = run(&document, &state); + assert!(resolution.tree.is_some()); + only(&resolution, Code::DecodeRefused, Some("u"), "pub.t.c.v1"); + assert!(resolution.reads.contains(&comp_address("c"))); + }); +} + +#[test] +fn the_composition_record_must_be_the_one_the_use_names() { + big(|| { + // Version 2's bytes sit at version 1's address; and a different name likewise. + let mut v2 = composition("c", &[], boxed("c-root", vec![])); + v2.version = ver(2); + let other = composition("other", &[], boxed("c-root", vec![])); + for wrong in [v2, other] { + let mut state = MemState::new(); + state.put_raw(comp_address("c"), store::payload(&wrong)); + let resolution = run(&surface(boxed("root", vec![use_of("u", "c", vec![])]), &[]), &state); + only(&resolution, Code::CompositionInvalid, Some("u"), "differs"); + } + }); +} + +#[test] +fn cycles_and_depth_end_in_a_placeholder() { + big(|| { + let a = composition("a", &[], boxed("a-root", vec![use_of("to-b", "b", vec![])])); + let b = composition("b", &[], boxed("b-root", vec![use_of("to-a", "a", vec![])])); + let resolution = run(&surface(boxed("root", vec![use_of("u", "a", vec![])]), &[]), &state_with(&[a, b])); + only(&resolution, Code::CompositionCycle, Some("u/to-b/to-a"), "itself"); + assert!(matches!(node_of(&resolution, "u/to-b/to-a"), Node::Use(leaf) if leaf.args.is_empty())); + + // A chain of 33 compositions: the 33rd Use is over the limit. + let chain: Vec = (1..=33) + .map(|n| { + let inner = if n < 33 { vec![use_of("next", &format!("c{}", n + 1), vec![])] } else { vec![] }; + composition(&format!("c{n}"), &[], boxed("body", inner)) + }) + .collect(); + let resolution = run(&surface(boxed("root", vec![use_of("u", "c1", vec![])]), &[]), &state_with(&chain)); + assert!(resolution.tree.is_some()); + assert_eq!(resolution.diagnostics.len(), 1); + assert_eq!(resolution.diagnostics[0].code, Code::CompositionCycle); + assert!(resolution.diagnostics[0].detail.contains("deep")); + }); +} + +fn limited(max_nodes: usize) -> Limits { + Limits { max_nodes, ..Limits::default() } +} + +fn refused_for_limit(resolution: &Resolution) { + assert!(resolution.tree.is_none(), "{:?}", resolution.diagnostics); + assert!(resolution.diagnostics.iter().any(|found| found.code == Code::ExpansionLimit), "{:?}", resolution.diagnostics); +} + +#[test] +fn the_node_limit_is_exact_and_stops_a_doubling_expansion() { + big(|| { + // Exactly the limit is taken, one over is refused. + let flat = surface(boxed("root", (0..9).map(|n| text(&format!("t{n}"), "x")).collect()), &[]); + let at_limit = resolve(&flat, &MemState::new(), &limited(10)); + assert_eq!(at_limit.diagnostics, vec![]); + assert!(at_limit.tree.is_some()); + refused_for_limit(&resolve(&flat, &MemState::new(), &limited(9))); + + // A composition using the previous one twice, 30 levels: 2^30 nodes, which only an early stop + // survives. The small limit keeps the work small; the refusal is the assertion. + let mut chain = vec![composition("c0", &[], boxed("body", vec![]))]; + for n in 1..=30 { + let below = format!("c{}", n - 1); + let body = boxed("body", vec![use_of("l", &below, vec![]), use_of("r", &below, vec![])]); + chain.push(composition(&format!("c{n}"), &[], body)); + } + let document = surface(boxed("root", vec![use_of("u", "c30", vec![])]), &[]); + refused_for_limit(&resolve(&document, &state_with(&chain), &limited(100))); + + // Seven levels are 255 nodes: over 100, under the default. + let seven = surface(boxed("root", vec![use_of("u", "c7", vec![])]), &[]); + refused_for_limit(&resolve(&seven, &state_with(&chain), &limited(100))); + assert!(resolve(&seven, &state_with(&chain), &Limits::default()).tree.is_some()); + }); +} + +#[test] +fn a_slot_placed_twice_per_level_is_counted_when_it_is_spliced() { + big(|| { + // Each level places its slot twice around the level below: every level's expansion is counted + // once, so only the splice count sees the doubling. + let doubling = composition("c", &[("body", ParamKind::Slot)], boxed("b", vec![slot("body"), slot("body")])); + let mut nested = text("leaf", "x"); + for level in 0..12 { + nested = use_of(&format!("u{level}"), "c", vec![slot_arg("body", vec![nested])]); + } + let document = surface(boxed("root", vec![nested]), &[]); + refused_for_limit(&resolve(&document, &state_with(&[doubling]), &limited(1000))); + }); +} + +#[test] +fn a_tree_deeper_than_the_limit_is_refused() { + big(|| { + let mut deep = boxed("leaf", vec![]); + for level in 0..257 { + deep = boxed(&format!("level-{level}"), vec![deep]); + } + refused_for_limit(&run(&surface(deep, &[]), &MemState::new())); + + // A slot's nodes stand deeper in the body than they did in the caller: expand sees 60 and 200 + // levels, the finished tree about 265. (The body is a stored record, whose own nesting is bounded.) + let chain = |levels: usize, inner: Vec, tag: &str| { + let mut node = boxed(&format!("{tag}-bottom"), inner); + for level in 0..levels { + node = boxed(&format!("{tag}-{level}"), vec![node]); + } + node + }; + let body = composition("c", &[("body", ParamKind::Slot)], chain(60, vec![slot("body")], "b")); + let argument = slot_arg("body", vec![chain(200, vec![], "a")]); + let document = surface(boxed("root", vec![use_of("u", "c", vec![argument])]), &[]); + let resolution = run(&document, &state_with(&[body])); + refused_for_limit(&resolution); + assert!(resolution.diagnostics.iter().any(|found| found.detail.contains("deeper"))); + }); +} + +#[test] +fn argument_and_body_faults_each_leave_a_placeholder_naming_the_case() { + big(|| { + let text_body = || boxed("b", vec![param_text("t", "x")]); + let t = || [("x", ParamKind::Text)]; + let cases: Vec<(&str, CompositionDocument, Vec, &str)> = vec![ + ("missing argument", composition("c", &t(), text_body()), vec![], "has no argument"), + ( + "extra argument", + composition("c", &t(), text_body()), + vec![text_arg("x", "a"), text_arg("y", "b")], + "names no param", + ), + ("duplicate argument", composition("c", &t(), text_body()), vec![text_arg("x", "a"), text_arg("x", "b")], "twice"), + ( + "duplicate param", + composition("c", &[("x", ParamKind::Text), ("x", ParamKind::Text)], text_body()), + vec![text_arg("x", "a")], + "declares param 'x' twice", + ), + ( + "arm differs from kind", + composition("c", &t(), text_body()), + vec![Arg { name: "x".into(), value: ArgValue::Number(NumberArg { value: 1.0 }) }], + "is a Number but the param is a Text", + ), + ("param names nothing", composition("c", &t(), boxed("b", vec![param_text("t", "zz")])), vec![text_arg("x", "a")], "does not declare"), + ( + "param of the wrong kind", + composition("c", &[("x", ParamKind::Number)], boxed("b", vec![param_text("t", "x")])), + vec![Arg { name: "x".into(), value: ArgValue::Number(NumberArg { value: 1.0 }) }], + "used as text", + ), + ( + "literal command in a body", + composition("c", &[], boxed("b", vec![button("go", command("real"))])), + vec![], + "composition takes its commands", + ), + ( + "root visibility", + composition("c", &[], Node::Box(BoxNode { common: NodeCommon { visible: lit_bool(false), ..common("b") }, ..match boxed("b", vec![]) { Node::Box(b) => b, _ => unreachable!() } })), + vec![], + "visible", + ), + ]; + for (name, composition, args, detail) in cases { + let document = surface(boxed("root", vec![use_of("u", "c", args)]), &["real"]); + let resolution = run(&document, &state_with(&[composition])); + assert!(resolution.tree.is_some(), "{name}"); + only(&resolution, Code::CompositionInvalid, Some("u"), detail); + assert!(matches!(node_of(&resolution, "u"), Node::Use(leaf) if leaf.args.is_empty()), "{name}"); + } + }); +} + +#[test] +fn a_param_outside_a_composition_refuses_the_whole_document() { + big(|| { + let resolution = run(&surface(boxed("root", vec![param_text("t", "x")]), &[]), &MemState::new()); + assert!(resolution.tree.is_none()); + only(&resolution, Code::UnboundParam, Some("t"), "param 'x'"); + let resolution = run(&surface(boxed("root", vec![button("b", CommandRef::Param(param("x")))]), &[]), &MemState::new()); + only(&resolution, Code::UnboundParam, Some("b"), "param 'x'"); + }); +} + +#[test] +fn ids_survive_a_republish_and_follow_sibling_order() { + big(|| { + let set = Fixture::F09CompositionStack.load(); + let state = MemState::from_fixture(Fixture::F09CompositionStack); + let one = run(&set.surfaces[0], &state); + let mut republished = set.surfaces[0].clone(); + republished.version = ver(2); + assert_eq!(all_ids(&run(&republished, &state)), all_ids(&one)); + + // Swapping two siblings moves their ids and renames none. + let Node::Box(root) = &mut republished.root else { unreachable!() }; + root.children.swap(0, 1); + let swapped = all_ids(&run(&republished, &state)); + assert_ne!(swapped, all_ids(&one)); + let (mut left, mut right) = (swapped, all_ids(&one)); + left.sort(); + right.sort(); + assert_eq!(left, right); + }); +} + +#[test] +fn thing_std_is_compiled_in_and_never_read() { + big(|| { + // A provider's own `thing.std` stat is never asked for, so it cannot shadow core's. + let mut state = MemState::new(); + let shadow = CompositionDocument { + publisher: thing_std::PUBLISHER.into(), + name: seg("stat"), + version: ver(1), + params: vec![], + body: boxed("shadow", vec![]), + }; + state.put(&ProviderId::new(thing_std::PUBLISHER), &shadow); + let used = Node::Use(UseNode { + common: common("s"), + composition: CompositionRef { publisher: thing_std::PUBLISHER.into(), name: seg("stat"), version: ver(1) }, + args: vec![ + text_arg("label", "L"), + Arg { name: "value".into(), value: ArgValue::Bind(item_bind(path(&["v"]))) }, + ], + }); + let resolution = run(&surface(boxed("root", vec![used]), &[]), &state); + assert_eq!(resolution.diagnostics, vec![]); + assert!(find(&resolution.tree.as_ref().unwrap().document().root, "s/stat-label").is_some()); + assert!(resolution.reads.is_empty()); + let touched = |call: &Call| matches!(call, Call::Read(address) if address.provider.as_str() == thing_std::PUBLISHER); + assert!(!state.calls().iter().any(touched)); + + // A std name nobody compiled in is unresolved, and still not read. + let ghost = Node::Use(UseNode { + common: common("g"), + composition: CompositionRef { publisher: thing_std::PUBLISHER.into(), name: seg("nope"), version: ver(1) }, + args: vec![], + }); + let resolution = run(&surface(boxed("root", vec![ghost]), &[]), &state); + only(&resolution, Code::UnresolvedUse, Some("g"), "nope"); + assert!(resolution.reads.is_empty()); + }); +} + +#[test] +fn every_std_composition_expands_with_literal_shaped_arguments() { + big(|| { + for composition in thing_std::all() { + let args: Vec = composition + .params + .iter() + .map(|decl| { + let value = match decl.kind { + ParamKind::Text => ArgValue::Text(TextArg { value: "x".into() }), + ParamKind::Number => ArgValue::Number(NumberArg { value: 1.0 }), + ParamKind::Bool => ArgValue::Bool(BoolArg { value: true }), + ParamKind::Bind => ArgValue::Bind(item_bind(path(&["v"]))), + ParamKind::Collection => ArgValue::Collection(CollectionArg { + source: CollectionSource::Member(item_bind(path(&["v"]))), + }), + ParamKind::Command => ArgValue::Command(CommandArg { command: command("real") }), + ParamKind::Slot => ArgValue::Slot(SlotArg { nodes: vec![text("note", "n")] }), + }; + Arg { name: decl.name.clone(), value } + }) + .collect(); + let used = Node::Use(UseNode { + common: common("u"), + composition: CompositionRef { publisher: composition.publisher.clone(), name: composition.name.clone(), version: composition.version }, + args, + }); + let resolution = run(&surface(boxed("root", vec![used]), &["real"]), &MemState::new()); + assert_eq!(resolution.diagnostics, vec![], "{}", composition.name.as_str()); + let debug = format!("{:?}", resolution.tree.unwrap().document()); + assert!(!debug.contains("Param(") && !debug.contains("Slot("), "{}", composition.name.as_str()); + } + }); +} + +#[test] +fn every_fixture_resolves_without_panic_to_nothing_or_unique_ids() { + big(|| { + for fixture in Fixture::ALL { + let (set, state) = (fixture.load(), MemState::from_fixture(fixture)); + for document in &set.surfaces { + let resolution = run(document, &state); + if resolution.tree.is_some() { + let mut found = all_ids(&resolution); + let before = found.len(); + found.sort(); + found.dedup(); + assert_eq!(found.len(), before, "{} {}", fixture.file_name(), document.label.as_str()); + } + } + } + }); +} + +#[test] +fn slot_arguments_are_spliced_where_the_body_places_them() { + big(|| { + // A body that places its slot twice repeats the caller's ids. + let twice = composition("c", &[("body", ParamKind::Slot)], boxed("b", vec![slot("body"), slot("body")])); + let document = surface(boxed("root", vec![use_of("u", "c", vec![slot_arg("body", vec![text("note", "n")])])]), &[]); + let resolution = run(&document, &state_with(&[twice])); + assert!(resolution.tree.is_none()); + only(&resolution, Code::DuplicateNodeId, Some("note"), "twice"); + + // A body passes its own slot argument on to a composition it uses. + let inner = composition("inner", &[("body", ParamKind::Slot)], boxed("ib", vec![slot("body")])); + let outer = composition( + "outer", + &[("body", ParamKind::Slot)], + boxed("ob", vec![use_of("in", "inner", vec![slot_arg("body", vec![slot("body")])])]), + ); + let document = surface(boxed("root", vec![use_of("u", "outer", vec![slot_arg("body", vec![text("note", "n")])])]), &[]); + let resolution = run(&document, &state_with(&[inner, outer])); + assert_eq!(resolution.diagnostics, vec![]); + assert_eq!(all_ids(&resolution), ["root", "u", "u/in", "note"]); + }); +} + +#[test] +fn a_slot_stands_only_in_a_child_list_of_a_composition_body() { + big(|| { + // Outside any composition: the surface root, a surface's child list, under a non-body node, + // and in a slot argument of a surface-level Use. + let unbound = [ + ("the surface root", slot("body")), + ("a surface child list", boxed("root", vec![slot("body")])), + ("under a Repeat template", boxed("root", vec![repeat("rows", boxed("row", vec![slot("body")]))])), + ("a surface-level slot argument", boxed("root", vec![use_of("u", "c", vec![slot_arg("body", vec![slot("body")])])])), + ]; + let c = composition("c", &[("body", ParamKind::Slot)], boxed("b", vec![slot("body")])); + let state = state_with(std::slice::from_ref(&c)); + for (place, root) in unbound { + let resolution = run(&surface(root, &[]), &state); + assert!(resolution.tree.is_none(), "{place}"); + assert!(resolution.diagnostics.iter().all(|found| found.code == Code::UnboundParam), "{place}"); + assert!(!resolution.diagnostics.is_empty(), "{place}"); + } + + // In a body, anywhere but a child list: the template of a Repeat, or the body root. + let template = composition("t", &[("body", ParamKind::Slot)], boxed("b", vec![repeat("rows", slot("body"))])); + let root_slot = composition("r", &[("body", ParamKind::Slot)], slot("body")); + for (name, bad) in [("t", template), ("r", root_slot)] { + let document = surface(boxed("root", vec![use_of("u", name, vec![slot_arg("body", vec![text("note", "n")])])]), &[]); + let resolution = run(&document, &state_with(&[bad])); + assert!(resolution.tree.is_some(), "{name}"); + only(&resolution, Code::CompositionInvalid, Some("u"), "child list"); + } + }); +} + +#[test] +fn resolve_reads_only_through_read() { + big(|| { + let set = Fixture::F09CompositionStack.load(); + let state = MemState::from_fixture(Fixture::F09CompositionStack); + run(&set.surfaces[0], &state); + assert!(state.calls().iter().all(|call| matches!(call, Call::Read(_)))); + let _: &dyn StatePort = &state; + }); +} + +#[test] +fn an_anchor_in_a_body_follows_the_expanded_ids() { + big(|| { + let overlay = |anchor: &str| { + Node::Overlay(OverlayNode { + common: common("pop"), + anchor: Anchor::Node(AnchorNode { node: nid(anchor) }), + modal: false, + dismiss: CommandRef::Param(param("dismiss")), + children: vec![], + }) + }; + let body = boxed("b", vec![text("target", "t"), overlay("target"), { + let Node::Overlay(root_anchored) = overlay("b") else { unreachable!() }; + Node::Overlay(OverlayNode { common: common("pop-root"), ..root_anchored }) + }]); + let document = surface(boxed("root", vec![use_of("u", "c", vec![command_arg("dismiss", "real")])]), &["real"]); + let resolution = run(&document, &state_with(&[composition("c", &[("dismiss", ParamKind::Command)], body)])); + assert_eq!(resolution.diagnostics, vec![]); + for (id, target) in [("u/pop", "u/target"), ("u/pop-root", "u")] { + let Node::Overlay(found) = node_of(&resolution, id) else { panic!("not an Overlay") }; + assert_eq!(found.anchor, Anchor::Node(AnchorNode { node: nid(target) }), "{id}"); + } + }); +} + +fn root_common_of(resolution: &Resolution, id: &str) -> NodeCommon { + let Node::Box(found) = node_of(resolution, id) else { panic!("not a Box") }; + found.common.clone() +} + +#[test] +fn the_expanded_root_takes_the_uses_visibility_and_label() { + big(|| { + let flag = |provider: Option<&str>| Bind { + source: StateSource::Record(StateRef { + provider: provider.map(ProviderId::new), + schema: SchemaId::new("gamecult.thing.test.flag.v1"), + key: RecordKey::new("shown"), + }), + member: path(&["on"]), + format: None, + }; + let labelled = |label: Option| { + let Node::Box(mut root) = boxed("b", vec![]) else { unreachable!() }; + root.common.a11y_label = label; + Node::Box(root) + }; + let used = |visible: BoolSource, label: Option, args: Vec| { + Node::Use(UseNode { + common: NodeCommon { id: nid("u"), visible, a11y_label: label }, + composition: reference("c"), + args, + }) + }; + let run_one = |body: Node, params: &[(&str, ParamKind)], used: Node| { + run(&surface(boxed("root", vec![used]), &[]), &state_with(&[composition("c", params, body)])) + }; + + // The Use's bound visibility and its label win over the body root's label. + let resolution = run_one( + labelled(Some(lit_text("body label"))), + &[], + used(BoolSource::Bound(flag(None)), Some(lit_text("use label")), vec![]), + ); + assert_eq!(resolution.diagnostics, vec![]); + let common = root_common_of(&resolution, "u"); + assert_eq!(common.visible, BoolSource::Bound(flag(Some("provider.t")))); + assert_eq!(common.a11y_label, Some(lit_text("use label"))); + + // Without a Use label the body root's own label stands, a Param of it substituted. + let resolution = run_one( + labelled(Some(TextSource::Param(param("lbl")))), + &[("lbl", ParamKind::Text)], + used(lit_bool(true), None, vec![text_arg("lbl", "from arg")]), + ); + assert_eq!(root_common_of(&resolution, "u").a11y_label, Some(lit_text("from arg"))); + let resolution = run_one(labelled(None), &[], used(lit_bool(true), None, vec![])); + assert_eq!(root_common_of(&resolution, "u").a11y_label, None); + + // A literal false on the Use hides the expansion. + let resolution = run_one(labelled(None), &[], used(lit_bool(false), None, vec![])); + assert_eq!(root_common_of(&resolution, "u").visible, lit_bool(false)); + }); +} + +#[test] +fn a_param_left_in_any_position_outside_a_composition_refuses() { + big(|| { + let slider = Node::Slider(SliderNode { + common: common("s"), + min: 0.0, + max: 1.0, + step: 0.1, + value: NumberSource::Param(param("n")), + commit: command("real"), + }); + let enabled = Node::Button(ButtonNode { + common: common("b"), + content: vec![], + on_activate: command("real"), + enabled: BoolSource::Param(param("on")), + }); + let Node::Repeat(mut rows) = repeat("r", text("row", "x")) else { unreachable!() }; + rows.collection = CollectionSource::Param(param("rows")); + let Node::Text(mut shown) = text("t", "x") else { unreachable!() }; + shown.common.visible = BoolSource::Param(param("v")); + let cases = [("number", slider), ("bool", enabled), ("collection", Node::Repeat(rows)), ("visible", Node::Text(shown))]; + for (name, node) in cases { + let resolution = run(&surface(boxed("root", vec![node]), &["real"]), &MemState::new()); + assert!(resolution.tree.is_none(), "{name}"); + assert_eq!(resolution.diagnostics.len(), 1, "{name}"); + assert_eq!(resolution.diagnostics[0].code, Code::UnboundParam, "{name}"); + } + }); +} + +#[test] +fn an_absent_provider_is_the_surfaces_in_select_and_plot_too() { + big(|| { + let bind = |key: &str| Bind { + source: StateSource::Record(StateRef { + provider: None, + schema: SchemaId::new("gamecult.thing.test.row.v1"), + key: RecordKey::new(key), + }), + member: path(&["v"]), + format: None, + }; + let select = Node::Select(SelectNode { + common: common("sel"), + options: OptionList::Bound(BoundOptions { + collection: CollectionSource::Records(RecordsSource { + provider: None, + schema: SchemaId::new("gamecult.thing.test.row.v1"), + key_prefix: "row-".into(), + }), + value_member: path(&["id"]), + label_member: path(&["name"]), + }), + value: bind("a"), + on_change: command("real"), + }); + let plot = Node::Plot(PlotNode { + common: common("plot"), + series: bind("b"), + mark: PlotMark::Line, + x_min: None, + x_max: None, + y_min: None, + y_max: None, + }); + let resolution = run(&surface(boxed("root", vec![select, plot]), &["real"]), &MemState::new()); + assert_eq!(resolution.diagnostics, vec![]); + let debug = format!("{:?}", resolution.tree.unwrap().document()); + assert!(!debug.contains("provider: None")); + // The surface's own provider id, then the options collection, the select value and the series. + assert_eq!(debug.matches("provider.t").count(), 4); + }); +} + +#[test] +fn duplicate_ids_are_found_under_every_container_and_on_a_placeholder() { + big(|| { + let overlay = |child: Node| { + Node::Overlay(OverlayNode { + common: common("pop"), + anchor: Anchor::Viewport, + modal: false, + dismiss: command("real"), + children: vec![child], + }) + }; + let button = Node::Button(ButtonNode { + common: common("btn"), + content: vec![text("d", "x")], + on_activate: command("real"), + enabled: lit_bool(true), + }); + let cases = [ + ("repeat template", repeat("rows", text("d", "x"))), + ("overlay children", overlay(text("d", "x"))), + ("button content", button), + ("a placeholder's id", use_of("d", "ghost", vec![])), + ]; + for (name, other) in cases { + let document = surface(boxed("root", vec![text("d", "first"), other]), &["real"]); + let resolution = run(&document, &MemState::new()); + assert!(resolution.tree.is_none(), "{name}"); + let duplicates: Vec<_> = + resolution.diagnostics.iter().filter(|found| found.code == Code::DuplicateNodeId).collect(); + assert_eq!(duplicates.len(), 1, "{name}: {:?}", resolution.diagnostics); + assert_eq!(duplicates[0].node.as_ref().map(NodeId::as_str), Some("d"), "{name}"); + } + }); +} + +#[test] +fn a_failed_body_leaves_only_its_own_diagnostic() { + big(|| { + // The ghost Use in the body is reported by the expansion, then the body fails on its Param: + // the whole body is replaced, so its partial diagnostics go with it. + let body = composition("c", &[], boxed("b", vec![use_of("ghost-use", "ghost", vec![]), param_text("t", "zz")])); + let resolution = run(&surface(boxed("root", vec![use_of("u", "c", vec![])]), &[]), &state_with(&[body])); + only(&resolution, Code::CompositionInvalid, Some("u"), "does not declare"); + }); +} + +#[test] +fn a_std_reference_is_pinned_to_its_version() { + big(|| { + let v2 = Node::Use(UseNode { + common: common("s"), + composition: CompositionRef { publisher: thing_std::PUBLISHER.into(), name: seg("stat"), version: ver(2) }, + args: vec![], + }); + let resolution = run(&surface(boxed("root", vec![v2]), &[]), &MemState::new()); + only(&resolution, Code::UnresolvedUse, Some("s"), "stat"); + }); +} + +#[test] +fn diagnostics_and_reads_come_out_in_a_defined_order() { + big(|| { + // Expansion faults first, in expansion order, then the finished tree's; reads sorted by key. + let names = ["n3", "n9", "n0", "n7", "n1", "n8", "n5", "n2", "n6", "n4"]; + let mut children = vec![text("d", "x")]; + children.extend(names.iter().map(|name| use_of(&format!("g-{name}"), name, vec![]))); + children.push(text("d", "y")); + let resolution = run(&surface(boxed("root", children), &[]), &MemState::new()); + let seen: Vec<_> = + resolution.diagnostics.iter().map(|found| (found.code, found.node.as_ref().map(NodeId::as_str))).collect(); + let mut expected: Vec<_> = names.iter().map(|_| Code::UnresolvedUse).collect(); + expected.push(Code::DuplicateNodeId); + assert_eq!(seen.iter().map(|(code, _)| *code).collect::>(), expected); + assert_eq!(seen[0].1, Some("g-n3")); + assert_eq!(seen.last().unwrap().1, Some("d")); + let mut sorted: Vec<_> = (0..10).map(|n| comp_address(&format!("n{n}"))).collect(); + sorted.sort_by_key(|address| address.key.as_str().to_string()); + assert_eq!(resolution.reads, sorted); + }); +} + +/// A chain of `levels` nodes, the first the root: Boxes, or Repeats whose template is the next. +fn chain(levels: usize, repeats: bool) -> Node { + let mut node = text("bottom", "x"); + for level in 1..levels { + let id = format!("level-{level}"); + node = if repeats { repeat(&id, node) } else { boxed(&id, vec![node]) }; + } + node +} + +#[test] +fn the_depth_rule_is_judged_on_the_finished_tree_through_box_and_repeat() { + big(|| { + for repeats in [false, true] { + let at_limit = run(&surface(chain(256, repeats), &[]), &MemState::new()); + assert_eq!(at_limit.diagnostics, vec![], "repeats={repeats}"); + assert!(at_limit.tree.is_some()); + let over = run(&surface(chain(257, repeats), &[]), &MemState::new()); + refused_for_limit(&over); + assert!(over.diagnostics.iter().any(|found| found.detail.contains("deeper")), "repeats={repeats}"); + } + }); +} + +#[test] +fn an_unplaced_slot_argument_does_not_count_toward_the_depth_rule() { + big(|| { + let ignoring = composition("c", &[("body", ParamKind::Slot)], boxed("b", vec![])); + let mut deep = text("leaf", "x"); + for level in 0..300 { + deep = boxed(&format!("a-{level}"), vec![deep]); + } + let document = surface(boxed("root", vec![use_of("u", "c", vec![slot_arg("body", vec![deep])])]), &[]); + let resolution = run(&document, &state_with(&[ignoring])); + assert_eq!(resolution.diagnostics, vec![]); + assert_eq!(all_ids(&resolution), ["root", "u"]); + }); +} + +#[test] +fn input_too_deep_to_recurse_into_is_refused_with_its_own_code() { + big(|| { + // A debug-build level costs tens of KiB of stack, so 1,100 levels want a stack of their own. + let resolution = std::thread::Builder::new() + .stack_size(128 * 1024 * 1024) + .spawn(|| run(&surface(chain(1100, false), &[]), &MemState::new())) + .unwrap() + .join() + .unwrap(); + assert!(resolution.tree.is_none()); + assert_eq!(resolution.diagnostics.len(), 1, "{:?}", resolution.diagnostics); + assert_eq!(resolution.diagnostics[0].code, Code::TooDeepToResolve); + }); +} + +#[test] +fn a_slot_naming_a_param_of_another_kind_is_invalid() { + big(|| { + let body = composition("c", &[("x", ParamKind::Text)], boxed("b", vec![slot("x")])); + let document = surface(boxed("root", vec![use_of("u", "c", vec![text_arg("x", "t")])]), &[]); + let resolution = run(&document, &state_with(&[body])); + only(&resolution, Code::CompositionInvalid, Some("u"), "used as a slot"); + }); +} + + diff --git a/crates/thing-testkit/fixtures/README.md b/crates/thing-testkit/fixtures/README.md index 72ce72e..21ca217 100644 --- a/crates/thing-testkit/fixtures/README.md +++ b/crates/thing-testkit/fixtures/README.md @@ -15,8 +15,8 @@ frozen, and a normal test run only compares and reads them. The rows are the fix | `f06-scroll-list.surface.cc` | One surface: a Box with `overflow: scroll` holding a Repeat over a RecordsSource prefix, template keyed by the item's `id` (the 1,000 items are provider state, not here) | - | | `f07-plot.surface.cc` | One surface with a Plot of each mark (Line, Bar, Area) over a bound series, with and without axis bounds | - | | `f08-embed-viewport.surface.cc` | One surface: an Embed of declared fixed size as a leaf between two Texts | - | -| `f09-composition-stack.surface.cc` | One surface whose Use passes one argument of each ArgValue arm and a Slot holding a second Use (two levels), and the publisher CompositionDocument both name | 5 | -| `f10-hostile.surface.cc` | Four surfaces, one hostile shape each: an undeclared CommandRef, a duplicate id after expansion, an unresolved Use, and a Bind whose schema no fixture provides; plus the one composition (`dup`) the duplicate-id surface expands | 4, 5, 6 | +| `f09-composition-stack.surface.cc` | One surface: a `thing.std` stat Use, and a Use passing one argument of each ArgValue arm whose slot argument holds a second Use (two levels); plus the publisher CompositionDocument both name, whose body places the Slot node | 5 | +| `f10-hostile.surface.cc` | Four surfaces, one hostile shape each: an undeclared CommandRef, a duplicate id after expansion (the surface's `dup-use/shared-id` against the expansion of `dup-use`), an unresolved Use, and a Bind whose schema no fixture provides; plus the one composition (`dup`) the duplicate-id surface expands | 4, 5, 6 | | `f11-deep.surface.cc` | One surface: the deepest Box chain whose payload CultCache's `check_payload_depth` accepts, found by the builder | - | | `f11-deep-refused.bin` | The payload of the same chain one Box level deeper, raw: `check_payload_depth` refuses it at depth 257 and so does CultCache. No store can hold it | - | | `f12-text-edge.surface.cc` | One surface of five Text nodes: bidi (Hebrew and Arabic in Latin), CJK wide characters, combining marks, emoji ZWJ sequences, and a paragraph long enough to wrap | - | diff --git a/crates/thing-testkit/fixtures/f09-composition-stack.surface.cc b/crates/thing-testkit/fixtures/f09-composition-stack.surface.cc index 2fbb0ce..e72f6bd 100644 Binary files a/crates/thing-testkit/fixtures/f09-composition-stack.surface.cc and b/crates/thing-testkit/fixtures/f09-composition-stack.surface.cc differ diff --git a/crates/thing-testkit/fixtures/f10-hostile.surface.cc b/crates/thing-testkit/fixtures/f10-hostile.surface.cc index e96531a..56e3926 100644 Binary files a/crates/thing-testkit/fixtures/f10-hostile.surface.cc and b/crates/thing-testkit/fixtures/f10-hostile.surface.cc differ diff --git a/crates/thing-testkit/src/fixture.rs b/crates/thing-testkit/src/fixture.rs index 549ee6b..59228a2 100644 --- a/crates/thing-testkit/src/fixture.rs +++ b/crates/thing-testkit/src/fixture.rs @@ -133,28 +133,24 @@ impl Fixture { /// Encode the built documents into a store and bless or compare the committed file; returns /// the committed bytes. pub fn write(self) -> Vec { - let work = scratch_dir("write"); - let scratch = work.join(self.file_name()); - let mut cache = store::create(&scratch); let set = self.build(); - for surface in &set.surfaces { - store::put_pinned(&mut cache, &surface.record_key(), surface); - } - for composition in &set.compositions { - store::put_pinned(&mut cache, &composition.record_key(), composition); - } - for catalog in &set.catalogs { - store::put_pinned(&mut cache, &catalog.record_key(), catalog); - } - for invocation in &set.invocations { - store::put_pinned(&mut cache, &invocation.record_key(), invocation); - } - for result in &set.results { - store::put_pinned(&mut cache, &result.record_key(), result); - } - drop(cache); - let bytes = std::fs::read(&scratch).unwrap(); - let _ = std::fs::remove_dir_all(&work); + let bytes = store::bytes(|cache| { + for surface in &set.surfaces { + store::put_pinned(cache, &surface.record_key(), surface); + } + for composition in &set.compositions { + store::put_pinned(cache, &composition.record_key(), composition); + } + for catalog in &set.catalogs { + store::put_pinned(cache, &catalog.record_key(), catalog); + } + for invocation in &set.invocations { + store::put_pinned(cache, &invocation.record_key(), invocation); + } + for result in &set.results { + store::put_pinned(cache, &result.record_key(), result); + } + }); golden::check(&Self::dir(), self.file_name(), &bytes) } @@ -162,7 +158,7 @@ impl Fixture { /// store, so this opens a copy in a directory of its own, removed once the store is read: /// the fixtures directory is never written. pub fn open(self) -> CultCache { - let work = scratch_dir("open"); + let work = store::scratch_dir("open"); let copy = work.join(self.file_name()); std::fs::copy(Self::dir().join(self.file_name()), ©).unwrap(); let cache = store::open(©); @@ -184,16 +180,6 @@ impl Fixture { } } -/// A fresh directory of its own under the temp directory (process id and a serial), so the lock -/// file a store creates beside its file goes when the directory does. -fn scratch_dir(purpose: &str) -> PathBuf { - static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let work = std::env::temp_dir().join(format!("thing-testkit-{purpose}-{}-{serial}", std::process::id())); - std::fs::create_dir_all(&work).unwrap(); - work -} - const SWARM: &str = "provider.swarm"; const SWARM_SCHEMA: &str = "gamecult.thing.test.swarm.v1"; @@ -298,12 +284,24 @@ fn composition_stack() -> SurfaceDocument { // Two levels: the outer card's slot holds a second card. let inner = card_use("inner-card", vec![text("inner-note", "nested")]); let outer = card_use("outer-card", vec![inner]); + // A compiled-in composition: thing.std is never asked of the port. + let std_stat = Node::Use(UseNode { + common: common("std-stat"), + composition: CompositionRef { publisher: "thing.std".into(), name: seg("stat"), version: ver(1) }, + args: vec![ + Arg { name: "label".into(), value: ArgValue::Text(TextArg { value: "Load".into() }) }, + Arg { + name: "value".into(), + value: ArgValue::Bind(Bind { source: swarm_ref("summary"), member: path(&["load"]), format: None }), + }, + ], + }); SurfaceDocument { provider_id: ProviderId::new(STACK), label: seg("stack"), version: ver(1), title: "Stack".into(), - root: boxed("root", vec![outer]), + root: boxed("root", vec![std_stat, outer]), commands: vec![CommandDecl { id: CommandId::new("open"), payload_schema: SchemaId::new("gamecult.thing.test.open.v1"), @@ -357,7 +355,7 @@ fn stack_card() -> CompositionDocument { .into_iter() .map(|(name, kind)| ParamDecl { name: name.into(), kind }) .collect(), - body: boxed("card-root", vec![title, rows, act]), + body: boxed("card-root", vec![title, rows, act, Node::Slot(SlotNode { param: param("body") })]), } } @@ -410,8 +408,9 @@ fn hostile() -> Vec { }); vec![ hostile_surface("undeclared-command", vec![undeclared]), - // The composition `dup` emits `shared-id`, which the surface also uses. - hostile_surface("duplicate-id", vec![hostile_use("dup-use", "dup"), text("shared-id", "also here")]), + // The composition `dup` emits `shared-id`, which expands to `dup-use/shared-id`; the surface + // authors that same id beside the Use. + hostile_surface("duplicate-id", vec![hostile_use("dup-use", "dup"), text("dup-use/shared-id", "also here")]), // No composition `ghost` exists anywhere. hostile_surface("unresolved-use", vec![hostile_use("ghost-use", "ghost")]), hostile_surface("schema-mismatch", vec![mismatched]), diff --git a/crates/thing-testkit/src/store.rs b/crates/thing-testkit/src/store.rs index 4b8610a..5f20791 100644 --- a/crates/thing-testkit/src/store.rs +++ b/crates/thing-testkit/src/store.rs @@ -1,7 +1,7 @@ //! CultCache single-file stores of contract documents, written under a pinned clock so the //! bytes are reproducible. -use std::path::Path; +use std::path::{Path, PathBuf}; use cultcache_rs::{CultCache, CultCacheRegistry, DatabaseEntry, SingleFileMessagePackBackingStore}; use thing_contract::ThingContract; @@ -37,3 +37,31 @@ pub fn open(path: &Path) -> CultCache { cache.pull_all_backing_stores().unwrap(); cache } + +/// A fresh directory of its own under the temp directory (process id and a serial), so the lock +/// file a store creates beside its file goes when the directory does. +pub(crate) fn scratch_dir(purpose: &str) -> PathBuf { + static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let work = std::env::temp_dir().join(format!("thing-testkit-{purpose}-{}-{serial}", std::process::id())); + std::fs::create_dir_all(&work).unwrap(); + work +} + +/// The bytes of a scratch single-file store that `fill` filled under the pinned clock. The scratch +/// store and its lock file are removed. +pub fn bytes(fill: impl FnOnce(&mut CultCache)) -> Vec { + let work = scratch_dir("write"); + let scratch = work.join("store.cc"); + let mut cache = create(&scratch); + fill(&mut cache); + drop(cache); + let bytes = std::fs::read(&scratch).unwrap(); + let _ = std::fs::remove_dir_all(&work); + bytes +} + +/// The payload the contract writes for `value`, as a store would hold it. +pub fn payload(value: &T) -> Vec { + memory().prepare_entry("payload", value).unwrap().0.payload +} diff --git a/crates/thing-testkit/tests/fixtures.rs b/crates/thing-testkit/tests/fixtures.rs index 87b2de2..222f945 100644 --- a/crates/thing-testkit/tests/fixtures.rs +++ b/crates/thing-testkit/tests/fixtures.rs @@ -104,7 +104,9 @@ fn f09_stacks_compositions_with_every_argument_arm() { let set = load(Fixture::F09CompositionStack); assert_eq!((set.surfaces.len(), set.compositions.len()), (1, 1)); let surface = &set.surfaces[0]; - let [outer] = box_children(&surface.root) else { panic!("one Use expected") }; + let [std_stat, outer] = box_children(&surface.root) else { panic!("two Uses expected") }; + let Node::Use(std_stat) = std_stat else { panic!("not a Use") }; + assert_eq!((std_stat.composition.publisher.as_str(), std_stat.composition.name.as_str()), ("thing.std", "stat")); let Node::Use(outer) = outer else { panic!("not a Use") }; assert_eq!(outer.composition.publisher, set.compositions[0].publisher); assert_eq!(outer.composition.name, set.compositions[0].name); @@ -143,10 +145,10 @@ fn f10_holds_exactly_the_four_hostile_surfaces() { let CommandRef::Id(command) = &button.on_activate else { panic!("not a command id") }; assert!(!commands_declared(undeclared).contains(&command.id.as_str())); - // The surface uses `shared-id` and so does the composition its Use expands to. + // The composition emits `shared-id`, which expands to `dup-use/shared-id`: the surface authors that id. let dup = by("duplicate-id"); let children = box_children(&dup.root); - assert!(children.iter().any(|node| matches!(node, Node::Text(text) if text.common.id.as_str() == "shared-id"))); + assert!(children.iter().any(|node| matches!(node, Node::Text(text) if text.common.id.as_str() == "dup-use/shared-id"))); let Node::Use(used) = &children[0] else { panic!("not a Use") }; let composition = set.compositions.iter().find(|composition| composition.name == used.composition.name).unwrap(); assert!(box_children(&composition.body).iter().any(|node| matches!(node, Node::Text(text) if text.common.id.as_str() == "shared-id"))); @@ -226,11 +228,10 @@ fn arm(node: &Node) -> &'static str { } } -// The thirteen arms the fixtures place. Slot (arm 13) is not among them: a Slot stands only in a composition body, -// and placing one in f09 is resolve's cut, not the fixtures'. -const ALL_ARMS: [&str; 13] = [ - "Box", "Button", "Embed", "Image", "Overlay", "Plot", "Repeat", "Select", "Slider", "Text", "TextInput", "Toggle", - "Use", +// The fourteen arms the fixtures place; the Slot stands in f09's composition body. +const ALL_ARMS: [&str; 14] = [ + "Box", "Button", "Embed", "Image", "Overlay", "Plot", "Repeat", "Select", "Slider", "Slot", "Text", "TextInput", + "Toggle", "Use", ]; /// Every node under `node`, itself first, through every child position the union has. @@ -271,7 +272,7 @@ fn holds(fixture: Fixture, wanted: &[&str]) { } #[test] -fn the_twelve_fixtures_cover_all_thirteen_node_arms() { +fn the_twelve_fixtures_cover_all_fourteen_node_arms() { let mut covered = std::collections::BTreeSet::new(); for fixture in Fixture::ALL { covered.extend(arms_of(fixture));