From 629fb9834db05a6a2d1eceaebec1812da0a853eb Mon Sep 17 00:00:00 2001 From: cflmy Date: Wed, 25 Nov 2026 09:44:16 +0800 Subject: [PATCH] frontend: expose heading scope facts for the public boundary Keep the one heading index but record the effective mode origin and source unit, the nearest ancestor unit, the complete section span and the heading span separately, and cover the whole source with the root unit. Reject a dot inside a function/namespace component as an ambiguous public identity, and escape the structural separators in UnitId display so a segment containing '/', '#' or '%' cannot collide with a deeper path. Add focused tests for the new invariants and diagnostics. --- crates/marqdo-frontend/src/units.rs | 197 ++++++++++++++++++++++++-- crates/marqdo-ir/src/lib.rs | 47 +++++- crates/marqdo-value/src/diagnostic.rs | 9 ++ 3 files changed, 237 insertions(+), 16 deletions(-) diff --git a/crates/marqdo-frontend/src/units.rs b/crates/marqdo-frontend/src/units.rs index 9ece2e7..326cfc9 100644 --- a/crates/marqdo-frontend/src/units.rs +++ b/crates/marqdo-frontend/src/units.rs @@ -39,6 +39,16 @@ pub struct HeadingInfo { pub kind: UnitKind, /// Semantic mode declared or inherited by this heading. pub mode: SemanticMode, + /// How the effective mode was established. + pub mode_origin: ModeOrigin, + /// Unit that provided the effective mode (this unit, an explicit ancestor, + /// or the document root). + pub mode_source_unit_id: UnitId, + /// Nearest real ancestor unit (the root for a top-level heading). + pub parent_id: UnitId, + /// Complete section range: this heading through the next same-or-higher + /// heading, or the end of the source. It includes child headings. + pub full_span: Span, } /// A function range mapped from a level-2 heading. @@ -116,6 +126,28 @@ pub enum SemanticMode { Exec, } +/// How a heading's effective mode was established. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ModeOrigin { + /// The document root is Knowledge by default. + Default, + /// The ATX heading declares `@exec` or `@knowledge`. + Explicit, + /// The heading inherits the mode of an ancestor or the root. + Inherited, +} + +impl ModeOrigin { + /// Stable public name used by Analysis. + pub fn as_str(self) -> &'static str { + match self { + ModeOrigin::Default => "default", + ModeOrigin::Explicit => "explicit", + ModeOrigin::Inherited => "inherited", + } + } +} + fn heading_declaration( node: &MdNode, ) -> (Option, Option, Option) { @@ -184,20 +216,22 @@ fn heading_declaration( /// Build the heading/function index for a parsed document. pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex { let mut index = UnitIndex::default(); + let root_id = UnitId { + module: module.clone(), + path: Vec::new(), + }; index.units.push(UnitInfo { - id: UnitId { - module: module.clone(), - path: Vec::new(), - }, + id: root_id.clone(), level: 0, name: String::new(), - span: doc.root.span, + // The root covers the whole source, including a tolerated UTF-8 BOM. + span: Span::new(0, doc.source.len()), kind: UnitKind::Root, function: None, }); - // Stack of (level, path, mode) for ancestors. - let mut stack: Vec<(u8, Vec, SemanticMode)> = Vec::new(); + // Stack of (level, path, mode, mode_source_unit_id) for ancestors. + let mut stack: Vec<(u8, Vec, SemanticMode, UnitId)> = Vec::new(); let mut seen: BTreeMap<(Vec, String), Span> = BTreeMap::new(); let mut current_namespace: Option = None; let mut current_function: Option = None; @@ -224,7 +258,7 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex { // Resolve the ancestor scope before deriving the mode: remove every // same-or-higher-level heading first so a heading can only inherit from // its nearest *ancestor*, never from the previous sibling. - while let Some((parent_level, _, _)) = stack.last() { + while let Some((parent_level, _, _, _)) = stack.last() { if *parent_level >= level { stack.pop(); } else { @@ -233,8 +267,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex { } let inherited = stack .last() - .map(|(_, _, mode)| *mode) + .map(|(_, _, mode, _)| *mode) .unwrap_or(SemanticMode::Knowledge); + let inherited_source = stack + .last() + .map(|(_, _, _, source)| source.clone()) + .unwrap_or_else(|| root_id.clone()); let mode = declared.unwrap_or(inherited); let raw_name = match declared_name { Some(name) => name, @@ -254,13 +292,25 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex { let parent_path = stack .last() - .map(|(_, path, _)| path.clone()) + .map(|(_, path, _, _)| path.clone()) .unwrap_or_default(); + let parent_id = UnitId { + module: module.clone(), + path: parent_path.clone(), + }; let path = { let mut path = parent_path.clone(); path.push(name.clone()); path }; + let unit_id = UnitId { + module: module.clone(), + path: path.clone(), + }; + let (mode_origin, mode_source_unit_id) = match declared { + Some(_) => (ModeOrigin::Explicit, unit_id.clone()), + None => (ModeOrigin::Inherited, inherited_source), + }; let key = (parent_path.clone(), name.clone()); if let Some(previous) = seen.get(&key) { @@ -304,6 +354,27 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex { Some(namespace) => format!("{namespace}.{local}"), None => local.clone(), }; + // `.` separates namespace from local name in a FunctionId. A + // component that itself contains `.` would make two different + // definitions render the same public id; reject it explicitly + // instead of silently producing a non-injective identity. + let ambiguous = local.contains('.') + || current_namespace + .as_deref() + .map(|namespace| namespace.contains('.')) + .unwrap_or(false); + if ambiguous { + index.diagnostics.push( + Diagnostic::error( + codes::SEM_AMBIGUOUS_IDENTITY, + Some(child.span), + "function or namespace name contains `.`, which is the namespace separator; the public function id would be ambiguous", + ) + .with_hint( + "rename the namespace or function so it does not contain a dot", + ), + ); + } let id = FunctionId { module: module.clone(), name: qualified, @@ -327,10 +398,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex { path: path.clone(), kind, mode, - }; - let unit_id = UnitId { - module: module.clone(), - path, + mode_origin, + mode_source_unit_id, + parent_id, + // Filled after all headings are known (the end is the next + // same-or-higher heading or EOF). + full_span: child.span, }; index.units.push(UnitInfo { id: unit_id, @@ -361,7 +434,21 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex { } } heading_infos.push(info.clone()); - stack.push((level, info.path.clone(), mode)); + stack.push((level, info.path.clone(), mode, info.mode_source_unit_id.clone())); + } + + // Complete section ranges: from this heading to the next heading of the + // same or a higher level, or EOF. Child headings are included. + let total = doc.source.len(); + for position in 0..heading_infos.len() { + let level = heading_infos[position].level; + let start = heading_infos[position].span.start; + let end = heading_infos[position + 1..] + .iter() + .find(|candidate| candidate.level <= level) + .map(|candidate| candidate.span.start) + .unwrap_or(total); + heading_infos[position].full_span = Span::new(start, end.max(start)); } // Function body ranges and spans. @@ -624,6 +711,86 @@ mod tests { assert_eq!(normal.kind, UnitKind::Knowledge); } + #[test] + fn full_spans_cover_sections_and_parent_edges_form_a_tree() { + let source = "# @knowledge 力学\n\n## @exec 计算力\n\n`return 1`\n\n### 细节\n\n正文\n\n## 说明\n\n结尾\n"; + let index = index_of(source); + let by_name = |name: &str| { + index + .headings + .iter() + .find(|heading| heading.name == name) + .unwrap_or_else(|| panic!("missing heading {name}")) + }; + let calc = by_name("计算力"); + let detail = by_name("细节"); + let note = by_name("说明"); + // The function range includes its H3 child but not the next H2. + assert_eq!(calc.full_span.start, calc.span.start); + assert!(calc.full_span.end > detail.span.start); + assert_eq!(calc.full_span.end, note.span.start); + assert_eq!(detail.full_span.end, note.span.start); + assert_eq!(note.full_span.end, source.len()); + assert_eq!(detail.parent_id.path, vec!["力学".to_string(), "计算力".to_string()]); + assert_eq!(calc.parent_id.path, vec!["力学".to_string()]); + let root = &index.units[0]; + assert_eq!(root.span, marqdo_span::Span::new(0, source.len())); + assert_eq!( + calc.parent_id, + index.units.iter().find(|u| u.name == "力学").unwrap().id.clone() + ); + assert_eq!(by_name("力学").parent_id, root.id); + } + + #[test] + fn mode_origin_and_source_are_explicit() { + let index = index_of( + "# @knowledge 数学\n\n## @exec 计算\n\n### 细节\n\n`return 1`\n\n## 说明\n\n正文\n", + ); + let by_name = |name: &str| { + index + .headings + .iter() + .find(|heading| heading.name == name) + .unwrap_or_else(|| panic!("missing heading {name}")) + }; + let namespace = by_name("数学"); + assert_eq!(namespace.mode_origin, ModeOrigin::Explicit); + assert_eq!(namespace.mode_source_unit_id, namespace_unit(&index, "数学")); + let calc = by_name("计算"); + assert_eq!(calc.mode_origin, ModeOrigin::Explicit); + assert_eq!(calc.mode_source_unit_id.path, vec!["数学".to_string(), "计算".to_string()]); + let detail = by_name("细节"); + assert_eq!(detail.mode_origin, ModeOrigin::Inherited); + assert_eq!(detail.mode_source_unit_id.path, calc.mode_source_unit_id.path); + let note = by_name("说明"); + assert_eq!(note.mode_origin, ModeOrigin::Inherited); + assert_eq!(note.mode_source_unit_id.path, vec!["数学".to_string()]); + } + + fn namespace_unit(index: &UnitIndex, name: &str) -> UnitId { + index + .units + .iter() + .find(|unit| unit.name == name) + .map(|unit| unit.id.clone()) + .expect("namespace unit") + } + + #[test] + fn a_dot_in_a_function_component_is_rejected_as_an_ambiguous_identity() { + let index = index_of("# @knowledge a.b\n\n## @exec f\n\n`return 1`\n"); + assert!(index + .diagnostics + .iter() + .any(|diagnostic| diagnostic.code == "sem.ambiguous_identity")); + let index = index_of("## @exec a.b\n\n`return 1`\n"); + assert!(index + .diagnostics + .iter() + .any(|diagnostic| diagnostic.code == "sem.ambiguous_identity")); + } + #[test] fn knowledge_scope_payloads_and_sections_stay_inert() { let index = index_of( diff --git a/crates/marqdo-ir/src/lib.rs b/crates/marqdo-ir/src/lib.rs index 6323e67..cd58a07 100644 --- a/crates/marqdo-ir/src/lib.rs +++ b/crates/marqdo-ir/src/lib.rs @@ -137,12 +137,31 @@ impl fmt::Display for UnitId { if index > 0 { f.write_str("/")?; } - f.write_str(part)?; + f.write_str(&escape_identity_segment(part))?; } Ok(()) } } +/// Escape the structural separators of a canonical identity segment. +/// +/// A unit display id is `#/`. Escaping `%`, `/` and `#` +/// inside each segment keeps the rendering injective: a single heading named +/// `a/b` renders `a%2Fb`, never the two-level path `a` -> `b`. Headings that +/// do not contain a separator keep their existing rendering. +pub fn escape_identity_segment(segment: &str) -> String { + let mut out = String::with_capacity(segment.len()); + for ch in segment.chars() { + match ch { + '%' => out.push_str("%25"), + '/' => out.push_str("%2F"), + '#' => out.push_str("%23"), + other => out.push(other), + } + } + out +} + /// Role of a heading range. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -582,6 +601,32 @@ mod tests { assert_eq!(module.id.to_string(), "root:default::index.mq.md"); } + #[test] + fn unit_ids_are_injective_across_separator_characters() { + let module = ModuleId::from("index.mq.md"); + let one_segment = UnitId { + module: module.clone(), + path: vec!["a/b".to_string()], + }; + let two_segments = UnitId { + module: module.clone(), + path: vec!["a".to_string(), "b".to_string()], + }; + assert_ne!(one_segment.to_string(), two_segments.to_string()); + assert!(one_segment.to_string().ends_with("#a%2Fb")); + assert!(two_segments.to_string().ends_with("#a/b")); + let hash = UnitId { + module: module.clone(), + path: vec!["a#b%c".to_string()], + }; + assert_eq!(hash.to_string(), "root:default::index.mq.md#a%23b%25c"); + let plain = UnitId { + module, + path: vec!["数学".to_string(), "计算力".to_string()], + }; + assert_eq!(plain.to_string(), "root:default::index.mq.md#数学/计算力"); + } + #[test] fn ir_serializes_for_inspect() { let stmt = Stmt::Return { diff --git a/crates/marqdo-value/src/diagnostic.rs b/crates/marqdo-value/src/diagnostic.rs index 981cf14..d855627 100644 --- a/crates/marqdo-value/src/diagnostic.rs +++ b/crates/marqdo-value/src/diagnostic.rs @@ -53,6 +53,9 @@ pub mod codes { pub const SEM_NO_ENTRY_FUNCTION: &str = "sem.no_entry_function"; /// A signature was inferred rather than declared. pub const SEM_INFERRED_SIGNATURE: &str = "sem.inferred_signature"; + /// A canonical identity would be ambiguous (a separator appears inside a + /// component), so no injective public identity can be produced. + pub const SEM_AMBIGUOUS_IDENTITY: &str = "sem.ambiguous_identity"; /// An executable payload failed to parse as an expression or statement. pub const EXPR_PARSE: &str = "expr.parse"; /// A function name is referenced but no such function exists. @@ -69,6 +72,12 @@ pub mod codes { pub const MODULE_CYCLE: &str = "module.cycle"; /// A Markdown reference or link target cannot be resolved. pub const REF_UNRESOLVED: &str = "ref.unresolved"; + /// A Markdown reference has several exact canonical-name candidates. + pub const REF_AMBIGUOUS: &str = "ref.ambiguous"; + /// A Markdown reference is malformed or outside the allowed scope. + pub const REF_INVALID: &str = "ref.invalid"; + /// A Markdown reference target was not verified by the current catalog. + pub const REF_NOT_LOADED: &str = "ref.not_loaded"; /// The requested math operation is outside the supported subset. pub const MATH_UNSUPPORTED: &str = "math.unsupported"; /// A foreign language kernel is not available on this machine.