resolve: one owner of the node count, reads sorted, tests for the limits, root common, unbound and provider arms, container walks
This commit is contained in:
parent
c9c46a9a8b
commit
bd4c876dce
3 changed files with 288 additions and 23 deletions
|
|
@ -7,8 +7,6 @@ mod expand;
|
|||
pub mod std;
|
||||
mod validate;
|
||||
|
||||
use ::std::collections::HashSet;
|
||||
|
||||
use thing_contract::SurfaceDocument;
|
||||
|
||||
use crate::diagnostic::{Code, Diagnostic};
|
||||
|
|
@ -49,10 +47,12 @@ impl ResolvedTree {
|
|||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Resolution {
|
||||
pub tree: Option<ResolvedTree>,
|
||||
/// In document pre-order.
|
||||
/// Expansion faults in expansion pre-order, then the finished tree's faults (duplicate ids, depth)
|
||||
/// in tree pre-order.
|
||||
pub diagnostics: Vec<Diagnostic>,
|
||||
/// Every non-std composition address consulted, whether present, absent or refused.
|
||||
pub reads: HashSet<Address>,
|
||||
/// Every non-std composition address consulted, whether present, absent or refused, once each, ordered
|
||||
/// by provider, schema and key.
|
||||
pub reads: Vec<Address>,
|
||||
}
|
||||
|
||||
pub fn resolve(document: &SurfaceDocument, port: &dyn StatePort, limits: &Limits) -> Resolution {
|
||||
|
|
@ -69,7 +69,11 @@ pub fn resolve(document: &SurfaceDocument, port: &dyn StatePort, limits: &Limits
|
|||
}
|
||||
};
|
||||
let mut diagnostics = ::std::mem::take(&mut expander.diagnostics);
|
||||
let reads = ::std::mem::take(&mut expander.reads);
|
||||
let mut reads: Vec<Address> = ::std::mem::take(&mut expander.reads).into_iter().collect();
|
||||
reads.sort_by(|a, b| {
|
||||
let key = |address: &Address| (address.provider.as_str().to_string(), address.schema.as_str().to_string(), address.key.as_str().to_string());
|
||||
key(a).cmp(&key(b))
|
||||
});
|
||||
let tree = root.and_then(|root| {
|
||||
diagnostics.extend(validate::check(&root, limits, &document.record_key()));
|
||||
let refused = diagnostics.iter().any(|diagnostic| diagnostic.code.refuses_document());
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
//! The one pass over the finished tree: ids unique, and the tree within its limits. Commands,
|
||||
//! Params and Slots are judged where they land (expand.rs), so no other pass reads them.
|
||||
//! The one pass over the finished tree: ids unique, and the tree within its depth limit (a slot's
|
||||
//! nodes are placed deeper than expand saw them). Commands, Params and Slots are judged where they
|
||||
//! land and the node count is expand's alone (it must stop before it builds a tree it would refuse).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
|
|
@ -43,7 +44,7 @@ pub(super) fn size(node: &Node) -> usize {
|
|||
1 + children(node).iter().map(size).sum::<usize>()
|
||||
}
|
||||
|
||||
/// Faults of the finished tree, in pre-order. A tree deeper than the limit is not walked further.
|
||||
/// Faults of the finished tree, in pre-order: duplicate ids, then depth. A tree deeper than the limit is not walked further.
|
||||
pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec<Diagnostic> {
|
||||
let mut found = Vec::new();
|
||||
let fault = |code, node: Option<&NodeId>, detail: String| Diagnostic {
|
||||
|
|
@ -53,11 +54,9 @@ pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec<Diagnost
|
|||
detail,
|
||||
};
|
||||
let mut seen: HashSet<&NodeId> = HashSet::new();
|
||||
let mut count = 0usize;
|
||||
let mut too_deep = false;
|
||||
let mut stack = vec![(root, 1usize)];
|
||||
while let Some((node, depth)) = stack.pop() {
|
||||
count += 1;
|
||||
if depth > limits.max_tree_depth {
|
||||
too_deep = true;
|
||||
continue;
|
||||
|
|
@ -72,8 +71,5 @@ pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec<Diagnost
|
|||
if too_deep {
|
||||
found.push(fault(Code::ExpansionLimit, None, format!("the tree is deeper than {} levels", limits.max_tree_depth)));
|
||||
}
|
||||
if count > limits.max_nodes {
|
||||
found.push(fault(Code::ExpansionLimit, None, format!("the tree has more than {} nodes", limits.max_nodes)));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
|
|
|||
|
|
@ -323,28 +323,82 @@ fn cycles_and_depth_end_in_a_placeholder() {
|
|||
});
|
||||
}
|
||||
|
||||
fn limited(max_nodes: usize) -> Limits {
|
||||
Limits { max_nodes, ..Limits::default() }
|
||||
}
|
||||
|
||||
fn refused_for_limit(resolution: &Resolution) {
|
||||
assert!(resolution.tree.is_none());
|
||||
assert!(resolution.diagnostics.iter().any(|found| found.code == Code::ExpansionLimit), "{:?}", resolution.diagnostics);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expansion_is_bounded() {
|
||||
fn the_node_limit_is_exact_and_stops_a_doubling_expansion() {
|
||||
big(|| {
|
||||
// A composition using the previous one twice, 30 levels: 2^30 nodes, so only an early stop terminates.
|
||||
// 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 resolution = run(&surface(boxed("root", vec![use_of("u", "c30", vec![])]), &[]), &state_with(&chain));
|
||||
assert!(resolution.tree.is_none());
|
||||
assert!(resolution.diagnostics.iter().any(|found| found.code == Code::ExpansionLimit));
|
||||
let document = surface(boxed("root", vec![use_of("u", "c30", vec![])]), &[]);
|
||||
refused_for_limit(&resolve(&document, &state_with(&chain), &limited(100)));
|
||||
|
||||
// A tree deeper than the limit.
|
||||
// Seven levels are 255 nodes: over 100, under the default.
|
||||
let seven = surface(boxed("root", vec![use_of("u", "c7", vec![])]), &[]);
|
||||
refused_for_limit(&resolve(&seven, &state_with(&chain), &limited(100)));
|
||||
assert!(resolve(&seven, &state_with(&chain), &Limits::default()).tree.is_some());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slot_placed_twice_per_level_is_counted_when_it_is_spliced() {
|
||||
big(|| {
|
||||
// Each level places its slot twice around the level below: every level's expansion is counted
|
||||
// once, so only the splice count sees the doubling.
|
||||
let doubling = composition("c", &[("body", ParamKind::Slot)], boxed("b", vec![slot("body"), slot("body")]));
|
||||
let mut nested = text("leaf", "x");
|
||||
for level in 0..12 {
|
||||
nested = use_of(&format!("u{level}"), "c", vec![slot_arg("body", vec![nested])]);
|
||||
}
|
||||
let document = surface(boxed("root", vec![nested]), &[]);
|
||||
refused_for_limit(&resolve(&document, &state_with(&[doubling]), &limited(1000)));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tree_deeper_than_the_limit_is_refused() {
|
||||
big(|| {
|
||||
let mut deep = boxed("leaf", vec![]);
|
||||
for level in 0..257 {
|
||||
deep = boxed(&format!("level-{level}"), vec![deep]);
|
||||
}
|
||||
let resolution = run(&surface(deep, &[]), &MemState::new());
|
||||
assert!(resolution.tree.is_none());
|
||||
assert!(resolution.diagnostics.iter().any(|found| found.code == Code::ExpansionLimit));
|
||||
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 200 and 100
|
||||
// levels, the finished tree is 300.
|
||||
let chain = |levels: usize, inner: Vec<Node>, 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(200, vec![slot("body")], "b"));
|
||||
let argument = slot_arg("body", vec![chain(100, 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")));
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -623,3 +677,214 @@ fn an_anchor_in_a_body_follows_the_expanded_ids() {
|
|||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn root_common_of(resolution: &Resolution, id: &str) -> NodeCommon {
|
||||
let Node::Box(found) = node_of(resolution, id) else { panic!("not a Box") };
|
||||
found.common.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_expanded_root_takes_the_uses_visibility_and_label() {
|
||||
big(|| {
|
||||
let flag = |provider: Option<&str>| Bind {
|
||||
source: StateSource::Record(StateRef {
|
||||
provider: provider.map(ProviderId::new),
|
||||
schema: SchemaId::new("gamecult.thing.test.flag.v1"),
|
||||
key: RecordKey::new("shown"),
|
||||
}),
|
||||
member: path(&["on"]),
|
||||
format: None,
|
||||
};
|
||||
let labelled = |label: Option<TextSource>| {
|
||||
let Node::Box(mut root) = boxed("b", vec![]) else { unreachable!() };
|
||||
root.common.a11y_label = label;
|
||||
Node::Box(root)
|
||||
};
|
||||
let used = |visible: BoolSource, label: Option<TextSource>, args: Vec<Arg>| {
|
||||
Node::Use(UseNode {
|
||||
common: NodeCommon { id: nid("u"), visible, a11y_label: label },
|
||||
composition: reference("c"),
|
||||
args,
|
||||
})
|
||||
};
|
||||
let run_one = |body: Node, params: &[(&str, ParamKind)], used: Node| {
|
||||
run(&surface(boxed("root", vec![used]), &[]), &state_with(&[composition("c", params, body)]))
|
||||
};
|
||||
|
||||
// The Use's bound visibility and its label win over the body root's label.
|
||||
let resolution = run_one(
|
||||
labelled(Some(lit_text("body label"))),
|
||||
&[],
|
||||
used(BoolSource::Bound(flag(None)), Some(lit_text("use label")), vec![]),
|
||||
);
|
||||
assert_eq!(resolution.diagnostics, vec![]);
|
||||
let common = root_common_of(&resolution, "u");
|
||||
assert_eq!(common.visible, BoolSource::Bound(flag(Some("provider.t"))));
|
||||
assert_eq!(common.a11y_label, Some(lit_text("use label")));
|
||||
|
||||
// Without a Use label the body root's own label stands, a Param of it substituted.
|
||||
let resolution = run_one(
|
||||
labelled(Some(TextSource::Param(param("lbl")))),
|
||||
&[("lbl", ParamKind::Text)],
|
||||
used(lit_bool(true), None, vec![text_arg("lbl", "from arg")]),
|
||||
);
|
||||
assert_eq!(root_common_of(&resolution, "u").a11y_label, Some(lit_text("from arg")));
|
||||
let resolution = run_one(labelled(None), &[], used(lit_bool(true), None, vec![]));
|
||||
assert_eq!(root_common_of(&resolution, "u").a11y_label, None);
|
||||
|
||||
// A literal false on the Use hides the expansion.
|
||||
let resolution = run_one(labelled(None), &[], used(lit_bool(false), None, vec![]));
|
||||
assert_eq!(root_common_of(&resolution, "u").visible, lit_bool(false));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_param_left_in_any_position_outside_a_composition_refuses() {
|
||||
big(|| {
|
||||
let slider = Node::Slider(SliderNode {
|
||||
common: common("s"),
|
||||
min: 0.0,
|
||||
max: 1.0,
|
||||
step: 0.1,
|
||||
value: NumberSource::Param(param("n")),
|
||||
commit: command("real"),
|
||||
});
|
||||
let enabled = Node::Button(ButtonNode {
|
||||
common: common("b"),
|
||||
content: vec![],
|
||||
on_activate: command("real"),
|
||||
enabled: BoolSource::Param(param("on")),
|
||||
});
|
||||
let Node::Repeat(mut rows) = repeat("r", text("row", "x")) else { unreachable!() };
|
||||
rows.collection = CollectionSource::Param(param("rows"));
|
||||
let Node::Text(mut shown) = text("t", "x") else { unreachable!() };
|
||||
shown.common.visible = BoolSource::Param(param("v"));
|
||||
let cases = [("number", slider), ("bool", enabled), ("collection", Node::Repeat(rows)), ("visible", Node::Text(shown))];
|
||||
for (name, node) in cases {
|
||||
let resolution = run(&surface(boxed("root", vec![node]), &["real"]), &MemState::new());
|
||||
assert!(resolution.tree.is_none(), "{name}");
|
||||
assert_eq!(resolution.diagnostics.len(), 1, "{name}");
|
||||
assert_eq!(resolution.diagnostics[0].code, Code::UnboundParam, "{name}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absent_provider_is_the_surfaces_in_select_and_plot_too() {
|
||||
big(|| {
|
||||
let bind = |key: &str| Bind {
|
||||
source: StateSource::Record(StateRef {
|
||||
provider: None,
|
||||
schema: SchemaId::new("gamecult.thing.test.row.v1"),
|
||||
key: RecordKey::new(key),
|
||||
}),
|
||||
member: path(&["v"]),
|
||||
format: None,
|
||||
};
|
||||
let select = Node::Select(SelectNode {
|
||||
common: common("sel"),
|
||||
options: OptionList::Bound(BoundOptions {
|
||||
collection: CollectionSource::Records(RecordsSource {
|
||||
provider: None,
|
||||
schema: SchemaId::new("gamecult.thing.test.row.v1"),
|
||||
key_prefix: "row-".into(),
|
||||
}),
|
||||
value_member: path(&["id"]),
|
||||
label_member: path(&["name"]),
|
||||
}),
|
||||
value: bind("a"),
|
||||
on_change: command("real"),
|
||||
});
|
||||
let plot = Node::Plot(PlotNode {
|
||||
common: common("plot"),
|
||||
series: bind("b"),
|
||||
mark: PlotMark::Line,
|
||||
x_min: None,
|
||||
x_max: None,
|
||||
y_min: None,
|
||||
y_max: None,
|
||||
});
|
||||
let resolution = run(&surface(boxed("root", vec![select, plot]), &["real"]), &MemState::new());
|
||||
assert_eq!(resolution.diagnostics, vec![]);
|
||||
let debug = format!("{:?}", resolution.tree.unwrap().document());
|
||||
assert!(!debug.contains("provider: None"));
|
||||
// The surface's own provider id, then the options collection, the select value and the series.
|
||||
assert_eq!(debug.matches("provider.t").count(), 4);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_ids_are_found_under_every_container_and_on_a_placeholder() {
|
||||
big(|| {
|
||||
let overlay = |child: Node| {
|
||||
Node::Overlay(OverlayNode {
|
||||
common: common("pop"),
|
||||
anchor: Anchor::Viewport,
|
||||
modal: false,
|
||||
dismiss: command("real"),
|
||||
children: vec![child],
|
||||
})
|
||||
};
|
||||
let button = Node::Button(ButtonNode {
|
||||
common: common("btn"),
|
||||
content: vec![text("d", "x")],
|
||||
on_activate: command("real"),
|
||||
enabled: lit_bool(true),
|
||||
});
|
||||
let cases = [
|
||||
("repeat template", repeat("rows", text("d", "x"))),
|
||||
("overlay children", overlay(text("d", "x"))),
|
||||
("button content", button),
|
||||
("a placeholder's id", use_of("d", "ghost", vec![])),
|
||||
];
|
||||
for (name, other) in cases {
|
||||
let document = surface(boxed("root", vec![text("d", "first"), other]), &["real"]);
|
||||
let resolution = run(&document, &MemState::new());
|
||||
assert!(resolution.tree.is_none(), "{name}");
|
||||
let duplicates: Vec<_> =
|
||||
resolution.diagnostics.iter().filter(|found| found.code == Code::DuplicateNodeId).collect();
|
||||
assert_eq!(duplicates.len(), 1, "{name}: {:?}", resolution.diagnostics);
|
||||
assert_eq!(duplicates[0].node.as_ref().map(NodeId::as_str), Some("d"), "{name}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_body_leaves_only_its_own_diagnostic() {
|
||||
big(|| {
|
||||
// The ghost Use in the body is reported by the expansion, then the body fails on its Param:
|
||||
// the whole body is replaced, so its partial diagnostics go with it.
|
||||
let body = composition("c", &[], boxed("b", vec![use_of("ghost-use", "ghost", vec![]), param_text("t", "zz")]));
|
||||
let resolution = run(&surface(boxed("root", vec![use_of("u", "c", vec![])]), &[]), &state_with(&[body]));
|
||||
only(&resolution, Code::CompositionInvalid, Some("u"), "does not declare");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_std_reference_is_pinned_to_its_version() {
|
||||
big(|| {
|
||||
let v2 = Node::Use(UseNode {
|
||||
common: common("s"),
|
||||
composition: CompositionRef { publisher: thing_std::PUBLISHER.into(), name: seg("stat"), version: ver(2) },
|
||||
args: vec![],
|
||||
});
|
||||
let resolution = run(&surface(boxed("root", vec![v2]), &[]), &MemState::new());
|
||||
only(&resolution, Code::UnresolvedUse, Some("s"), "stat");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostics_and_reads_come_out_in_a_defined_order() {
|
||||
big(|| {
|
||||
// Expansion faults first, in expansion order, then the finished tree's; reads sorted by key.
|
||||
let children = vec![text("d", "x"), use_of("g2", "zeta", vec![]), use_of("g1", "alpha", vec![]), 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();
|
||||
assert_eq!(
|
||||
seen,
|
||||
[(Code::UnresolvedUse, Some("g2")), (Code::UnresolvedUse, Some("g1")), (Code::DuplicateNodeId, Some("d"))]
|
||||
);
|
||||
assert_eq!(resolution.reads, vec![comp_address("alpha"), comp_address("zeta")]);
|
||||
});
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue