resolve: validate owns the depth rule; expand keeps a named stack bound with its own code; tests

This commit is contained in:
Meta Vens 2026-11-28 00:32:37 +01:00
commit 209be3f37b
4 changed files with 91 additions and 11 deletions

View file

@ -20,14 +20,17 @@ pub enum Code {
DuplicateNodeId,
/// A Param or a Slot outside any composition.
UnboundParam,
/// The expansion outgrew the limits of its tree.
/// The expanded tree has too many nodes or is deeper than the depth rule.
ExpansionLimit,
/// The input nests deeper than the expander can recurse. A stack bound, not the depth rule: the depth
/// rule is judged on the finished tree and reports ExpansionLimit.
TooDeepToResolve,
}
impl Code {
/// Whether the fault leaves no tree (the whole document is refused) or only a placeholder.
pub fn refuses_document(self) -> bool {
matches!(self, Code::UndeclaredCommand | Code::DuplicateNodeId | Code::UnboundParam | Code::ExpansionLimit)
matches!(self, Code::UndeclaredCommand | Code::DuplicateNodeId | Code::UnboundParam | Code::ExpansionLimit | Code::TooDeepToResolve)
}
}

View file

@ -14,11 +14,19 @@ use crate::port::{Address, Lookup, Record, StatePort};
use super::{Limits, std as thing_std, validate};
/// The deepest input the expander recurses into. This is a stack bound and not the depth rule: the
/// rule (`Limits::max_tree_depth`) is judged by validate on the finished tree, where a slot argument
/// the body never places does not count. It exists because an in-memory tree from a Rust caller can
/// be deeper than any decoded document (CultCache bounds decoded nesting at 256), and recursion
/// over it would overflow the stack.
const STACK_BOUND: usize = 1024;
/// A fault the nearest enclosing Use turns into a placeholder (`Invalid`), or one that ends the
/// whole expansion (`Limit`).
/// whole expansion (`Limit`, or `Stack` for input too deep to recurse into).
pub(super) enum Fault {
Invalid(String),
Limit(String),
Stack(String),
}
type Res<T> = Result<T, Fault>;
@ -296,8 +304,8 @@ impl<'a> Expander<'a> {
}
fn node(&mut self, node: &Node, scope: Option<&Scope>, depth: usize, root: bool) -> Res<Node> {
if depth > self.limits.max_tree_depth {
return Err(Fault::Limit(format!("the expansion is deeper than {} levels", self.limits.max_tree_depth)));
if depth > STACK_BOUND {
return Err(Fault::Stack(format!("the input nests deeper than {STACK_BOUND} levels")));
}
self.count(1)?;
// Each arm settles its own positions first and its child lists last: a diagnostic names the

View file

@ -63,6 +63,10 @@ pub fn resolve(document: &SurfaceDocument, port: &dyn StatePort, limits: &Limits
expander.diag(Code::ExpansionLimit, None, detail);
None
}
Err(expand::Fault::Stack(detail)) => {
expander.diag(Code::TooDeepToResolve, None, detail);
None
}
Err(expand::Fault::Invalid(detail)) => {
expander.diag(Code::CompositionInvalid, None, detail);
None

View file

@ -877,14 +877,79 @@ fn a_std_reference_is_pinned_to_its_version() {
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 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();
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")]);
let mut expected: Vec<_> = names.iter().map(|_| Code::UnresolvedUse).collect();
expected.push(Code::DuplicateNodeId);
assert_eq!(seen.iter().map(|(code, _)| *code).collect::<Vec<_>>(), expected);
assert_eq!(seen[0].1, Some("g-n3"));
assert_eq!(seen.last().unwrap().1, Some("d"));
let mut sorted: Vec<_> = (0..10).map(|n| comp_address(&format!("n{n}"))).collect();
sorted.sort_by_key(|address| address.key.as_str().to_string());
assert_eq!(resolution.reads, sorted);
});
}
/// A chain of `levels` nodes, the first the root: Boxes, or Repeats whose template is the next.
fn chain(levels: usize, repeats: bool) -> Node {
let mut node = text("bottom", "x");
for level in 1..levels {
let id = format!("level-{level}");
node = if repeats { repeat(&id, node) } else { boxed(&id, vec![node]) };
}
node
}
#[test]
fn the_depth_rule_is_judged_on_the_finished_tree_through_box_and_repeat() {
big(|| {
for repeats in [false, true] {
let at_limit = run(&surface(chain(256, repeats), &[]), &MemState::new());
assert_eq!(at_limit.diagnostics, vec![], "repeats={repeats}");
assert!(at_limit.tree.is_some());
let over = run(&surface(chain(257, repeats), &[]), &MemState::new());
refused_for_limit(&over);
assert!(over.diagnostics.iter().any(|found| found.detail.contains("deeper")), "repeats={repeats}");
}
});
}
#[test]
fn an_unplaced_slot_argument_does_not_count_toward_the_depth_rule() {
big(|| {
let ignoring = composition("c", &[("body", ParamKind::Slot)], boxed("b", vec![]));
let mut deep = text("leaf", "x");
for level in 0..300 {
deep = boxed(&format!("a-{level}"), vec![deep]);
}
let document = surface(boxed("root", vec![use_of("u", "c", vec![slot_arg("body", vec![deep])])]), &[]);
let resolution = run(&document, &state_with(&[ignoring]));
assert_eq!(resolution.diagnostics, vec![]);
assert_eq!(all_ids(&resolution), ["root", "u"]);
});
}
#[test]
fn input_too_deep_to_recurse_into_is_refused_with_its_own_code() {
big(|| {
let resolution = run(&surface(chain(1100, false), &[]), &MemState::new());
assert!(resolution.tree.is_none());
assert_eq!(resolution.diagnostics.len(), 1, "{:?}", resolution.diagnostics);
assert_eq!(resolution.diagnostics[0].code, Code::TooDeepToResolve);
});
}
#[test]
fn a_slot_naming_a_param_of_another_kind_is_invalid() {
big(|| {
let body = composition("c", &[("x", ParamKind::Text)], boxed("b", vec![slot("x")]));
let document = surface(boxed("root", vec![use_of("u", "c", vec![text_arg("x", "t")])]), &[]);
let resolution = run(&document, &state_with(&[body]));
only(&resolution, Code::CompositionInvalid, Some("u"), "used as a slot");
});
}