feat: interpret the remaining retained H3 contracts (WEB-01)

Add the input/event/scenario/interaction/dependency/acceptance model and
validation on top of the core loader:
- 输入/事件 plain-text tables with non-empty unique names; links rejected;
- 场景 only on leaf components, ASCII slug states unique, exactly one initial,
  content cell is exactly one link to a Knowledge unit (Exec and design
  component declarations rejected), scene limit 32;
- 交互 state references, non-empty unique event labels per state, reachability
  from the initial state, multi-state requires transitions, 128 limit;
- 依赖 must target loaded design components with non-empty reasons and an
  acyclic design dependency graph;
- 验收 keeps the direct section text, rejects empty content, never interprets
  it as a test;
- contract-aligned limits (100 docs/200 defs/1000 instances/12 depth/12 slots
  per row/1 MiB file/16 MiB total) and a richer deterministic handoff.

14 real-CLI contract tests now cover the positives and main negatives. Docs and
the WEB-01 evidence record which security/concurrency cases and WEB-03 handoff
remain open; WEB-01 stays open.

Refs cflmy/marqdo-web-design#1, cflmy/marqdo#6
This commit was merged in pull request #4.
This commit is contained in:
cflmy committed 2026-11-27 02:37:22 +08:00
1 parent 75cd26ef89
commit 9684e388ce
6 files changed
+948 -14

No files matched your search

+86 -8
View File
@@ -84,6 +84,37 @@ fn text_at(module: &Module, span: (usize, usize)) -> String {
.to_string()
}
/// Resolve one exact anchor to its unit without imposing the design-component kind.
pub fn any_unit_by_anchor(module: &Module, anchor: &str) -> Result<Unit, Diagnostic> {
let mut matches = Vec::new();
for entry in &module.anchors {
if entry["anchor"].as_str() != Some(anchor) {
continue;
}
if let Some(unit) = entry["unit_id"]
.as_str()
.and_then(|unit_id| units(module).into_iter().find(|unit| unit.id == unit_id))
{
matches.push(unit);
}
}
match matches.len() {
0 => Err(Diagnostic::error(
"web.unit.anchor_missing",
format!("no unit has the exact anchor {anchor:?}"),
)
.with_anchor(anchor)
.at(module.relative.clone(), None)),
1 => Ok(matches.remove(0)),
_ => Err(Diagnostic::error(
"web.unit.anchor_ambiguous",
format!("anchor {anchor:?} resolves to more than one unit"),
)
.with_anchor(anchor)
.at(module.relative.clone(), None)),
}
}
/// Select the Knowledge H2 by its exact anchor, never by label/path guessing.
pub fn knowledge_h2(module: &Module, anchor: &str) -> Result<Unit, Diagnostic> {
let mut matches = Vec::new();
@@ -163,6 +194,48 @@ fn walk_links<'a>(node: &'a Value, out: &mut Vec<&'a Value>) {
}
}
/// Select the single table with one exact header inside a direct retained H3.
/// `Ok(None)` means the section is absent.
pub fn section_table(
module: &Module,
h2: &Unit,
name: &str,
header: &[&str],
) -> Result<Option<(Unit, Table)>, Diagnostic> {
let Some(section) = direct_sections(module, h2)
.into_iter()
.find(|section| section.name == name)
else {
return Ok(None);
};
let mut tables = Vec::new();
walk_tables(&module.document, &mut tables);
let mut inside: Vec<&Value> = tables
.into_iter()
.filter(|table| {
span_from(&table["span"])
.map(|(start, end)| start >= section.span.0 && end <= section.span.1)
.unwrap_or(false)
})
.collect();
match inside.len() {
0 => Err(Diagnostic::error(
"web.table.missing",
format!("`{name}` section has no GFM table"),
)
.at(module.relative.clone(), Some(section.span))),
1 => {
let table = parse_table_with_header(module, inside.remove(0), header, name)?;
Ok(Some((section, table)))
}
_ => Err(Diagnostic::error(
"web.table.multiple",
format!("`{name}` section must contain exactly one GFM table"),
)
.at(module.relative.clone(), Some(section.span))),
}
}
/// Select the single retained `组件` table inside its direct H3 section.
/// Returns `Ok(None)` when the component declares no component table.
pub fn components_table(module: &Module, h2: &Unit) -> Result<Option<(Unit, Table)>, Diagnostic> {
@@ -190,7 +263,7 @@ pub fn components_table(module: &Module, h2: &Unit) -> Result<Option<(Unit, Tabl
),
1 => Ok(Some((
section.clone(),
parse_table(module, inside.remove(0))?,
parse_table_with_header(module, inside.remove(0), &COMPONENTS_HEADER, COMPONENTS)?,
))),
_ => Err(Diagnostic::error(
"web.table.multiple",
@@ -200,7 +273,12 @@ pub fn components_table(module: &Module, h2: &Unit) -> Result<Option<(Unit, Tabl
}
}
fn parse_table(module: &Module, table: &Value) -> Result<Table, Diagnostic> {
fn parse_table_with_header(
module: &Module,
table: &Value,
expected_header: &[&str],
name: &str,
) -> Result<Table, Diagnostic> {
let span = span_from(&table["span"]).ok_or_else(|| {
Diagnostic::error("web.table.span", "table has no source span")
.at(module.relative.clone(), None)
@@ -233,12 +311,12 @@ fn parse_table(module: &Module, table: &Value) -> Result<Table, Diagnostic> {
.collect()
})
.unwrap_or_default();
if headers != COMPONENTS_HEADER {
if headers != expected_header {
return Err(Diagnostic::error(
"web.table.header",
format!(
"`组件` header must be exactly {:?}, found {:?}",
COMPONENTS_HEADER, headers
"`{name}` header must be exactly {:?}, found {:?}",
expected_header, headers
),
)
.at(module.relative.clone(), Some(span)));
@@ -246,12 +324,12 @@ fn parse_table(module: &Module, table: &Value) -> Result<Table, Diagnostic> {
let mut rows = Vec::new();
for row in ast_rows.iter().skip(1) {
let raw_cells = row["children"].as_array().cloned().unwrap_or_default();
if raw_cells.len() != COMPONENTS_HEADER.len() {
if raw_cells.len() != expected_header.len() {
return Err(Diagnostic::error(
"web.table.columns",
format!(
"component row must have {} cells, found {}",
COMPONENTS_HEADER.len(),
"`{name}` row must have {} cells, found {}",
expected_header.len(),
raw_cells.len()
),
)
+646 -3
View File
@@ -35,6 +35,11 @@ pub struct LoadConfig {
pub root: PathBuf,
pub max_depth: usize,
pub max_modules: usize,
pub max_definitions: usize,
pub max_instances: usize,
pub max_scenes: usize,
pub max_transitions: usize,
pub max_file_bytes: usize,
pub max_source_bytes: usize,
}
@@ -51,8 +56,13 @@ impl LoadConfig {
unit: unit.into(),
root: root.into(),
max_depth: 12,
max_modules: 64,
max_source_bytes: 8 * 1024 * 1024,
max_modules: 100,
max_definitions: 200,
max_instances: 1000,
max_scenes: 32,
max_transitions: 128,
max_file_bytes: 1024 * 1024,
max_source_bytes: 16 * 1024 * 1024,
}
}
}
@@ -95,11 +105,63 @@ pub struct ChildSlot {
pub span: Span,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InputDecl {
pub name: String,
pub entry_type: String,
pub description: String,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventDecl {
pub name: String,
pub data: String,
pub description: String,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Scenario {
pub state: String,
/// Content unit (Knowledge H2/H3), never a design-component declaration.
pub content: SourceRef,
pub initial: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Interaction {
pub current: String,
pub event: String,
pub next: String,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dependency {
/// Component definition key (`root-relative path#anchor`).
pub target: String,
pub reason: String,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Acceptance {
pub text: String,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComponentDef {
pub key: String,
pub source: SourceRef,
pub slots: Vec<ChildSlot>,
pub inputs: Vec<InputDecl>,
pub events: Vec<EventDecl>,
pub scenarios: Vec<Scenario>,
pub interactions: Vec<Interaction>,
pub dependencies: Vec<Dependency>,
pub acceptance: Option<Acceptance>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -237,6 +299,44 @@ fn find_reference<'a>(module: &'a Module, link: &Link) -> Result<&'a Value, Load
})
}
fn plain_text(
cells: &[Cell],
module: &Module,
code: &'static str,
) -> Result<Vec<String>, LoadError> {
let mut values = Vec::new();
for cell in cells {
if !cell.links.is_empty() {
return Err(LoadError::Design(vec![Diagnostic::error(
code,
"this contract table accepts plain text only, not links",
)
.at(module.relative.clone(), Some(cell.span))]));
}
values.push(cell.text.trim().to_string());
}
Ok(values)
}
fn normalized_key(module: &Module, anchor: &str) -> String {
format!("{}#{}", module.relative, anchor)
}
fn parse_initial(value: &str) -> Result<bool, &'static str> {
match value.trim() {
"true" => Ok(true),
"false" => Ok(false),
_ => Err("初始 must be exactly `true` or `false`"),
}
}
fn json_span(span: (usize, usize)) -> Span {
Span {
start: span.0,
end: span.1,
}
}
struct Loader {
config: LoadConfig,
root: PathBuf,
@@ -264,6 +364,15 @@ impl Loader {
));
}
let module = analysis::analyze(&self.config.cli, &canonical, &self.root)?;
if module.source.len() > self.config.max_file_bytes {
return Err(design_error(
"web.limit.source",
format!(
"source file {} exceeds the {} byte limit",
module.relative, self.config.max_file_bytes
),
));
}
self.source_bytes += module.source.len();
if self.source_bytes > self.config.max_source_bytes {
return Err(design_error(
@@ -331,6 +440,120 @@ impl Loader {
Ok((target_module, unit, fragment))
}
fn resolve_content_unit(
&mut self,
module: &Module,
link: &Link,
) -> Result<(Module, Unit), LoadError> {
let reference = find_reference(module, link)?;
let candidate = reference["candidate_path"]
.as_str()
.unwrap_or("")
.to_string();
let fragment = reference["fragment"].as_str().unwrap_or("").to_string();
if fragment.is_empty() {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.scene.content",
"场景 content link must name an exact anchor",
)
.at(module.relative.clone(), Some(link.span))]));
}
let target_module = if candidate.is_empty() {
module.clone()
} else {
if Path::new(&candidate).is_absolute() || link.url.contains("://") {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.scene.content",
"场景 content target must be project-relative",
)
.at(module.relative.clone(), Some(link.span))]));
}
let target = module.path.parent().unwrap_or(&self.root).join(&candidate);
let canonical = target.canonicalize().map_err(|error| {
LoadError::Design(vec![Diagnostic::error(
"web.scene.content",
format!("cannot resolve 场景 content target {candidate:?}: {error}"),
)
.at(module.relative.clone(), Some(link.span))])
})?;
if !canonical.starts_with(&self.root) {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.scene.content",
"场景 content target escapes the explicit root",
)
.at(module.relative.clone(), Some(link.span))]));
}
self.analyze(&canonical)?
};
let scene_unit =
document::any_unit_by_anchor(&target_module, &fragment).map_err(|diagnostic| {
let span = diagnostic.span.clone().map(|span| (span.start, span.end));
LoadError::Design(vec![diagnostic.at(target_module.relative.clone(), span)])
})?;
if scene_unit.mode != "knowledge" || matches!(scene_unit.kind.as_str(), "exec" | "function")
{
return Err(LoadError::Design(vec![Diagnostic::error(
"web.scene.content",
format!(
"场景 content must be a Knowledge unit (kind={} mode={})",
scene_unit.kind, scene_unit.mode
),
)
.with_anchor(fragment)
.at(module.relative.clone(), Some(link.span))]));
}
Ok((target_module, scene_unit))
}
fn resolve_dependency_component(
&mut self,
module: &Module,
link: &Link,
) -> Result<(Module, Unit), LoadError> {
let reference = find_reference(module, link)?;
let candidate = reference["candidate_path"]
.as_str()
.unwrap_or("")
.to_string();
let fragment = reference["fragment"].as_str().unwrap_or("").to_string();
if candidate.is_empty() || fragment.is_empty() {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.dependency.target",
"依赖 component cell must link to a design component anchor",
)
.at(module.relative.clone(), Some(link.span))]));
}
if Path::new(&candidate).is_absolute() || link.url.contains("://") {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.dependency.target",
"依赖 target must be project-relative",
)
.at(module.relative.clone(), Some(link.span))]));
}
let target = module.path.parent().unwrap_or(&self.root).join(&candidate);
let canonical = target.canonicalize().map_err(|error| {
LoadError::Design(vec![Diagnostic::error(
"web.dependency.target",
format!("cannot resolve 依赖 target {candidate:?}: {error}"),
)
.at(module.relative.clone(), Some(link.span))])
})?;
if !canonical.starts_with(&self.root) {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.dependency.target",
"依赖 target escapes the explicit root",
)
.at(module.relative.clone(), Some(link.span))]));
}
let target_module = self.analyze(&canonical)?;
let target_unit =
document::knowledge_h2(&target_module, &fragment).map_err(|diagnostic| {
let span = diagnostic.span.clone().map(|span| (span.start, span.end));
LoadError::Design(vec![diagnostic.at(target_module.relative.clone(), span)])
})?;
Ok((target_module, target_unit))
}
fn load_definition(
&mut self,
module: &Module,
@@ -356,7 +579,7 @@ impl Loader {
}
self.stack.push(key.clone());
let table = document::components_table(module, unit)?;
let mut slots = Vec::new();
let mut slots: Vec<ChildSlot> = Vec::new();
if let Some((section, table)) = table {
let mut previous_row = 0u32;
let mut seen_slots = BTreeSet::new();
@@ -411,6 +634,13 @@ impl Loader {
self.resolve_target(module, link)?;
let target_key =
self.load_definition(&target_module, &target_unit, &target_anchor, depth + 1)?;
let row_slots = slots.iter().filter(|existing| existing.row == row).count() + 1;
if row_slots > 12 {
return Err(design_error(
"web.layout.slots_per_row",
format!("row {row} exceeds the 12 slots per row limit"),
));
}
slots.push(ChildSlot {
slot,
row,
@@ -424,17 +654,384 @@ impl Loader {
}
let _ = section;
}
let mut inputs = Vec::new();
if let Some((_, table)) =
document::section_table(module, unit, "输入", &["名称", "类型", "说明"])?
{
let mut seen = BTreeSet::new();
for cells in &table.rows {
let values = plain_text(cells, module, "web.input.text")?;
if values[0].is_empty() {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.input.name",
"输入 name must not be empty",
)
.at(module.relative.clone(), Some(cells[0].span))]));
}
if !seen.insert(values[0].clone()) {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.input.name",
format!("输入 name {:?} is declared twice", values[0]),
)
.at(module.relative.clone(), Some(cells[0].span))]));
}
inputs.push(InputDecl {
name: values[0].clone(),
entry_type: values[1].clone(),
description: values[2].clone(),
span: json_span(cells[0].span),
});
}
}
let mut events = Vec::new();
if let Some((_, table)) =
document::section_table(module, unit, "事件", &["名称", "数据", "说明"])?
{
let mut seen = BTreeSet::new();
for cells in &table.rows {
let values = plain_text(cells, module, "web.event.text")?;
if values[0].is_empty() {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.event.name",
"事件 name must not be empty",
)
.at(module.relative.clone(), Some(cells[0].span))]));
}
if !seen.insert(values[0].clone()) {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.event.name",
format!("事件 name {:?} is declared twice", values[0]),
)
.at(module.relative.clone(), Some(cells[0].span))]));
}
events.push(EventDecl {
name: values[0].clone(),
data: values[1].clone(),
description: values[2].clone(),
span: json_span(cells[0].span),
});
}
}
let mut scenarios = Vec::new();
if let Some((_, table)) =
document::section_table(module, unit, "场景", &["状态", "内容", "初始"])?
{
if !slots.is_empty() {
return Err(design_error(
"web.scene.not_leaf",
"`场景` is only allowed on a leaf component (no child slots)",
));
}
if table.rows.len() > self.config.max_scenes {
return Err(design_error(
"web.limit.scenes",
format!("scene limit {} exceeded", self.config.max_scenes),
));
}
let mut seen = BTreeSet::new();
let mut initial = 0;
for cells in &table.rows {
let state = cells[0].text.trim().to_string();
if !valid_state(&state) {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.scene.state",
format!("state {state:?} must be a lowercase ASCII slug"),
)
.at(module.relative.clone(), Some(cells[0].span))]));
}
if !seen.insert(state.clone()) {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.scene.state_duplicate",
format!("state {state:?} is declared twice"),
)
.at(module.relative.clone(), Some(cells[0].span))]));
}
let link = single_link(&cells[1], &module.relative, cells[1].span)?;
let (target_module, target_unit) = self.resolve_content_unit(module, link)?;
if cells[1].text.trim() != link.text.trim() {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.scene.content",
"场景 content cell must contain only the content Link",
)
.at(module.relative.clone(), Some(cells[1].span))]));
}
let is_initial = parse_initial(cells[2].text.trim()).map_err(|message| {
LoadError::Design(vec![Diagnostic::error("web.scene.initial", message)
.at(module.relative.clone(), Some(cells[2].span))])
})?;
if is_initial {
initial += 1;
}
let content = source_ref(&target_module, &target_unit, target_unit.anchor_text());
scenarios.push(Scenario {
state,
content,
initial: is_initial,
});
}
if initial != 1 {
return Err(design_error(
"web.scene.initial",
format!("exactly one scene must be initial, found {initial}"),
));
}
}
let mut interactions = Vec::new();
if let Some((_, table)) =
document::section_table(module, unit, "交互", &["当前", "事件", "下一状态"])?
{
if scenarios.is_empty() {
return Err(design_error(
"web.interaction.without_scene",
"`交互` requires a `场景` table",
));
}
if table.rows.len() > self.config.max_transitions {
return Err(design_error(
"web.limit.transitions",
format!("transition limit {} exceeded", self.config.max_transitions),
));
}
let states: BTreeSet<&str> = scenarios.iter().map(|item| item.state.as_str()).collect();
let initial_state = scenarios
.iter()
.find(|item| item.initial)
.map(|item| item.state.clone())
.unwrap_or_default();
let mut seen = BTreeSet::new();
for cells in &table.rows {
let values = plain_text(cells, module, "web.interaction.text")?;
let (current, event, next) =
(values[0].clone(), values[1].clone(), values[2].clone());
if !states.contains(current.as_str()) || !states.contains(next.as_str()) {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.interaction.state",
format!(
"transition {current:?} -> {next:?} references an undeclared state"
),
)
.at(module.relative.clone(), Some(cells[0].span))]));
}
if event.is_empty() {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.interaction.event",
"transition event label must not be empty",
)
.at(module.relative.clone(), Some(cells[1].span))]));
}
if !seen.insert((current.clone(), event.clone())) {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.interaction.event_duplicate",
format!("event {event:?} is declared twice for state {current:?}"),
)
.at(module.relative.clone(), Some(cells[1].span))]));
}
interactions.push(Interaction {
current,
event,
next,
span: json_span(cells[0].span),
});
}
let mut reachable = BTreeSet::from([initial_state.clone()]);
let mut changed = true;
while changed {
changed = false;
for transition in &interactions {
if reachable.contains(&transition.current)
&& !reachable.contains(&transition.next)
{
reachable.insert(transition.next.clone());
changed = true;
}
}
}
for state in &states {
if !reachable.contains(*state) {
return Err(design_error(
"web.interaction.unreachable",
format!("scene state {state:?} is not reachable from the initial state"),
));
}
}
if scenarios.len() > 1 && interactions.is_empty() {
return Err(design_error(
"web.interaction.missing",
"multi-state `场景` requires an `交互` table",
));
}
} else if scenarios.len() > 1 {
return Err(design_error(
"web.interaction.missing",
"multi-state `场景` requires an `交互` table",
));
}
let mut dependencies = Vec::new();
if let Some((_, table)) = document::section_table(module, unit, "依赖", &["组件", "原因"])?
{
for cells in &table.rows {
let link = single_link(&cells[0], &module.relative, cells[0].span)?;
if cells[0].text.trim() != link.text.trim() {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.dependency.target",
"依赖 component cell must contain only the Link",
)
.at(module.relative.clone(), Some(cells[0].span))]));
}
let reason = cells[1].text.trim().to_string();
if reason.is_empty() {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.dependency.reason",
"依赖 reason must not be empty",
)
.at(module.relative.clone(), Some(cells[1].span))]));
}
let (target_module, target_unit) =
self.resolve_dependency_component(module, link)?;
dependencies.push(Dependency {
target: normalized_key(&target_module, target_unit.anchor_text()),
reason,
span: json_span(cells[0].span),
});
}
}
let mut acceptance = None;
if let Some(section) = document::direct_sections(module, unit)
.into_iter()
.find(|section| section.name == "验收")
{
let start = section
.heading_span
.map(|(_, end)| end)
.unwrap_or(section.span.0);
let text = module
.text_span(start, section.span.1)
.unwrap_or_default()
.trim()
.to_string();
if text.is_empty() {
return Err(design_error(
"web.acceptance.empty",
"`验收` section must not be empty",
));
}
acceptance = Some(Acceptance {
text,
span: json_span(section.span),
});
}
self.stack.pop();
if self.definitions.len() >= self.config.max_definitions {
return Err(design_error(
"web.limit.definitions",
format!("definition limit {} exceeded", self.config.max_definitions),
));
}
let definition = ComponentDef {
key: key.clone(),
source: source_ref(module, unit, anchor),
slots,
inputs,
events,
scenarios,
interactions,
dependencies,
acceptance,
};
self.definitions.insert(key.clone(), definition);
Ok(key)
}
}
fn valid_state(state: &str) -> bool {
let mut chars = state.chars();
let Some(first) = chars.next() else {
return false;
};
first.is_ascii_lowercase()
&& chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || matches!(ch, '_' | '-'))
}
fn validate_design(definitions: &BTreeMap<String, ComponentDef>) -> Result<(), LoadError> {
// Dependencies must name loaded design components and stay acyclic.
let mut edges: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
for (key, definition) in definitions {
for dependency in &definition.dependencies {
if !definitions.contains_key(&dependency.target) {
return Err(LoadError::Design(vec![Diagnostic::error(
"web.dependency.unknown",
format!(
"依赖 target {:?} is not a loaded design component",
dependency.target
),
)
.at(
definition.source.path.clone(),
Some((dependency.span.start, dependency.span.end)),
)]));
}
edges
.entry(key.as_str())
.or_default()
.push(dependency.target.as_str());
}
}
fn visit<'a>(
node: &'a str,
edges: &BTreeMap<&'a str, Vec<&'a str>>,
visiting: &mut BTreeSet<&'a str>,
done: &mut BTreeSet<&'a str>,
) -> bool {
if done.contains(node) {
return true;
}
if !visiting.insert(node) {
return false;
}
if let Some(targets) = edges.get(node) {
for target in targets {
if !visit(target, edges, visiting, done) {
return false;
}
}
}
visiting.remove(node);
done.insert(node);
true
}
let mut done = BTreeSet::new();
for node in edges.keys() {
let mut visiting = BTreeSet::new();
if !visit(node, &edges, &mut visiting, &mut done) {
return Err(design_error(
"web.dependency.cycle",
"design dependency cycle requires coordination and cannot be claimed parallel",
));
}
}
// Scene content must never be a design component declaration.
let keys: BTreeSet<String> = definitions.keys().cloned().collect();
for definition in definitions.values() {
for scenario in &definition.scenarios {
let target = normalized_key_from_source(&scenario.content);
if keys.contains(&target) {
return Err(design_error(
"web.scene.content_component",
format!(
"场景 content {:?} is a design component declaration",
target
),
));
}
}
}
Ok(())
}
fn normalized_key_from_source(source: &SourceRef) -> String {
format!("{}#{}", source.path, source.anchor)
}
/// Load one explicit design unit and interpret the contract.
pub fn load(config: &LoadConfig) -> Result<Design, LoadError> {
if config.unit.starts_with('#') {
@@ -486,8 +1083,15 @@ pub fn load(config: &LoadConfig) -> Result<Design, LoadError> {
let module = loader.analyze(&entry)?;
let unit = document::knowledge_h2(&module, &config.unit)?;
let root_key = loader.load_definition(&module, &unit, &config.unit, 0)?;
validate_design(&loader.definitions)?;
let mut instances = Vec::new();
collect_instances(&loader.definitions, &root_key, "root", &mut instances);
if instances.len() > config.max_instances {
return Err(design_error(
"web.limit.instances",
format!("instance limit {} exceeded", config.max_instances),
));
}
let mut sources = loader
.modules
.values()
@@ -556,6 +1160,45 @@ pub fn handoff(design: &Design) -> String {
slot.slot, slot.row, slot.width, slot.target
));
}
for input in &definition.inputs {
out.push_str(&format!(
"{indent} - input `{}` ({}) {}\n",
input.name, input.entry_type, input.description
));
}
for event in &definition.events {
out.push_str(&format!(
"{indent} - event `{}` ({}) {}\n",
event.name, event.data, event.description
));
}
for scenario in &definition.scenarios {
out.push_str(&format!(
"{indent} - scenario `{}`{} -> `{}#{}`\n",
scenario.state,
if scenario.initial { " (initial)" } else { "" },
scenario.content.path,
scenario.content.anchor
));
}
for interaction in &definition.interactions {
out.push_str(&format!(
"{indent} - transition `{}` --{}--> `{}`\n",
interaction.current, interaction.event, interaction.next
));
}
for dependency in &definition.dependencies {
out.push_str(&format!(
"{indent} - dependency `{}`: {}\n",
dependency.target, dependency.reason
));
}
if let Some(acceptance) = &definition.acceptance {
out.push_str(&format!(
"{indent} - acceptance: {}\n",
acceptance.text.replace('\n', " ")
));
}
}
}
out.push_str("\n## Sources\n\n");