diff --git a/Cargo.lock b/Cargo.lock index 42c4049..9628970 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,12 +17,30 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + [[package]] name = "autocfg" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -65,10 +83,29 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cultcache-rs" -version = "0.2.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7#b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7" +version = "0.3.1" +source = "git+https://github.com/GameCult/CultLib.git?rev=4c9af401ae33812d862dde4ff3131433fc73c7dc#4c9af401ae33812d862dde4ff3131433fc73c7dc" dependencies = [ "anyhow", "chrono", @@ -79,20 +116,33 @@ dependencies = [ "serde", "serde_bytes", "serde_json", + "serde_stacker", + "sha2", + "stacker", "uuid", - "windows-sys", + "windows-sys 0.59.0", ] [[package]] name = "cultcache-rs-derive" -version = "0.1.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7#b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7" +version = "0.2.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=4c9af401ae33812d862dde4ff3131433fc73c7dc#4c9af401ae33812d862dde4ff3131433fc73c7dc" dependencies = [ "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "find-msvc-tools" version = "0.1.14" @@ -133,6 +183,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -212,6 +272,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -233,6 +302,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "quote" version = "1.0.47" @@ -335,6 +414,28 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_stacker" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a" +dependencies = [ + "serde", + "serde_core", + "stacker", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -347,6 +448,19 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "syn" version = "2.0.119" @@ -385,6 +499,7 @@ dependencies = [ name = "thing-core" version = "0.1.0" dependencies = [ + "stacker", "thing-contract", "thing-testkit", ] @@ -400,6 +515,12 @@ dependencies = [ "thing-core", ] +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.26" @@ -417,6 +538,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -552,6 +679,15 @@ dependencies = [ "windows-targets", ] +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-targets" version = "0.52.6" diff --git a/Cargo.toml b/Cargo.toml index d4018b6..4902143 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,6 @@ resolver = "2" [workspace.dependencies] anyhow = "1" -cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7", package = "cultcache-rs" } +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "4c9af401ae33812d862dde4ff3131433fc73c7dc", package = "cultcache-rs" } serde = { version = "1", features = ["derive"] } rmp-serde = "1.3" diff --git a/crates/thing-contract/src/asset.rs b/crates/thing-contract/src/asset.rs index 9e97d7e..0827521 100644 --- a/crates/thing-contract/src/asset.rs +++ b/crates/thing-contract/src/asset.rs @@ -28,7 +28,7 @@ pub struct AssetCatalog { pub catalog_id: Segment, #[cultcache(key = 2)] pub version: Version, - #[cultcache(key = 3)] + #[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray")] pub assets: Vec, } diff --git a/crates/thing-contract/src/command.rs b/crates/thing-contract/src/command.rs index 6db6a88..9daf1c3 100644 --- a/crates/thing-contract/src/command.rs +++ b/crates/thing-contract/src/command.rs @@ -37,6 +37,7 @@ pub enum CommandRef { /// A typed record of the declared `payload_schema`, as its MessagePack bytes. #[derive(Clone, Debug, PartialEq, CultSlots)] +#[cultcache(type_name = "GameCult.Thing.Contract.RecordPayload")] pub struct RecordPayload { #[cultcache(key = 0)] pub schema: SchemaId, @@ -105,7 +106,7 @@ pub struct CommandInvocation { pub command: CommandId, #[cultcache(key = 4)] pub payload: RecordPayload, - #[cultcache(key = 5)] + #[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray")] pub captured: Vec, #[cultcache(key = 6)] pub client: String, diff --git a/crates/thing-contract/src/domain.rs b/crates/thing-contract/src/domain.rs index 59e26b0..09a5d45 100644 --- a/crates/thing-contract/src/domain.rs +++ b/crates/thing-contract/src/domain.rs @@ -9,6 +9,7 @@ use std::fmt; +use cultcache_rs::CultTypeName; use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; /// A value was outside its domain. Names the domain and its bound, never the value. @@ -72,6 +73,13 @@ impl std::error::Error for DomainError {} #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Seq(i32); +impl CultTypeName for Seq { + fn cult_type_name() -> String { + "System.Int32".to_string() + } + const VALUE_TYPE: bool = true; +} + impl Seq { pub const FIRST: Seq = Seq(1); @@ -108,6 +116,13 @@ impl Seq { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Version(i64); +impl CultTypeName for Version { + fn cult_type_name() -> String { + "System.Int64".to_string() + } + const VALUE_TYPE: bool = true; +} + impl Version { pub fn new(value: i64) -> Result { if value >= 0 { Ok(Self(value)) } else { Err(DomainError::new("Version", "at least 0")) } @@ -166,6 +181,12 @@ impl Count { #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Segment(String); +impl CultTypeName for Segment { + fn cult_type_name() -> String { + "System.String".to_string() + } +} + impl Segment { pub fn new(value: impl Into) -> Result { let value = value.into(); diff --git a/crates/thing-contract/src/keys.rs b/crates/thing-contract/src/keys.rs index f6de211..32b603e 100644 --- a/crates/thing-contract/src/keys.rs +++ b/crates/thing-contract/src/keys.rs @@ -1,5 +1,6 @@ //! Identifier newtypes and the record key of each kind. No caller spells a key as a free string. +use cultcache_rs::CultTypeName; use serde::{Deserialize, Serialize}; use crate::domain::{Segment, Seq, Version}; @@ -20,6 +21,12 @@ macro_rules! id_type { &self.0 } } + + impl CultTypeName for $name { + fn cult_type_name() -> String { + "System.String".to_string() + } + } }; } diff --git a/crates/thing-contract/src/lib.rs b/crates/thing-contract/src/lib.rs index 2edc6ed..39c72a0 100644 --- a/crates/thing-contract/src/lib.rs +++ b/crates/thing-contract/src/lib.rs @@ -8,11 +8,6 @@ //! `Deserialize` (CultCache's `DatabaseEntry` requires it). The domains therefore live in the //! field types (`Seq`, `Version`, `Count`, `Segment`), whose `Deserialize` calls the same //! `new` the constructors call, so no door skips a check. -//! -//! Hazard: decoding these kinds from untrusted bytes on a default-size thread can abort the -//! process inside CultCache's nesting bound before the bound refuses (the stack is not -//! bounded by nesting depth). The owner is `cultlib-gaps:follow_up:decode-stack-safety`; the -//! tests decode on a 16 MiB thread until it lands. mod asset; mod command; diff --git a/crates/thing-contract/src/node.rs b/crates/thing-contract/src/node.rs index b121722..8be831c 100644 --- a/crates/thing-contract/src/node.rs +++ b/crates/thing-contract/src/node.rs @@ -23,6 +23,7 @@ pub struct NodeCommon { } #[derive(Clone, Debug, PartialEq, CultUnion)] +#[cultcache(type_name = "GameCult.Thing.Contract.Node")] pub enum Node { #[cultcache(key = 0)] Box(BoxNode), @@ -444,7 +445,7 @@ pub struct SurfaceDocument { pub title: String, #[cultcache(key = 4)] pub root: Node, - #[cultcache(key = 5)] + #[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray")] pub commands: Vec, } @@ -464,7 +465,7 @@ pub struct CompositionDocument { pub name: Segment, #[cultcache(key = 2)] pub version: Version, - #[cultcache(key = 3)] + #[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray")] pub params: Vec, #[cultcache(key = 4)] pub body: Node, diff --git a/crates/thing-contract/src/result.rs b/crates/thing-contract/src/result.rs index d2a1bb9..99cd0f4 100644 --- a/crates/thing-contract/src/result.rs +++ b/crates/thing-contract/src/result.rs @@ -41,6 +41,7 @@ pub struct FailedOutcome { } #[derive(Clone, Debug, PartialEq, CultUnion)] +#[cultcache(type_name = "GameCult.Thing.Contract.Outcome")] pub enum Outcome { #[cultcache(key = 0)] Pending(PendingOutcome), diff --git a/crates/thing-contract/tests/catalog_members.rs b/crates/thing-contract/tests/catalog_members.rs new file mode 100644 index 0000000..1148b35 --- /dev/null +++ b/crates/thing-contract/tests/catalog_members.rs @@ -0,0 +1,60 @@ +//! The catalog rows the five document kinds publish are the rows the C# package declares: +//! `tests/thing-contract-parity/catalog-members.tsv`, which NameSetTests (C#) and parity.test.ts +//! (TypeScript) are held to as well. Schema ids differ by writer, so the comparison is by group, +//! as `catalogGroups` in parity.test.ts makes it. + +use std::path::PathBuf; + +use cultcache_rs::{DatabaseEntry, SchemaCatalogMember, SingleFileMessagePackBackingStore}; +use thing_contract::*; + +fn tsv_groups() -> Vec { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity/catalog-members.tsv"); + let text = std::fs::read_to_string(path).unwrap(); + let mut groups: Vec<(String, Vec)> = Vec::new(); + for row in text.lines().filter(|line| !line.trim().is_empty()) { + let (schema, rest) = row.split_once('\t').unwrap(); + match groups.iter_mut().find(|(id, _)| id == schema) { + Some((_, rows)) => rows.push(rest.to_string()), + None => groups.push((schema.to_string(), vec![rest.to_string()])), + } + } + sorted(groups.into_iter().map(|(_, rows)| rows.join("\n")).collect()) +} + +fn group(members: &[SchemaCatalogMember]) -> String { + members.iter().map(|m| format!("{}\t{}\t{}", m.slot, m.member_name, m.type_name)).collect::>().join("\n") +} + +fn sorted(mut groups: Vec) -> Vec { + groups.sort(); + groups +} + +#[test] +fn rows_equal_the_csharp_file() { + let mine = sorted(vec![ + group(&SurfaceDocument::schema_members()), + group(&CompositionDocument::schema_members()), + group(&CommandInvocation::schema_members()), + group(&CommandResult::schema_members()), + group(&AssetCatalog::schema_members()), + ]); + assert_eq!(mine, tsv_groups()); +} + +#[test] +fn the_written_store_carries_the_rows() { + // goldens.rs writes a store of one record per kind and compares it byte for byte with the + // committed surface.cc, so the committed file's catalog is the catalog the crate writes. It is + // copied first: reading a store creates a lock file beside it. + let committed = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens/surface.cc"); + let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("catalog-members"); + std::fs::create_dir_all(&work).unwrap(); + let copy = work.join("surface.cc"); + std::fs::copy(committed, ©).unwrap(); + let catalog = SingleFileMessagePackBackingStore::new(©).pull_schema_catalog().unwrap(); + let from_store = sorted(catalog.iter().map(|entry| group(&entry.members)).collect()); + assert_eq!(from_store, tsv_groups()); + let _ = std::fs::remove_dir_all(&work); +} diff --git a/crates/thing-contract/tests/goldens.rs b/crates/thing-contract/tests/goldens.rs index ea96c3d..8a74b28 100644 --- a/crates/thing-contract/tests/goldens.rs +++ b/crates/thing-contract/tests/goldens.rs @@ -642,13 +642,6 @@ fn refusal_cases() { #[test] fn deep_tree() { - // Decoding a Node costs tens of KiB of debug stack per nesting level, so the chain runs on a - // thread that has the room; the 2 MiB default does not. The hazard is CultCache's, owned by - // cultlib-gaps:follow_up:decode-stack-safety; the test stays on the big thread until it lands. - std::thread::Builder::new().stack_size(16 * 1024 * 1024).spawn(deep_tree_body).unwrap().join().unwrap(); -} - -fn deep_tree_body() { // A 64-deep Box chain. let mut chain = text("leaf", "bottom"); for depth in (0..64).rev() { diff --git a/crates/thing-contract/tests/goldens/surface.cc b/crates/thing-contract/tests/goldens/surface.cc index 38d494f..a0f7d1b 100644 Binary files a/crates/thing-contract/tests/goldens/surface.cc and b/crates/thing-contract/tests/goldens/surface.cc differ diff --git a/crates/thing-core/Cargo.toml b/crates/thing-core/Cargo.toml index 36ce641..d12f760 100644 --- a/crates/thing-core/Cargo.toml +++ b/crates/thing-core/Cargo.toml @@ -7,6 +7,7 @@ publish = false [dependencies] thing-contract = { path = "../thing-contract" } +stacker = "0.1.25" [dev-dependencies] thing-testkit = { path = "../thing-testkit" } diff --git a/crates/thing-core/src/resolve/expand.rs b/crates/thing-core/src/resolve/expand.rs index a6174fb..5dc22b5 100644 --- a/crates/thing-core/src/resolve/expand.rs +++ b/crates/thing-core/src/resolve/expand.rs @@ -18,8 +18,8 @@ use super::{Limits, std as thing_std, validate}; /// 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. +/// over it would overflow the stack. The recursion grows its own stack (`super::grow`), so the bound +/// holds on any thread. const STACK_BOUND: usize = 1024; /// A fault the nearest enclosing Use turns into a placeholder (`Invalid`), or one that ends the @@ -294,7 +294,7 @@ impl<'a> Expander<'a> { (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()); + out.extend(arg.nodes.iter().map(clone_deep)); } other => return wrong_kind(&slot.param, other, "a slot"), }, @@ -305,6 +305,10 @@ impl<'a> Expander<'a> { } fn node(&mut self, node: &Node, scope: Option<&Scope>, depth: usize, root: bool) -> Res { + super::grow(|| self.node_at(node, scope, depth, root)) + } + + fn node_at(&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"))); } @@ -537,6 +541,42 @@ impl<'a> Expander<'a> { } /// The id of a body root. A Slot has none, and the body fails on it before an id is read. +/// A copy of an expanded subtree that grows its own stack. The derived `Clone` of `Node` costs about +/// 12 KiB of debug stack per level, so a spliced slot argument up to `STACK_BOUND` levels deep would +/// overflow it; each container here recurses through `grow`. An expanded subtree holds no Slot and no +/// Use with arguments, so the four containers are the only nodes that hold nodes. +fn clone_deep(node: &Node) -> Node { + super::grow(|| match node { + Node::Box(b) => Node::Box(BoxNode { + common: b.common.clone(), + style: b.style.clone(), + paint: b.paint.clone(), + role: b.role.clone(), + children: b.children.iter().map(clone_deep).collect(), + }), + Node::Button(b) => Node::Button(ButtonNode { + common: b.common.clone(), + content: b.content.iter().map(clone_deep).collect(), + on_activate: b.on_activate.clone(), + enabled: b.enabled.clone(), + }), + Node::Overlay(o) => Node::Overlay(OverlayNode { + common: o.common.clone(), + anchor: o.anchor.clone(), + modal: o.modal, + dismiss: o.dismiss.clone(), + children: o.children.iter().map(clone_deep).collect(), + }), + Node::Repeat(r) => Node::Repeat(RepeatNode { + common: r.common.clone(), + collection: r.collection.clone(), + key_member: r.key_member.clone(), + template: std::boxed::Box::new(clone_deep(&r.template)), + }), + other => other.clone(), + }) +} + fn body_id(node: &Node) -> NodeId { match node { Node::Box(n) => n.common.id.clone(), diff --git a/crates/thing-core/src/resolve/mod.rs b/crates/thing-core/src/resolve/mod.rs index 13d827e..002eb9f 100644 --- a/crates/thing-core/src/resolve/mod.rs +++ b/crates/thing-core/src/resolve/mod.rs @@ -12,6 +12,17 @@ use thing_contract::SurfaceDocument; use crate::diagnostic::{Code, Diagnostic}; use crate::port::{Address, StatePort}; +/// Stack left below which recursion moves to a fresh segment, and the segment's size: the values +/// cultcache-rs uses for decode. Every recursion over a tree runs through `grow`, so a tree as deep +/// as `STACK_BOUND` resolves on a default thread. +const RED_ZONE: usize = 512 * 1024; +const SEGMENT: usize = 2 * 1024 * 1024; + +/// Runs one recursive step with room for the next, growing the stack when it is nearly spent. +fn grow(step: impl FnOnce() -> R) -> R { + stacker::maybe_grow(RED_ZONE, SEGMENT, step) +} + /// The bounds of one expansion. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Limits { @@ -81,7 +92,17 @@ pub fn resolve(document: &SurfaceDocument, port: &dyn StatePort, limits: &Limits 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() } }) + // Field by field: `..document.clone()` would clone the whole input tree to discard it. + (!refused).then(|| ResolvedTree { + document: SurfaceDocument { + provider_id: document.provider_id.clone(), + label: document.label.clone(), + version: document.version, + title: document.title.clone(), + root, + commands: document.commands.clone(), + }, + }) }); Resolution { tree, diagnostics, reads } } diff --git a/crates/thing-core/src/resolve/validate.rs b/crates/thing-core/src/resolve/validate.rs index 1357cde..4244e42 100644 --- a/crates/thing-core/src/resolve/validate.rs +++ b/crates/thing-core/src/resolve/validate.rs @@ -41,7 +41,7 @@ fn id(node: &Node) -> Option<&NodeId> { /// Nodes in the subtree, the node itself included. pub(super) fn size(node: &Node) -> usize { - 1 + children(node).iter().map(size).sum::() + super::grow(|| 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. @@ -73,3 +73,38 @@ pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec left { + let burn = [0u8; 4096]; + std::hint::black_box(&burn); + with_stack_left(left, work); + std::hint::black_box(&burn); + } else { + work(); + } + } + + #[test] + fn size_of_a_deep_subtree_grows_its_own_stack() { + // expand counts a slot argument with `size` after the argument was expanded, from wherever the + // stack stands; a 1,000-level argument must not run it out. + let mut deep = text("bottom", "x"); + for level in 1..1000 { + deep = boxed(&format!("level-{level}"), vec![deep]); + } + let mut counted = 0; + with_stack_left(100 * 1024, &mut || counted = size(&deep)); + assert_eq!(counted, 1000); + // Dropping a tree this deep needs the room the test thread has outside `with_stack_left`. + } +} diff --git a/crates/thing-core/tests/goldens/resolve-f09-composition-stack.bin b/crates/thing-core/tests/goldens/resolve-f09-composition-stack.bin index 259dc2c..147eb0f 100644 Binary files a/crates/thing-core/tests/goldens/resolve-f09-composition-stack.bin 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 index 671d184..9c191d0 100644 --- a/crates/thing-core/tests/goldens/resolve-f09-composition-stack.txt +++ b/crates/thing-core/tests/goldens/resolve-f09-composition-stack.txt @@ -291,7 +291,7 @@ SurfaceDocument { steps: [ Name( MemberName { - name: "load", + name: "Load", }, ), ], @@ -468,7 +468,7 @@ SurfaceDocument { steps: [ Name( MemberName { - name: "id", + name: "Id", }, ), ], @@ -493,7 +493,7 @@ SurfaceDocument { steps: [ Name( MemberName { - name: "name", + name: "Name", }, ), ], @@ -722,7 +722,7 @@ SurfaceDocument { steps: [ Name( MemberName { - name: "id", + name: "Id", }, ), ], @@ -747,7 +747,7 @@ SurfaceDocument { steps: [ Name( MemberName { - name: "name", + name: "Name", }, ), ], diff --git a/crates/thing-core/tests/resolve.rs b/crates/thing-core/tests/resolve.rs index 949cd37..7f70c96 100644 --- a/crates/thing-core/tests/resolve.rs +++ b/crates/thing-core/tests/resolve.rs @@ -13,13 +13,16 @@ 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"; +/// Room for a test that clones, prints or compares a deep Node: the contract's derived Clone, Debug +/// and PartialEq cost about 12 KiB of debug stack per level, so a 256-level tree overflows a default +/// thread outside resolve (reported as thing2:cut_report:cut-bind-pin.h1). The tests that run resolve +/// itself on a default thread do not use this. +fn with_room(work: impl FnOnce()) { + stacker::grow(64 * 1024 * 1024, work); +} + fn surface(root: Node, commands: &[&str]) -> SurfaceDocument { SurfaceDocument { provider_id: ProviderId::new("provider.t"), @@ -189,138 +192,128 @@ fn fixture_resolution(fixture: Fixture, label: &str) -> Resolution { #[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(); + with_room(f09_expands_body); +} - // 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"))); +fn f09_expands_body() { + 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 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")); + // 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"))); - // 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")); + // 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")); - 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")); - }); + // 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"); + 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"); - }); + // 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"); - }); + 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)); - }); + 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"))); - }); + 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"); - } - }); + // 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())); + 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")); - }); + // 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 { @@ -334,348 +327,326 @@ fn refused_for_limit(resolution: &Resolution) { #[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))); + // 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))); + // 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()); - }); + // 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))); - }); + // 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())); + with_room(a_tree_deeper_than_the_limit_is_refused_body); +} - // 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"))); - }); +fn a_tree_deeper_than_the_limit_is_refused_body() { + 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}"); - } - }); + 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'"); - }); + 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)); + 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); - }); + // 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()); + // 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()); - } - }); + 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()); - } + 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 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"]); - }); + // 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}"); - } + // 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"); - } - }); + // 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; - }); + 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}"); - } - }); + 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 { @@ -685,214 +656,200 @@ fn root_common_of(resolution: &Resolution, id: &str) -> NodeCommon { #[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)])) - }; + 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"))); + // 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); + // 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)); - }); + // 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}"); - } + 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 { + 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: RecordKey::new(key), + key_prefix: "row-".into(), }), - 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); + 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}"); - } + 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"); - }); + // 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"); + 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); - }); + // 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. @@ -907,57 +864,145 @@ fn chain(levels: usize, repeats: bool) -> 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}"); - } - }); + 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"]); - }); + 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"]); +} + +/// Runs `work` on a thread with the default stack: resolve grows its own, so no caller sizes one. +fn on_default_thread(work: impl FnOnce() -> T + Send + 'static) -> T { + std::thread::spawn(work).join().unwrap() +} + +/// The way a chain nests: the child list or position through which each level holds the next. +#[derive(Clone, Copy, Debug)] +enum Through { + BoxChildren, + RepeatTemplate, + ButtonContent, + OverlayChildren, + SlotArgument, +} + +/// A chain of `levels` nodes, the first the root, each holding the next through `through`; a slot +/// argument chain is Uses (the body composition is `c`), so its levels are Uses over a Text leaf. +fn nested(levels: usize, through: Through) -> Node { + let mut node = text("bottom", "x"); + for level in 1..levels { + let id = format!("level-{level}"); + node = match through { + Through::BoxChildren => boxed(&id, vec![node]), + Through::RepeatTemplate => repeat(&id, node), + Through::ButtonContent => { + let Node::Button(button) = button(&id, command("go")) else { unreachable!() }; + Node::Button(ButtonNode { content: vec![node], ..button }) + } + Through::OverlayChildren => Node::Overlay(OverlayNode { + common: common(&id), + anchor: Anchor::Viewport, + modal: false, + dismiss: command("go"), + children: vec![node], + }), + Through::SlotArgument => use_of(&id, "c", vec![slot_arg("body", vec![node])]), + }; + } + node +} + +fn resolve_nested(levels: usize, through: Through) -> Resolution { + on_default_thread(move || { + let state = state_with(&[composition("c", &[("body", ParamKind::Slot)], boxed("b", vec![slot("body")]))]); + run(&surface(nested(levels, through), &["go"]), &state) + }) +} + +fn too_deep_to_resolve(resolution: &Resolution) -> bool { + resolution.diagnostics.iter().any(|found| found.code == Code::TooDeepToResolve) } #[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); - }); + let resolution = resolve_nested(1100, Through::BoxChildren); + assert!(resolution.tree.is_none()); + assert_eq!(resolution.diagnostics.len(), 1, "{:?}", resolution.diagnostics); + assert_eq!(resolution.diagnostics[0].code, Code::TooDeepToResolve); +} + +#[test] +fn a_chain_past_the_depth_rule_and_within_the_stack_bound_resolves_then_is_refused_for_depth() { + let resolution = resolve_nested(1000, Through::BoxChildren); + refused_for_limit(&resolution); + assert!(!too_deep_to_resolve(&resolution), "{:?}", resolution.diagnostics); +} + +/// The bound is reached without overflow (the splice's clone and every drop run on the same default +/// thread), and one level past it is `TooDeepToResolve`, whichever way the levels nest. +fn stack_bound_counts(through: Through) { + let at_bound = resolve_nested(1024, through); + assert!(!too_deep_to_resolve(&at_bound), "{through:?}: {:?}", at_bound.diagnostics); + let past = resolve_nested(1025, through); + assert!(past.tree.is_none(), "{through:?}"); + assert!(too_deep_to_resolve(&past), "{through:?}: {:?}", past.diagnostics); +} + +#[test] +fn the_stack_bound_is_inclusive() { + // 1,024 levels is the deepest the expander recurses into; the depth rule refuses it later. + let at_bound = resolve_nested(1024, Through::BoxChildren); + refused_for_limit(&at_bound); + assert!(!too_deep_to_resolve(&at_bound), "{:?}", at_bound.diagnostics); +} + +#[test] +fn the_stack_bound_counts_box_children() { + stack_bound_counts(Through::BoxChildren); +} + +#[test] +fn the_stack_bound_counts_a_repeat_template() { + stack_bound_counts(Through::RepeatTemplate); +} + +#[test] +fn the_stack_bound_counts_button_content() { + stack_bound_counts(Through::ButtonContent); +} + +#[test] +fn the_stack_bound_counts_overlay_children() { + stack_bound_counts(Through::OverlayChildren); +} + +#[test] +fn the_stack_bound_counts_a_slot_argument() { + stack_bound_counts(Through::SlotArgument); } #[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"); - }); + 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/f01-swarm-dashboard.surface.cc b/crates/thing-testkit/fixtures/f01-swarm-dashboard.surface.cc index c09bf88..2ba4218 100644 Binary files a/crates/thing-testkit/fixtures/f01-swarm-dashboard.surface.cc and b/crates/thing-testkit/fixtures/f01-swarm-dashboard.surface.cc differ diff --git a/crates/thing-testkit/fixtures/f02-login-effect.surface.cc b/crates/thing-testkit/fixtures/f02-login-effect.surface.cc index 213e0fb..7937541 100644 Binary files a/crates/thing-testkit/fixtures/f02-login-effect.surface.cc and b/crates/thing-testkit/fixtures/f02-login-effect.surface.cc differ diff --git a/crates/thing-testkit/fixtures/f03-input-target.surface.cc b/crates/thing-testkit/fixtures/f03-input-target.surface.cc index eb8c30b..3e80295 100644 Binary files a/crates/thing-testkit/fixtures/f03-input-target.surface.cc and b/crates/thing-testkit/fixtures/f03-input-target.surface.cc differ diff --git a/crates/thing-testkit/fixtures/f04-form.surface.cc b/crates/thing-testkit/fixtures/f04-form.surface.cc index 1f4f535..009661f 100644 Binary files a/crates/thing-testkit/fixtures/f04-form.surface.cc and b/crates/thing-testkit/fixtures/f04-form.surface.cc differ diff --git a/crates/thing-testkit/fixtures/f05-modal-overlay.surface.cc b/crates/thing-testkit/fixtures/f05-modal-overlay.surface.cc index c3ba4e1..01f6b69 100644 Binary files a/crates/thing-testkit/fixtures/f05-modal-overlay.surface.cc and b/crates/thing-testkit/fixtures/f05-modal-overlay.surface.cc differ diff --git a/crates/thing-testkit/fixtures/f06-scroll-list.surface.cc b/crates/thing-testkit/fixtures/f06-scroll-list.surface.cc index 022b44f..1b0740e 100644 Binary files a/crates/thing-testkit/fixtures/f06-scroll-list.surface.cc and b/crates/thing-testkit/fixtures/f06-scroll-list.surface.cc differ diff --git a/crates/thing-testkit/fixtures/f07-plot.surface.cc b/crates/thing-testkit/fixtures/f07-plot.surface.cc index 5a23735..9877b27 100644 Binary files a/crates/thing-testkit/fixtures/f07-plot.surface.cc and b/crates/thing-testkit/fixtures/f07-plot.surface.cc differ diff --git a/crates/thing-testkit/fixtures/f08-embed-viewport.surface.cc b/crates/thing-testkit/fixtures/f08-embed-viewport.surface.cc index 4d44b35..b77db80 100644 Binary files a/crates/thing-testkit/fixtures/f08-embed-viewport.surface.cc and b/crates/thing-testkit/fixtures/f08-embed-viewport.surface.cc differ diff --git a/crates/thing-testkit/fixtures/f09-composition-stack.surface.cc b/crates/thing-testkit/fixtures/f09-composition-stack.surface.cc index e72f6bd..0447ecc 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 56e3926..614b081 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/fixtures/f11-deep.surface.cc b/crates/thing-testkit/fixtures/f11-deep.surface.cc index fd8a88c..f9374c5 100644 Binary files a/crates/thing-testkit/fixtures/f11-deep.surface.cc and b/crates/thing-testkit/fixtures/f11-deep.surface.cc differ diff --git a/crates/thing-testkit/fixtures/f12-text-edge.surface.cc b/crates/thing-testkit/fixtures/f12-text-edge.surface.cc index 73a766c..1ca91b2 100644 Binary files a/crates/thing-testkit/fixtures/f12-text-edge.surface.cc and b/crates/thing-testkit/fixtures/f12-text-edge.surface.cc differ diff --git a/crates/thing-testkit/src/fixture.rs b/crates/thing-testkit/src/fixture.rs index 59228a2..61f480b 100644 --- a/crates/thing-testkit/src/fixture.rs +++ b/crates/thing-testkit/src/fixture.rs @@ -194,7 +194,7 @@ fn swarm_ref(key: &str) -> StateSource { fn swarm_dashboard() -> SurfaceDocument { let load = Bind { source: swarm_ref("summary"), - member: path(&["load"]), + member: path(&["Load"]), format: Some(Format::Number(NumberFormat { precision: count(1), percent: true, unit: None })), }; let load_text = Node::Text(TextNode { @@ -212,10 +212,10 @@ fn swarm_dashboard() -> SurfaceDocument { schema: SchemaId::new(SWARM_SCHEMA), key_prefix: "mind-".into(), }), - key_member: path(&["id"]), + key_member: path(&["Id"]), template: std::boxed::Box::new(Node::Text(TextNode { common: common("mind-name"), - content: TextSource::Bound(item_bind(path(&["name"]))), + content: TextSource::Bound(item_bind(path(&["Name"]))), style_token: "body".into(), wrap: false, max_lines: Some(count(1)), @@ -258,7 +258,7 @@ const STACK: &str = "provider.stack"; /// A Use of the publisher's card with one argument of each arm and the given slot children. fn card_use(id: &str, slot: Vec) -> Node { - let source = Bind { source: swarm_ref("summary"), member: path(&["load"]), format: None }; + let source = Bind { source: swarm_ref("summary"), member: path(&["Load"]), format: None }; let rows = CollectionSource::Records(RecordsSource { provider: None, schema: SchemaId::new(SWARM_SCHEMA), @@ -292,7 +292,7 @@ fn composition_stack() -> SurfaceDocument { 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 }), + value: ArgValue::Bind(Bind { source: swarm_ref("summary"), member: path(&["Load"]), format: None }), }, ], }); @@ -323,10 +323,10 @@ fn stack_card() -> CompositionDocument { let rows = Node::Repeat(RepeatNode { common: common("card-rows"), collection: CollectionSource::Param(param("rows")), - key_member: path(&["id"]), + key_member: path(&["Id"]), template: std::boxed::Box::new(Node::Text(TextNode { common: common("card-row"), - content: TextSource::Bound(item_bind(path(&["name"]))), + content: TextSource::Bound(item_bind(path(&["Name"]))), style_token: "body".into(), wrap: false, max_lines: None, @@ -398,7 +398,7 @@ fn hostile() -> Vec { schema: SchemaId::new("gamecult.thing.test.nowhere.v1"), key: RecordKey::new("row-1"), }), - member: path(&["name"]), + member: path(&["Name"]), format: None, }), style_token: "body".into(), @@ -557,7 +557,7 @@ fn input_target() -> FixtureSet { }); let label = Node::Text(TextNode { common: common("target-label"), - content: TextSource::Bound(record_member(provider, "target", "cursor", &["label"])), + content: TextSource::Bound(record_member(provider, "target", "cursor", &["Label"])), style_token: "body".into(), wrap: false, max_lines: Some(count(1)), @@ -608,7 +608,7 @@ fn form() -> FixtureSet { let provider = "provider.settings"; let toggle = Node::Toggle(ToggleNode { common: common("enabled"), - checked: BoolSource::Bound(record_member(provider, "settings", "current", &["enabled"])), + checked: BoolSource::Bound(record_member(provider, "settings", "current", &["Enabled"])), on_change: command("save"), }); let slider = Node::Slider(SliderNode { @@ -616,7 +616,7 @@ fn form() -> FixtureSet { min: 0.0, max: 1.0, step: 0.05, - value: NumberSource::Bound(record_member(provider, "settings", "current", &["volume"])), + value: NumberSource::Bound(record_member(provider, "settings", "current", &["Volume"])), commit: command("save"), }); let select = Node::Select(SelectNode { @@ -627,7 +627,7 @@ fn form() -> FixtureSet { SelectOption { value: "light".into(), label: "Light".into() }, ], }), - value: record_member(provider, "settings", "current", &["theme"]), + value: record_member(provider, "settings", "current", &["Theme"]), on_change: command("save"), }); let port = text_input("port", InputKind::Number, "8080", command("save")); @@ -686,7 +686,7 @@ fn scroll_list() -> SurfaceDocument { role: Role::ListItem, children: vec![Node::Text(TextNode { common: common("item-title"), - content: TextSource::Bound(item_bind(path(&["title"]))), + content: TextSource::Bound(item_bind(path(&["Title"]))), style_token: "body".into(), wrap: false, max_lines: Some(count(1)), @@ -700,7 +700,7 @@ fn scroll_list() -> SurfaceDocument { schema: SchemaId::new(format!("{TEST_SCHEMA_ROOT}.item.v1")), key_prefix: "item-".into(), }), - key_member: path(&["id"]), + key_member: path(&["Id"]), template: std::boxed::Box::new(row), }); let mut list = style(); @@ -718,7 +718,7 @@ fn scroll_list() -> SurfaceDocument { fn plot() -> SurfaceDocument { let provider = "provider.market"; - let series = || record_member(provider, "series", "prices", &["values"]); + let series = || record_member(provider, "series", "prices", &["Values"]); let mark = |id: &str, mark: PlotMark, x: (Option, Option), y: (Option, Option)| { Node::Plot(PlotNode { common: common(id), diff --git a/crates/thing-testkit/src/store.rs b/crates/thing-testkit/src/store.rs index 5f20791..919a24b 100644 --- a/crates/thing-testkit/src/store.rs +++ b/crates/thing-testkit/src/store.rs @@ -20,6 +20,9 @@ pub fn create(path: &Path) -> CultCache { let _ = std::fs::remove_file(path); let mut cache = memory(); cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap(); + // From cultcache-rs 0.4 a cache that attached a store refuses writes until it pulls; the file + // was just removed, so the pull is empty. + cache.pull_all_backing_stores().unwrap(); cache } diff --git a/crates/thing-testkit/tests/fixtures.rs b/crates/thing-testkit/tests/fixtures.rs index 222f945..990b67e 100644 --- a/crates/thing-testkit/tests/fixtures.rs +++ b/crates/thing-testkit/tests/fixtures.rs @@ -10,61 +10,53 @@ use thing_testkit::mem_state::MemState; use thing_testkit::store; use thing_core::port::{Address, Lookup, StatePort}; -/// Decoding runs on a 16 MiB thread until the workspace pin of cultcache-rs carries -/// decode-stack-safety. -fn on_big_stack(work: impl FnOnce() -> T + Send + 'static) -> T { - std::thread::Builder::new().stack_size(16 * 1024 * 1024).spawn(work).unwrap().join().unwrap() -} - fn load(fixture: Fixture) -> FixtureSet { - on_big_stack(move || fixture.load()) + fixture.load() } #[test] fn every_fixture_round_trips_through_the_contract() { - on_big_stack(|| { - for fixture in Fixture::ALL { - // The builders reproduce the committed file byte for byte (or bless it). - let committed = fixture.write(); - assert_eq!(committed, std::fs::read(Fixture::dir().join(fixture.file_name())).unwrap()); - assert!(!committed.is_empty()); - let built = fixture.build(); - let loaded = fixture.load(); - assert_eq!(loaded, built, "{}: the store decodes to the built documents", fixture.file_name()); + for fixture in Fixture::ALL { + // The builders reproduce the committed file byte for byte (or bless it). + let committed = fixture.write(); + assert_eq!(committed, std::fs::read(Fixture::dir().join(fixture.file_name())).unwrap()); + assert!(!committed.is_empty()); + let built = fixture.build(); + let loaded = fixture.load(); + assert_eq!(loaded, built, "{}: the store decodes to the built documents", fixture.file_name()); - // Each record re-encodes to its stored payload. - let cache = fixture.open(); - let stored = cache.snapshot_envelopes(); - let payload = |kind: &str, key: String| { - stored.iter().find(|envelope| envelope.r#type == kind && envelope.key == key).unwrap().payload.clone() - }; - for surface in &loaded.surfaces { - assert_eq!(rmp_serde::to_vec(surface).unwrap(), payload("gamecult.thing.surface", surface.record_key())); - } - for composition in &loaded.compositions { - let key = composition.record_key(); - assert_eq!(rmp_serde::to_vec(composition).unwrap(), payload("gamecult.thing.composition", key)); - } - for catalog in &loaded.catalogs { - assert_eq!(rmp_serde::to_vec(catalog).unwrap(), payload("gamecult.thing.asset_catalog", catalog.record_key())); - } - for invocation in &loaded.invocations { - let key = invocation.record_key(); - assert_eq!(rmp_serde::to_vec(invocation).unwrap(), payload("gamecult.thing.command_invocation", key)); - } - for result in &loaded.results { - assert_eq!(rmp_serde::to_vec(result).unwrap(), payload("gamecult.thing.command_result", result.record_key())); - } - assert_eq!( - stored.len(), - loaded.document_count(), - "{}: the store holds the documents and nothing else", - fixture.file_name() - ); + // Each record re-encodes to its stored payload. + let cache = fixture.open(); + let stored = cache.snapshot_envelopes(); + let payload = |kind: &str, key: String| { + stored.iter().find(|envelope| envelope.r#type == kind && envelope.key == key).unwrap().payload.clone() + }; + for surface in &loaded.surfaces { + assert_eq!(rmp_serde::to_vec(surface).unwrap(), payload("gamecult.thing.surface", surface.record_key())); } - // The payload one Box level past f11's chain is a raw file, not a store. - assert_eq!(Fixture::write_deep_refused(), Fixture::deep_refused_payload()); - }); + for composition in &loaded.compositions { + let key = composition.record_key(); + assert_eq!(rmp_serde::to_vec(composition).unwrap(), payload("gamecult.thing.composition", key)); + } + for catalog in &loaded.catalogs { + assert_eq!(rmp_serde::to_vec(catalog).unwrap(), payload("gamecult.thing.asset_catalog", catalog.record_key())); + } + for invocation in &loaded.invocations { + let key = invocation.record_key(); + assert_eq!(rmp_serde::to_vec(invocation).unwrap(), payload("gamecult.thing.command_invocation", key)); + } + for result in &loaded.results { + assert_eq!(rmp_serde::to_vec(result).unwrap(), payload("gamecult.thing.command_result", result.record_key())); + } + assert_eq!( + stored.len(), + loaded.document_count(), + "{}: the store holds the documents and nothing else", + fixture.file_name() + ); + } + // The payload one Box level past f11's chain is a raw file, not a store. + assert_eq!(Fixture::write_deep_refused(), Fixture::deep_refused_payload()); } fn commands_declared(surface: &SurfaceDocument) -> Vec<&str> { @@ -171,7 +163,7 @@ fn f10_holds_exactly_the_four_hostile_surfaces() { #[test] fn a_state_holds_every_fixture_document_under_its_publisher() { - let state = on_big_stack(|| MemState::from_fixture(Fixture::F09CompositionStack)); + let state = MemState::from_fixture(Fixture::F09CompositionStack); let set = load(Fixture::F09CompositionStack); let at = Address { provider: ProviderId::new(set.compositions[0].publisher.clone()), @@ -393,7 +385,7 @@ fn f06_scrolls_a_repeat_over_a_records_prefix() { assert_eq!(root.style.overflow, Overflow::Scroll); let [Node::Repeat(items)] = &root.children[..] else { panic!("one Repeat expected") }; assert!(matches!(&items.collection, CollectionSource::Records(records) if !records.key_prefix.is_empty())); - assert_eq!(items.key_member, thing_testkit::build::path(&["id"])); + assert_eq!(items.key_member, thing_testkit::build::path(&["Id"])); } #[test] @@ -424,45 +416,43 @@ fn f08_embeds_a_fixed_size_leaf_among_siblings() { #[test] fn f11_is_the_deepest_chain_the_bound_admits_and_one_more_level_is_refused() { - on_big_stack(|| { - let (set, surface) = single_surface(Fixture::F11Deep); - let cache = Fixture::F11Deep.open(); - let stored = cache.snapshot_envelopes(); - assert_eq!(stored.len(), 1); - // The committed surface passes CultCache's own check and decodes to the built chain. - assert_eq!(check_payload_depth(&stored[0].payload), Ok(())); - assert_eq!(rmp_serde::to_vec(&surface).unwrap(), stored[0].payload); - let levels = { - let mut levels = 0; - let mut node = &surface.root; - while let Node::Box(boxed) = node { - levels += 1; - match boxed.children.first() { - Some(child) => node = child, - None => break, - } + let (set, surface) = single_surface(Fixture::F11Deep); + let cache = Fixture::F11Deep.open(); + let stored = cache.snapshot_envelopes(); + assert_eq!(stored.len(), 1); + // The committed surface passes CultCache's own check and decodes to the built chain. + assert_eq!(check_payload_depth(&stored[0].payload), Ok(())); + assert_eq!(rmp_serde::to_vec(&surface).unwrap(), stored[0].payload); + let levels = { + let mut levels = 0; + let mut node = &surface.root; + while let Node::Box(boxed) = node { + levels += 1; + match boxed.children.first() { + Some(child) => node = child, + None => break, } - levels - }; - assert!(levels > 1, "a chain, not one Box"); - assert_eq!(set.surfaces.len(), 1); + } + levels + }; + assert!(levels > 1, "a chain, not one Box"); + assert_eq!(set.surfaces.len(), 1); - // One Box level deeper is refused by the check, naming depth 257, and by CultCache. - let refused = golden::read(&Fixture::dir(), Fixture::DEEP_REFUSED); - assert_eq!(refused, Fixture::deep_refused_payload()); - assert_eq!(check_payload_depth(&refused), Err(PayloadTooDeep { depth: 257, limit: 256 })); - let mut cache = store::memory(); - let envelope = CultCacheEnvelope { - key: surface.record_key(), - r#type: "gamecult.thing.surface".into(), - payload: refused, - stored_at: store::PINNED_CLOCK.into(), - schema_id: Some("gamecult.thing.surface.v1".into()), - }; - let error = cache.put_raw_envelope(envelope).unwrap_err(); - assert!(error.downcast_ref::().is_some(), "{error:#}"); - assert!(cache.get::(&surface.record_key()).unwrap().is_none()); - }); + // One Box level deeper is refused by the check, naming depth 257, and by CultCache. + let refused = golden::read(&Fixture::dir(), Fixture::DEEP_REFUSED); + assert_eq!(refused, Fixture::deep_refused_payload()); + assert_eq!(check_payload_depth(&refused), Err(PayloadTooDeep { depth: 257, limit: 256 })); + let mut cache = store::memory(); + let envelope = CultCacheEnvelope { + key: surface.record_key(), + r#type: "gamecult.thing.surface".into(), + payload: refused, + stored_at: store::PINNED_CLOCK.into(), + schema_id: Some("gamecult.thing.surface.v1".into()), + }; + let error = cache.put_raw_envelope(envelope).unwrap_err(); + assert!(error.downcast_ref::().is_some(), "{error:#}"); + assert!(cache.get::(&surface.record_key()).unwrap().is_none()); } #[test] diff --git a/crates/thing-testkit/tests/scratch.rs b/crates/thing-testkit/tests/scratch.rs index 9b91344..5f7c126 100644 --- a/crates/thing-testkit/tests/scratch.rs +++ b/crates/thing-testkit/tests/scratch.rs @@ -17,15 +17,8 @@ fn scratch_entries() -> Vec { #[test] fn writing_a_fixture_leaves_no_scratch_file_or_lock_behind() { let before = scratch_entries(); - let stack = std::thread::Builder::new().stack_size(16 * 1024 * 1024); - stack - .spawn(|| { - for fixture in Fixture::ALL { - fixture.write(); - } - }) - .unwrap() - .join() - .unwrap(); + for fixture in Fixture::ALL { + fixture.write(); + } assert_eq!(scratch_entries(), before); } diff --git a/docs/thing2-map.md b/docs/thing2-map.md index 75ca59b..448c512 100644 --- a/docs/thing2-map.md +++ b/docs/thing2-map.md @@ -509,9 +509,8 @@ summary. `file:` path to the published version, and both packages get a release line. Until then both read CultLib from the sibling checkout at the Cargo rev (P22). - - CultLib pin bump: when `cultlib-gaps:follow_up:decode-stack-safety` lands, - move the pin and run `deep_tree` on the default thread (its 16 MiB thread - goes); the crate docs' hazard note goes with it. + - CultLib pin bump: done at CultLib `4c9af401` (cut bind-pin); `deep_tree` + runs on the default thread and the crate docs' hazard note is gone. - Missing-slot golden: re-added only when `cultlib-gaps:follow_up:rust-missing-slot-vs-reference` settles the rule. 2. **Core**, in three cuts: (a) resolution, compositions with `thing.std`, diff --git a/packages/GameCult.Thing.Contract/Asset.cs b/packages/GameCult.Thing.Contract/Asset.cs index cc0054d..f7ef90e 100644 --- a/packages/GameCult.Thing.Contract/Asset.cs +++ b/packages/GameCult.Thing.Contract/Asset.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Collections.Immutable; using GameCult.Caching; using MessagePack; @@ -30,7 +31,7 @@ public sealed class AssetCatalog [Key(0)] public string ProviderId { get; } [Key(1)] public string CatalogId { get; } [Key(2)] public long Version { get; } - [Key(3)] public IReadOnlyList Assets { get; } + [Key(3)] public ImmutableArray Assets { get; } public AssetCatalog(string providerId, string catalogId, long version, IReadOnlyList assets) { diff --git a/packages/GameCult.Thing.Contract/Command.cs b/packages/GameCult.Thing.Contract/Command.cs index 193574c..eae7dbc 100644 --- a/packages/GameCult.Thing.Contract/Command.cs +++ b/packages/GameCult.Thing.Contract/Command.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using GameCult.Caching; using MessagePack; @@ -92,7 +93,7 @@ public sealed class CommandDecl { [Key(0)] public string Id { get; } [Key(1)] public string PayloadSchema { get; } - [Key(2)] public IReadOnlyList Captures { get; } + [Key(2)] public ImmutableArray Captures { get; } [Key(3)] public string? Confirm { get; } public CommandDecl(string id, string payloadSchema, IReadOnlyList captures, string? confirm) @@ -155,7 +156,7 @@ public sealed class CommandInvocation [Key(2)] public long SurfaceVersion { get; } [Key(3)] public string Command { get; } [Key(4)] public RecordPayload Payload { get; } - [Key(5)] public IReadOnlyList Captured { get; } + [Key(5)] public ImmutableArray Captured { get; } [Key(6)] public string Client { get; } [Key(7)] public string IssuedAt { get; } [Key(8)] public string? Delegation { get; } diff --git a/packages/GameCult.Thing.Contract/Domain.cs b/packages/GameCult.Thing.Contract/Domain.cs index ca23b16..b9d865b 100644 --- a/packages/GameCult.Thing.Contract/Domain.cs +++ b/packages/GameCult.Thing.Contract/Domain.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; namespace GameCult.Thing.Contract; @@ -50,15 +51,14 @@ public static class ThingDomain value ?? throw new ThingDomainException(slot, "present"); /// - /// A required list slot: a read-only copy, so the caller's list cannot change the value afterwards. A null list or - /// a null item is refused naming the slot. + /// A required list slot, as a whole-value holder: a copy, so the caller's list cannot change the value afterwards. + /// A null list, a default array (what a nil payload decodes to) or a null item is refused naming the slot. /// - public static IReadOnlyList Items(IReadOnlyList? items, string slot) where T : class + public static ImmutableArray Items(IReadOnlyList? items, string slot) where T : class { - if (items is null) throw new ThingDomainException(slot, "present"); - var copy = new T[items.Count]; - for (var i = 0; i < copy.Length; i++) - copy[i] = items[i] ?? throw new ThingDomainException(slot, "free of nil items"); - return Array.AsReadOnly(copy); + if (items is null || items is ImmutableArray { IsDefault: true }) throw new ThingDomainException(slot, "present"); + var builder = ImmutableArray.CreateBuilder(items.Count); + foreach (var item in items) builder.Add(item ?? throw new ThingDomainException(slot, "free of nil items")); + return builder.MoveToImmutable(); } } diff --git a/packages/GameCult.Thing.Contract/GameCult.Thing.Contract.csproj b/packages/GameCult.Thing.Contract/GameCult.Thing.Contract.csproj index cbb9156..4fc572a 100644 --- a/packages/GameCult.Thing.Contract/GameCult.Thing.Contract.csproj +++ b/packages/GameCult.Thing.Contract/GameCult.Thing.Contract.csproj @@ -18,5 +18,6 @@ + diff --git a/packages/GameCult.Thing.Contract/Node.cs b/packages/GameCult.Thing.Contract/Node.cs index 8b8bdd6..2ae7423 100644 --- a/packages/GameCult.Thing.Contract/Node.cs +++ b/packages/GameCult.Thing.Contract/Node.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Collections.Immutable; using GameCult.Caching; using MessagePack; @@ -30,7 +31,7 @@ public sealed class BoxNode : Node [Key(1)] public BoxStyle Style { get; } [Key(2)] public Paint Paint { get; } [Key(3)] public Role Role { get; } - [Key(4)] public IReadOnlyList Children { get; } + [Key(4)] public ImmutableArray Children { get; } public BoxNode(NodeCommon common, BoxStyle style, Paint paint, Role role, IReadOnlyList children) { @@ -86,7 +87,7 @@ public sealed class ImageNode : Node public sealed class ButtonNode : Node { [Key(0)] public NodeCommon Common { get; } - [Key(1)] public IReadOnlyList Content { get; } + [Key(1)] public ImmutableArray Content { get; } [Key(2)] public CommandRef OnActivate { get; } [Key(3)] public BoolSource Enabled { get; } @@ -197,7 +198,7 @@ public sealed class OverlayNode : Node [Key(1)] public Anchor Anchor { get; } [Key(2)] public bool Modal { get; } [Key(3)] public CommandRef Dismiss { get; } - [Key(4)] public IReadOnlyList Children { get; } + [Key(4)] public ImmutableArray Children { get; } public OverlayNode(NodeCommon common, Anchor anchor, bool modal, CommandRef dismiss, IReadOnlyList children) { @@ -256,7 +257,7 @@ public sealed class UseNode : Node { [Key(0)] public NodeCommon Common { get; } [Key(1)] public CompositionRef Composition { get; } - [Key(2)] public IReadOnlyList Args { get; } + [Key(2)] public ImmutableArray Args { get; } public UseNode(NodeCommon common, CompositionRef composition, IReadOnlyList args) { @@ -344,7 +345,7 @@ public abstract class OptionList [MessagePackObject] public sealed class LiteralOptions : OptionList { - [Key(0)] public IReadOnlyList Options { get; } + [Key(0)] public ImmutableArray Options { get; } public LiteralOptions(IReadOnlyList options) { @@ -502,7 +503,7 @@ public sealed class CommandArg : ArgValue [MessagePackObject] public sealed class SlotArg : ArgValue { - [Key(0)] public IReadOnlyList Nodes { get; } + [Key(0)] public ImmutableArray Nodes { get; } public SlotArg(IReadOnlyList nodes) { @@ -642,7 +643,7 @@ public sealed class SurfaceDocument [Key(2)] public long Version { get; } [Key(3)] public string Title { get; } [Key(4)] public Node Root { get; } - [Key(5)] public IReadOnlyList Commands { get; } + [Key(5)] public ImmutableArray Commands { get; } public SurfaceDocument(string providerId, string label, long version, string title, Node root, IReadOnlyList commands) { @@ -664,7 +665,7 @@ public sealed class CompositionDocument [Key(0)] public string Publisher { get; } [Key(1)] public string Name { get; } [Key(2)] public long Version { get; } - [Key(3)] public IReadOnlyList Params { get; } + [Key(3)] public ImmutableArray Params { get; } [Key(4)] public Node Body { get; } public CompositionDocument(string publisher, string name, long version, IReadOnlyList @params, Node body) diff --git a/packages/GameCult.Thing.Contract/Source.cs b/packages/GameCult.Thing.Contract/Source.cs index b794345..ad8120c 100644 --- a/packages/GameCult.Thing.Contract/Source.cs +++ b/packages/GameCult.Thing.Contract/Source.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Collections.Immutable; using GameCult.Caching; using MessagePack; @@ -327,7 +328,7 @@ public sealed class Bind [MessagePackObject] public sealed class MemberPath { - [Key(0)] public IReadOnlyList Steps { get; } + [Key(0)] public ImmutableArray Steps { get; } public MemberPath(IReadOnlyList steps) { diff --git a/packages/GameCult.Thing.Contract/Style.cs b/packages/GameCult.Thing.Contract/Style.cs index 7aeb814..23fd0da 100644 --- a/packages/GameCult.Thing.Contract/Style.cs +++ b/packages/GameCult.Thing.Contract/Style.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Collections.Immutable; using GameCult.Caching; using MessagePack; @@ -438,8 +439,8 @@ public sealed class BoxStyle [Key(16)] public double Grow { get; } [Key(17)] public double Shrink { get; } [Key(18)] public Dimension Basis { get; } - [Key(19)] public IReadOnlyList GridColumns { get; } - [Key(20)] public IReadOnlyList GridRows { get; } + [Key(19)] public ImmutableArray GridColumns { get; } + [Key(20)] public ImmutableArray GridRows { get; } public BoxStyle(Display display, Direction direction, Wrap wrap, Size2 gap, Edges padding, Edges margin, Size2 size, Size2 minSize, Size2 maxSize, Position position, Edges inset, Overflow overflow, ItemAlign alignItems, ItemAlign alignSelf, ContentAlign alignContent, ContentAlign justifyContent, double grow, double shrink, Dimension basis, IReadOnlyList gridColumns, IReadOnlyList gridRows) { diff --git a/packages/thing-contract/src/codecs.ts b/packages/thing-contract/src/codecs.ts index eb55dfc..c8dfc1c 100644 --- a/packages/thing-contract/src/codecs.ts +++ b/packages/thing-contract/src/codecs.ts @@ -25,13 +25,13 @@ const named = (name: string): string => `GameCult.Thing.Contract.${name}`; const blob = present(bytes); -// The C# member type of a list slot is IReadOnlyList; cultcache-ts names only List (a stopgap, until -// thing2:follow_up:cultcache-ts-readonly-list-name lands). A list slot is required. +// The C# member type of a list slot is ImmutableArray, a whole-value holder; cultcache-ts names only List +// (a stopgap, until thing2:follow_up:cultcache-ts-readonly-list-name lands). A list slot is required. const readOnlyList = (item: Codec): Codec => { const inner = sequence(item); const readOnly: Codec = { get typeName() { - return item.typeName === undefined ? undefined : `System.Collections.Generic.IReadOnlyList<${item.typeName}>`; + return item.typeName === undefined ? undefined : `System.Collections.Immutable.ImmutableArray<${item.typeName}>`; }, encode: (value) => inner.encode(value), decode: (raw) => inner.decode(raw), diff --git a/packages/thing-contract/test/deep.test.ts b/packages/thing-contract/test/deep.test.ts index f6b8d34..d5326fd 100644 --- a/packages/thing-contract/test/deep.test.ts +++ b/packages/thing-contract/test/deep.test.ts @@ -1,6 +1,6 @@ // The deepest tree the payload bound admits decodes and re-encodes on Node's default stack (no --stack-size), and one -// level deeper is refused with CultCachePayloadDepthError, never an abort. The Rust test of the same name needs a 16 MiB -// thread for this; here the stack holds, and the bound refuses first. +// level deeper is refused with CultCachePayloadDepthError, never an abort. The Rust test of the same name holds on its +// default test thread too. import assert from "node:assert/strict"; import test from "node:test"; diff --git a/packages/thing-contract/test/names.test.ts b/packages/thing-contract/test/names.test.ts index 0fa2e55..3af9083 100644 --- a/packages/thing-contract/test/names.test.ts +++ b/packages/thing-contract/test/names.test.ts @@ -1,6 +1,6 @@ // The type names the package gives its codecs are the C# package's (tests/thing-contract-parity), and the member names // follow the owner's: Rust names that C# flattens into arm classes have one codec per arm, a list slot names -// IReadOnlyList, and TextInputNode's slot 2 is inputKind, the camelCase of C# InputKind. +// ImmutableArray, and TextInputNode's slot 2 is inputKind, the camelCase of C# InputKind. import assert from "node:assert/strict"; import { join } from "node:path"; import test from "node:test"; @@ -35,13 +35,13 @@ test("Scalar is a Rust name the C# package does not have; ParamName is its type } }); -test("a list slot is named IReadOnlyList, never List, and the element is a type of the C# package", () => { +test("a list slot is named ImmutableArray, never List, and the element is a type of the C# package", () => { let lists = 0; for (const [key, codec] of entries) { for (const member of codec.members ?? []) { - if (!/List$/u.exec(member.typeName); + const element = /^System\.Collections\.Immutable\.ImmutableArray<(.+)>$/u.exec(member.typeName); assert.ok(element !== null, `${key}: ${member.typeName}`); assert.ok(element[1] === "System.String" || names.has(element[1]), `${key}: ${member.typeName}`); } diff --git a/tests/GameCult.Thing.Contract.Tests/DeepTreeTests.cs b/tests/GameCult.Thing.Contract.Tests/DeepTreeTests.cs index 5914a7d..465173c 100644 --- a/tests/GameCult.Thing.Contract.Tests/DeepTreeTests.cs +++ b/tests/GameCult.Thing.Contract.Tests/DeepTreeTests.cs @@ -55,7 +55,7 @@ public sealed class DeepTreeTests var wide = new SurfaceDocument("provider.a", "wide", 1, "wide", Boxed("root", children.ToArray()), new List()); var bytes = Wire.Write(wide); var decoded = (SurfaceDocument)Wire.Read(typeof(SurfaceDocument), bytes); - Assert.That(((BoxNode)decoded.Root).Children, Has.Count.EqualTo(999)); + Assert.That(((BoxNode)decoded.Root).Children, Has.Length.EqualTo(999)); Assert.That(Convert.ToHexString(Wire.Write(decoded)), Is.EqualTo(Convert.ToHexString(bytes))); } } diff --git a/tests/GameCult.Thing.Contract.Tests/GoldenTests.cs b/tests/GameCult.Thing.Contract.Tests/GoldenTests.cs index 7f56677..40baebe 100644 --- a/tests/GameCult.Thing.Contract.Tests/GoldenTests.cs +++ b/tests/GameCult.Thing.Contract.Tests/GoldenTests.cs @@ -105,8 +105,6 @@ public sealed class GoldenTests // ---- the store ---- - // surface.cc's catalog is written by cultcache-rs with empty members, so this proves bytes and keys only; the type - // names are NameSetTests. [Test] public void StoreRead() { diff --git a/tests/GameCult.Thing.Contract.Tests/NameSetTests.cs b/tests/GameCult.Thing.Contract.Tests/NameSetTests.cs index 30341cb..ffca33f 100644 --- a/tests/GameCult.Thing.Contract.Tests/NameSetTests.cs +++ b/tests/GameCult.Thing.Contract.Tests/NameSetTests.cs @@ -23,6 +23,8 @@ public sealed class NameSetTests var entry = Wire.Registry.GetRequired(t).ToCatalogEntry(); return entry.Members.Select(m => $"{entry.SchemaId}\t{m.Slot}\t{m.MemberName}\t{m.TypeName}"); }).ToArray(); + if (Environment.GetEnvironmentVariable("THING_PARITY_WRITE") == "1") + File.WriteAllText(ParityTests.SourceParityPath("catalog-members.tsv"), string.Join("\n", actual) + "\n"); Assert.That(actual, Is.EqualTo(Lines("catalog-members.tsv"))); Assert.That(actual, Has.Length.GreaterThan(20)); } @@ -71,7 +73,7 @@ public sealed class NameSetTests var error = Assert.Throws(() => Wire.Registry.ResolvePersistedSchema(renamed.SchemaId, new[] { renamed }))!; Assert.That(error.Message, Does.Contain("changed type").And.Contain("System.Int32").And.Contain("System.Int64")); - var listed = Persisted(typeof(AssetCatalog), "System.Collections.Generic.IReadOnlyList", + var listed = Persisted(typeof(AssetCatalog), "System.Collections.Immutable.ImmutableArray", "System.Collections.Generic.List"); Assert.Throws(() => Wire.Registry.ResolvePersistedSchema(listed.SchemaId, new[] { listed }), "a store written when Assets was a List is refused"); diff --git a/tests/GameCult.Thing.Contract.Tests/ParityTests.cs b/tests/GameCult.Thing.Contract.Tests/ParityTests.cs index 5aa8d95..4481e05 100644 --- a/tests/GameCult.Thing.Contract.Tests/ParityTests.cs +++ b/tests/GameCult.Thing.Contract.Tests/ParityTests.cs @@ -15,7 +15,7 @@ public sealed class ParityTests { private static string ParityPath(string file) => Path.Combine(AppContext.BaseDirectory, "parity", file); - private static string SourceParityPath(string file) + internal static string SourceParityPath(string file) { for (var here = new DirectoryInfo(AppContext.BaseDirectory); here != null; here = here.Parent) { diff --git a/tests/GameCult.Thing.Contract.Tests/ReadOnlyListTests.cs b/tests/GameCult.Thing.Contract.Tests/ReadOnlyListTests.cs index 6a59403..cd79648 100644 --- a/tests/GameCult.Thing.Contract.Tests/ReadOnlyListTests.cs +++ b/tests/GameCult.Thing.Contract.Tests/ReadOnlyListTests.cs @@ -12,6 +12,7 @@ namespace GameCult.Thing.Contract.Tests; public sealed class ReadOnlyListTests { private static bool IsMutableCollection(Type type) => + !(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Immutable.ImmutableArray<>)) && (typeof(IList).IsAssignableFrom(type) || type.GetInterfaces().Concat(new[] { type }).Any(i => i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(ICollection<>) || i.GetGenericTypeDefinition() == typeof(IDictionary<,>)))); @@ -37,6 +38,35 @@ public sealed class ReadOnlyListTests Assert.That(checkedProperties, Is.GreaterThan(200)); } + /// + /// CultLib's element-id walk owns the elements of a list held as a class or interface of + /// [MessagePackObject] or [Union] elements, and demands an id on each. A list held as an ImmutableArray is one + /// whole value the walk never enters, so the contract holds every list that way. + /// + [Test] + public void NoKeyMemberIsAnOwnedListOfContractObjects() + { + bool IsContractObject(Type type) => + type.GetCustomAttribute() != null || type.GetCustomAttributes(false).Any(); + var offenders = new List(); + var checkedMembers = 0; + foreach (var type in typeof(CommandResult).Assembly.GetExportedTypes()) + foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (property.GetCustomAttribute() is null) continue; + checkedMembers++; + var t = property.PropertyType; + if (t.IsValueType) continue; + var element = t.GetInterfaces().Concat(new[] { t }) + .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + .Select(i => i.GetGenericArguments()[0]).FirstOrDefault(); + if (element != null && IsContractObject(element)) offenders.Add($"{type.Name}.{property.Name}: {t.Name}"); + } + + Assert.That(offenders, Is.Empty); + Assert.That(checkedMembers, Is.GreaterThan(100)); + } + [Test] public void EveryListParameterIsCopiedAndTheCopyCannotGrow() { @@ -76,6 +106,11 @@ public sealed class ReadOnlyListTests args[index] = null; var list = Assert.Throws(() => door.Call(args), $"{door.Name}: nil list")!; Assert.That(list.Bound, Is.EqualTo("present"), door.Name); + + // What a nil list decodes to: a default (uninitialised) ImmutableArray, which throws on first use. + args[index] = Activator.CreateInstance(typeof(System.Collections.Immutable.ImmutableArray<>).MakeGenericType(element)); + var uninitialised = Assert.Throws(() => door.Call(args), $"{door.Name}: default array")!; + Assert.That(uninitialised.Bound, Is.EqualTo("present"), door.Name); } } @@ -91,7 +126,7 @@ public sealed class ReadOnlyListTests Assert.That(box.Children, Is.Not.SameAs(array)); Assert.That(box.Children is Node[], Is.False, "the held list is the caller's array type"); var boxed = (BoxNode)Builders.Boxed("c", child, other); - Assert.That(boxed.Children, Has.Count.EqualTo(2)); + Assert.That(boxed.Children, Has.Length.EqualTo(2)); foreach (var (door, index, element) in ListParameters()) { diff --git a/tests/GameCult.Thing.Contract.Tests/SlotNodeTests.cs b/tests/GameCult.Thing.Contract.Tests/SlotNodeTests.cs index 2de2537..e6e5381 100644 --- a/tests/GameCult.Thing.Contract.Tests/SlotNodeTests.cs +++ b/tests/GameCult.Thing.Contract.Tests/SlotNodeTests.cs @@ -25,6 +25,6 @@ public sealed class SlotNodeTests var root = (BoxNode)composition.Body; var slot = (SlotNode)root.Children[^1]; Assert.That(slot.Param.Name, Is.EqualTo("body")); - Assert.That(root.Children, Has.Count.EqualTo(3)); + Assert.That(root.Children, Has.Length.EqualTo(3)); } } diff --git a/tests/thing-contract-parity/README.md b/tests/thing-contract-parity/README.md index 4b2c59a..017de16 100644 --- a/tests/thing-contract-parity/README.md +++ b/tests/thing-contract-parity/README.md @@ -4,7 +4,7 @@ The names the C# package `GameCult.Thing.Contract` gives its types. The C# packa | File | Rows | |---|---| -| `catalog-members.tsv` | One row per document slot, `schemaId`, `slot`, `memberName`, `typeName`, as `Wire.Registry`'s catalog entries print them. A list slot reads `System.Collections.Generic.IReadOnlyList`. | +| `catalog-members.tsv` | One row per document slot, `schemaId`, `slot`, `memberName`, `typeName`, as `Wire.Registry`'s catalog entries print them. A list slot reads `System.Collections.Immutable.ImmutableArray`. | | `type-names.txt` | The full name of every public type in `GameCult.Thing.Contract`, sorted ordinally. | | `written-by-cs.cc` | A single-file store the C# package's CultCache wrote from its own builders, one record of each kind. `packages/thing-contract/test/parity.test.ts` reads it. Regenerate: `THING_PARITY_WRITE=1 dotnet test tests/GameCult.Thing.Contract.Tests` (`ParityTests.cs`). | | `written-by-ts.cc` | The same five records, written by `@gamecult/thing-contract`'s CultCache. `ParityTests.cs` reads it. Regenerate: `THING_PARITY_WRITE=1 npm test` in `packages/thing-contract` (`parity.test.ts`). | diff --git a/tests/thing-contract-parity/catalog-members.tsv b/tests/thing-contract-parity/catalog-members.tsv index 2f449fb..aaed98b 100644 --- a/tests/thing-contract-parity/catalog-members.tsv +++ b/tests/thing-contract-parity/catalog-members.tsv @@ -1,27 +1,27 @@ -sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 0 InvocationId System.String -sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 1 SurfaceKey System.String -sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 2 SurfaceVersion System.Int64 -sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 3 Command System.String -sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 4 Payload GameCult.Thing.Contract.RecordPayload -sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 5 Captured System.Collections.Generic.IReadOnlyList -sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 6 Client System.String -sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 7 IssuedAt System.String -sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 8 Delegation System.String -sha256:3d751a6fb07487b0c84cf0ae1c4fe55e5ef0c1656eab41ca3236846a638bdd3f 0 ProviderId System.String -sha256:3d751a6fb07487b0c84cf0ae1c4fe55e5ef0c1656eab41ca3236846a638bdd3f 1 CatalogId System.String -sha256:3d751a6fb07487b0c84cf0ae1c4fe55e5ef0c1656eab41ca3236846a638bdd3f 2 Version System.Int64 -sha256:3d751a6fb07487b0c84cf0ae1c4fe55e5ef0c1656eab41ca3236846a638bdd3f 3 Assets System.Collections.Generic.IReadOnlyList -sha256:531f96346fbff5160daedc82ada2ad5cb3d0477631d2b580ccd1a2834f041b32 0 Publisher System.String -sha256:531f96346fbff5160daedc82ada2ad5cb3d0477631d2b580ccd1a2834f041b32 1 Name System.String -sha256:531f96346fbff5160daedc82ada2ad5cb3d0477631d2b580ccd1a2834f041b32 2 Version System.Int64 -sha256:531f96346fbff5160daedc82ada2ad5cb3d0477631d2b580ccd1a2834f041b32 3 Params System.Collections.Generic.IReadOnlyList -sha256:531f96346fbff5160daedc82ada2ad5cb3d0477631d2b580ccd1a2834f041b32 4 Body GameCult.Thing.Contract.Node -sha256:da2ca90e225d803191fd9a31ad1894e7dfab186f82e892717be8130d2e7ebf33 0 ProviderId System.String -sha256:da2ca90e225d803191fd9a31ad1894e7dfab186f82e892717be8130d2e7ebf33 1 Label System.String -sha256:da2ca90e225d803191fd9a31ad1894e7dfab186f82e892717be8130d2e7ebf33 2 Version System.Int64 -sha256:da2ca90e225d803191fd9a31ad1894e7dfab186f82e892717be8130d2e7ebf33 3 Title System.String -sha256:da2ca90e225d803191fd9a31ad1894e7dfab186f82e892717be8130d2e7ebf33 4 Root GameCult.Thing.Contract.Node -sha256:da2ca90e225d803191fd9a31ad1894e7dfab186f82e892717be8130d2e7ebf33 5 Commands System.Collections.Generic.IReadOnlyList +sha256:054253624267f9b37445b05f7fcf5c4de6f40ad16fa1427eb596c56e5471383e 0 ProviderId System.String +sha256:054253624267f9b37445b05f7fcf5c4de6f40ad16fa1427eb596c56e5471383e 1 CatalogId System.String +sha256:054253624267f9b37445b05f7fcf5c4de6f40ad16fa1427eb596c56e5471383e 2 Version System.Int64 +sha256:054253624267f9b37445b05f7fcf5c4de6f40ad16fa1427eb596c56e5471383e 3 Assets System.Collections.Immutable.ImmutableArray +sha256:9611b1313cb4cd285ba02e4170f5204c1fb009c52a058c864c0382abd26202bc 0 ProviderId System.String +sha256:9611b1313cb4cd285ba02e4170f5204c1fb009c52a058c864c0382abd26202bc 1 Label System.String +sha256:9611b1313cb4cd285ba02e4170f5204c1fb009c52a058c864c0382abd26202bc 2 Version System.Int64 +sha256:9611b1313cb4cd285ba02e4170f5204c1fb009c52a058c864c0382abd26202bc 3 Title System.String +sha256:9611b1313cb4cd285ba02e4170f5204c1fb009c52a058c864c0382abd26202bc 4 Root GameCult.Thing.Contract.Node +sha256:9611b1313cb4cd285ba02e4170f5204c1fb009c52a058c864c0382abd26202bc 5 Commands System.Collections.Immutable.ImmutableArray +sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 0 InvocationId System.String +sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 1 SurfaceKey System.String +sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 2 SurfaceVersion System.Int64 +sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 3 Command System.String +sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 4 Payload GameCult.Thing.Contract.RecordPayload +sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 5 Captured System.Collections.Immutable.ImmutableArray +sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 6 Client System.String +sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 7 IssuedAt System.String +sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 8 Delegation System.String +sha256:bcc1513ee682d1d58746836d4d2e98df086eb62c3fd9a797a2e72e561437393e 0 Publisher System.String +sha256:bcc1513ee682d1d58746836d4d2e98df086eb62c3fd9a797a2e72e561437393e 1 Name System.String +sha256:bcc1513ee682d1d58746836d4d2e98df086eb62c3fd9a797a2e72e561437393e 2 Version System.Int64 +sha256:bcc1513ee682d1d58746836d4d2e98df086eb62c3fd9a797a2e72e561437393e 3 Params System.Collections.Immutable.ImmutableArray +sha256:bcc1513ee682d1d58746836d4d2e98df086eb62c3fd9a797a2e72e561437393e 4 Body GameCult.Thing.Contract.Node sha256:e0273199abadb60da0bd9a7bcb863e131ef08bb2284f7eb729f76159caa369fd 0 InvocationId System.String sha256:e0273199abadb60da0bd9a7bcb863e131ef08bb2284f7eb729f76159caa369fd 1 Seq System.Int32 sha256:e0273199abadb60da0bd9a7bcb863e131ef08bb2284f7eb729f76159caa369fd 2 Outcome GameCult.Thing.Contract.Outcome diff --git a/tests/thing-contract-parity/written-by-cs.cc b/tests/thing-contract-parity/written-by-cs.cc index 7167c76..e8dbd2b 100644 Binary files a/tests/thing-contract-parity/written-by-cs.cc and b/tests/thing-contract-parity/written-by-cs.cc differ diff --git a/tests/thing-contract-parity/written-by-ts.cc b/tests/thing-contract-parity/written-by-ts.cc index 10b3daf..ccfb639 100644 Binary files a/tests/thing-contract-parity/written-by-ts.cc and b/tests/thing-contract-parity/written-by-ts.cc differ