//! Contract tests for `spec/document-structure.md` (marqdo-cli#25). //! //! These drive the real binary and assert only the current, implemented //! document-structure semantics: heading modes and inheritance, unit identity //! and scope rules, anchor collision numbering, byte-exact spans, `index.mq.md` //! entry/import meaning, and the link ≠ import ≠ call separation. #[path = "support/stdlib.rs"] pub mod stdlib_support; use std::path::{Path, PathBuf}; use std::process::Output; struct TempDir(PathBuf); impl TempDir { fn new(tag: &str) -> Self { let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|duration| duration.as_nanos()) .unwrap_or(0); let path = std::env::temp_dir().join(format!( "marqdo-document-structure-{tag}-{}-{nanos}", std::process::id() )); std::fs::create_dir_all(&path).unwrap(); Self(path) } fn path(&self) -> &Path { &self.0 } fn write(&self, relative: &str, contents: &str) { let path = self.path().join(relative); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).unwrap(); } std::fs::write(path, contents).unwrap(); } fn write_bytes(&self, relative: &str, contents: &[u8]) { let path = self.path().join(relative); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).unwrap(); } std::fs::write(path, contents).unwrap(); } } impl Drop for TempDir { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } fn cli(args: &[&str], dir: &Path) -> Output { stdlib_support::cli_command() .args(args) .current_dir(dir) .output() .unwrap() } fn stderr(output: &Output) -> String { String::from_utf8_lossy(&output.stderr).to_string() } fn check_document(dir: &Path, document: &str, artifact: &Path) -> serde_json::Value { let output = cli( &["check", document, "--emit", artifact.to_str().unwrap()], dir, ); assert!( output.status.success(), "check {document} failed: {}", stderr(&output) ); serde_json::from_slice(&std::fs::read(artifact).unwrap()).unwrap() } fn units(analysis: &serde_json::Value) -> Vec<&serde_json::Value> { analysis["modules"][0]["units"] .as_array() .unwrap() .iter() .collect() } fn unit<'a>(analysis: &'a serde_json::Value, path: &[&str]) -> &'a serde_json::Value { let path: Vec = path.iter().map(|segment| segment.to_string()).collect(); units(analysis) .into_iter() .find(|unit| { unit["path"] .as_array() .unwrap() .iter() .map(|segment| segment.as_str().unwrap()) .eq(path.iter().map(String::as_str)) }) .unwrap_or_else(|| panic!("missing unit {path:?}")) } #[test] fn heading_modes_inherit_from_the_nearest_ancestor_not_a_sibling() { let dir = TempDir::new("modes"); dir.write( "index.mq.md", "# @knowledge 数学\n\n\ ## @exec main\n\n`return 1`\n\n\ ## 普通说明\n\n这段是知识叙述。\n\n\ ### 子节\n\n更多知识。\n\n\ ## @exec 计算力\n\n`return 2`\n\n\ ### 细节\n\n`return 3`\n", ); let artifact = dir.path().join("analysis.json"); let analysis = check_document(dir.path(), "index.mq.md", &artifact); let root = &units(&analysis)[0]; assert_eq!(root["path"], serde_json::json!([])); assert_eq!(root["kind"], "root"); assert_eq!(root["mode"], "knowledge"); assert_eq!(root["mode_origin"], "default"); let namespace = unit(&analysis, &["数学"]); assert_eq!(namespace["kind"], "namespace"); assert_eq!(namespace["parent_id"], root["id"]); let main = unit(&analysis, &["数学", "main"]); assert_eq!(main["kind"], "function"); assert_eq!(main["mode"], "exec"); assert_eq!(main["mode_origin"], "explicit"); assert!(main["function"].is_string()); assert_eq!(main["parent_id"], namespace["id"]); // A sibling heading without a marker inherits the Knowledge H1, never the // preceding Exec H2. let knowledge = unit(&analysis, &["数学", "普通说明"]); assert_eq!(knowledge["kind"], "knowledge"); assert_eq!(knowledge["mode"], "knowledge"); assert_eq!(knowledge["mode_origin"], "inherited"); assert_eq!(knowledge["mode_source_unit_id"], namespace["id"]); assert!(knowledge["function"].is_null()); // An H3 under an Exec H2 is Exec and belongs to that function. let section = unit(&analysis, &["数学", "计算力", "细节"]); assert_eq!(section["kind"], "section"); assert_eq!(section["mode"], "exec"); assert_eq!(section["mode_origin"], "inherited"); assert_eq!( section["parent_id"], unit(&analysis, &["数学", "计算力"])["id"] ); assert_eq!( section["function"], unit(&analysis, &["数学", "计算力"])["function"] ); // A level-3 section under Knowledge never becomes callable. let knowledge_section = unit(&analysis, &["数学", "普通说明", "子节"]); assert_eq!(knowledge_section["kind"], "section"); assert!(knowledge_section["function"].is_null()); } #[test] fn same_name_is_addressable_in_different_parents_but_rejected_in_one_scope() { let allowed = TempDir::new("same-name-allowed"); allowed.write( "index.mq.md", "# @knowledge 甲\n\n## 说明\n\nA\n\n# @knowledge 乙\n\n## 说明\n\nB\n", ); let analysis = check_document( allowed.path(), "index.mq.md", &allowed.path().join("analysis.json"), ); let first = unit(&analysis, &["甲", "说明"]); let second = unit(&analysis, &["乙", "说明"]); assert_ne!(first["id"], second["id"]); let anchors = analysis["modules"][0]["anchors"].as_array().unwrap(); assert_eq!(anchors.len(), 4); assert_eq!( anchors .iter() .find(|anchor| anchor["anchor"] == "说明") .unwrap()["unit_id"], first["id"] ); assert_eq!( anchors .iter() .find(|anchor| anchor["anchor"] == "说明-2") .unwrap()["unit_id"], second["id"] ); let rejected = TempDir::new("same-name-rejected"); rejected.write( "index.mq.md", "# @knowledge 数学\n\n## @exec 计算\n\n`return 1`\n\n## @exec 计算\n\n`return 2`\n", ); let artifact = rejected.path().join("analysis.json"); let output = cli( &["check", "index.mq.md", "--emit", artifact.to_str().unwrap()], rejected.path(), ); assert_eq!(output.status.code(), Some(1)); assert!( stderr(&output).contains("sem.duplicate_unit_name"), "unexpected stderr: {}", stderr(&output) ); assert!( !artifact.exists(), "a failed check must not leave an Analysis artifact" ); } #[test] fn spans_are_half_open_utf8_bytes_even_with_bom_crlf_and_no_final_newline() { let dir = TempDir::new("spans"); let mut bytes = Vec::new(); bytes.extend_from_slice(b"\xef\xbb\xbf"); // UTF-8 BOM bytes.extend_from_slice("# @knowledge 数学\r\n\r\n## @exec 计算\r\n\r\n`return 1`".as_bytes()); // CRLF line endings, no trailing newline dir.write_bytes("index.mq.md", &bytes); let analysis = check_document(dir.path(), "index.mq.md", &dir.path().join("analysis.json")); let module = &analysis["modules"][0]; let source = module["source"].as_str().unwrap(); assert_eq!(source.as_bytes(), bytes.as_slice()); assert_eq!(module["document"]["span"]["start"], 0); assert_eq!(module["document"]["span"]["end"], bytes.len()); for unit in units(&analysis) { let start = unit["span"]["start"].as_u64().unwrap() as usize; let end = unit["span"]["end"].as_u64().unwrap() as usize; assert!(start <= end && end <= bytes.len(), "span out of range"); assert!( std::str::from_utf8(&bytes[start..end]).is_ok(), "span is not on UTF-8 boundaries" ); if let Some(heading) = unit["heading_span"].as_object() { let hs = heading["start"].as_u64().unwrap() as usize; let he = heading["end"].as_u64().unwrap() as usize; assert_eq!(bytes[hs], b'#', "heading_span must start at the heading"); assert!(std::str::from_utf8(&bytes[hs..he]).is_ok()); } } // The function section runs to EOF because it is the last heading. let function = unit(&analysis, &["数学", "计算"]); assert_eq!( function["span"]["end"].as_u64().unwrap() as usize, bytes.len() ); let heading_start = function["heading_span"]["start"].as_u64().unwrap() as usize; assert_eq!(&bytes[heading_start..heading_start + 2], b"##"); } #[test] fn index_md_is_the_entry_and_a_directory_dependency_resolves_to_its_index() { let dir = TempDir::new("index-entry"); dir.write( "marqdo.yaml", "project:\n name: demo\n version: 0.1.0\ndependencies:\n geo:\n path: ./geometry\n", ); dir.write( "geometry/index.mq.md", "# @knowledge 几何\n\n## @exec 面积\n\n`return 6`\n", ); dir.write( "index.mq.md", "---\nimport:\n geo: '@geo'\n---\n\n# @knowledge 主\n\n## @exec main\n\n`return 1`\n", ); let lock = cli(&["lock"], dir.path()); assert!(lock.status.success(), "lock failed: {}", stderr(&lock)); let analysis = check_document(dir.path(), "index.mq.md", &dir.path().join("analysis.json")); assert_eq!( analysis["project"]["entry_module_id"], "root:demo@0.1.0::index.mq.md" ); let modules = analysis["modules"].as_array().unwrap(); assert_eq!(modules.len(), 2, "no implicit modules may be loaded"); let dependency = modules .iter() .find(|module| module["id"].as_str().unwrap().starts_with("dep:geo@")) .expect("dependency module"); assert!( dependency["id"] .as_str() .unwrap() .ends_with("::index.mq.md"), "a directory dependency resolves to its index.mq.md" ); let root = modules .iter() .find(|module| module["id"] == "root:demo@0.1.0::index.mq.md") .unwrap(); assert_eq!( root["imports"][0]["resolved"], dependency["id"], "the explicit import names the dependency index module" ); assert!( dependency["units"] .as_array() .unwrap() .iter() .any(|unit| unit["path"] == serde_json::json!(["几何", "面积"])), "the dependency index is a normal document with normal units" ); } #[test] fn a_markdown_link_is_neither_an_import_nor_a_call() { let dir = TempDir::new("link-only"); dir.write( "index.mq.md", "# @knowledge 主\n\n[另一个文稿](other.mq.md)\n\n## @exec main\n\n`return 1`\n", ); dir.write("other.mq.md", "# @knowledge 其他\n\n## 说明\n\n正文\n"); let plain = check_document(dir.path(), "index.mq.md", &dir.path().join("plain.json")); assert_eq!(plain["modules"].as_array().unwrap().len(), 1); let reference = &plain["modules"][0]["references"][0]; assert_eq!(reference["state"], "not_loaded"); assert!(plain["modules"][0]["imports"] .as_array() .unwrap() .is_empty()); assert!(plain["modules"][0]["calls"].as_array().unwrap().is_empty()); // `check --refs` verifies local link targets through the explicit // verification catalog; it still does not import the target or add it to // the program, and the emitted Analysis keeps the loaded-only reference // projection (`not_loaded` means "not part of this program", not "missing"). let refs_artifact = dir.path().join("refs.json"); let output = cli( &[ "check", "index.mq.md", "--refs", "--emit", refs_artifact.to_str().unwrap(), ], dir.path(), ); assert!(output.status.success(), "{}", stderr(&output)); assert!( !stderr(&output).contains("ref."), "an existing local link target must not produce a refs diagnostic: {}", stderr(&output) ); let refs: serde_json::Value = serde_json::from_slice(&std::fs::read(&refs_artifact).unwrap()).unwrap(); assert_eq!(refs["modules"].as_array().unwrap().len(), 1); assert_eq!(refs["modules"][0]["references"][0]["state"], "not_loaded"); assert!(refs["modules"][0]["imports"].as_array().unwrap().is_empty()); assert!(refs["modules"][0]["calls"].as_array().unwrap().is_empty()); } #[test] fn unknown_mode_markers_are_still_hard_errors() { let dir = TempDir::new("bad-marker"); dir.write("index.mq.md", "# @knowledge 数学\n\n## @foo 标题\n\n正文\n"); let artifact = dir.path().join("analysis.json"); let output = cli( &["check", "index.mq.md", "--emit", artifact.to_str().unwrap()], dir.path(), ); assert_eq!(output.status.code(), Some(1)); assert!( stderr(&output).contains("sem.invalid_mode_marker"), "unexpected stderr: {}", stderr(&output) ); assert!(!artifact.exists()); }