diff --git a/crates/cli/src/analysis.rs b/crates/cli/src/analysis.rs deleted file mode 100644 index fa8e686..0000000 --- a/crates/cli/src/analysis.rs +++ /dev/null @@ -1,653 +0,0 @@ -//! Public Analysis projection (spec/analysis.md). -//! -//! This is deliberately not a serde dump of `marqdo-ir`: the schema and node -//! kinds are the public contract, while internal Rust types may change. The -//! exporter is read-only and never executes a document, loads a plugin or -//! starts a foreign kernel. - -use std::path::Path; - -use marqdo_expression::{BinaryOp, Expr, UnaryOp}; -use marqdo_ir::{Function, Module, ModuleId, PlaceTarget, Resource, SignatureKind, Stmt, UnitKind}; -use marqdo_span::Span; -use serde_json::{json, Value}; -use sha2::{Digest, Sha256}; - -use crate::loader::LoadedProject; - -/// Schema name and version. -pub const SCHEMA: &str = "marqdo.analysis"; -pub const SCHEMA_VERSION: u32 = 3; - -/// Build the deterministic public projection. -pub fn build(project: &LoadedProject) -> Value { - let mut modules = Vec::new(); - for (module_id, file) in &project.files { - let module = &file.analysis.module; - modules.push(json!({ - "id": module_id.to_string(), - "package_instance_id": module_id.instance, - "relative_path": module_id.relative_path, - "source_digest": sha256_hex(file.source.as_bytes()), - "units": units_json(module), - "functions": module.functions.iter().map(function_json).collect::>(), - "imports": module.imports.iter().map(|import| json!({ - "alias": import.alias, - "target": import.target, - "span": import.span, - "resolved": project.program.resolve_import(module_id, &import.alias).map(ToString::to_string), - })).collect::>(), - "references": reference_edges(project, module_id), - "calls": module.functions.iter().flat_map(|function| calls_json(project, module, function)).collect::>(), - "resources": resources_json(module_id, module), - })); - } - modules.sort_by(|a, b| { - a.get("id") - .and_then(Value::as_str) - .cmp(&b.get("id").and_then(Value::as_str)) - }); - json!({ - "schema": SCHEMA, - "schema_version": SCHEMA_VERSION, - "producer": { - "name": "marqdo", - "version": env!("CARGO_PKG_VERSION"), - "markdown_profile": "marqdo.md.v1", - }, - "project": { - "root_id": project.identity.root_id(), - "identity_kind": project.identity.kind(), - "lock_digest": lock_digest(project), - "stdlib": project.stdlib.as_ref().map(|stdlib| json!({ - "version": stdlib.version, - "digest": stdlib.digest, - "instance_id": stdlib.instance_id, - })), - }, - "modules": modules, - "diagnostics": diagnostics_json(project), - }) -} - -/// Encode exactly the bytes written by `check --emit`. -fn encode(project: &LoadedProject) -> Result, String> { - serde_json::to_vec_pretty(&build(project)) - .map_err(|error| format!("cannot encode analysis: {error}")) -} - -/// SHA-256 of the exact emitted Analysis bytes. -pub fn digest(project: &LoadedProject) -> Result { - encode(project).map(|bytes| format!("sha256:{}", sha256_hex(&bytes))) -} - -/// Atomically write the projection. An error must not leave a stale success -/// artifact behind. -pub fn write(project: &LoadedProject, path: &Path) -> Result<(), String> { - let bytes = encode(project)?; - let parent = path - .parent() - .filter(|parent| !parent.as_os_str().is_empty()) - .unwrap_or_else(|| Path::new(".")); - std::fs::create_dir_all(parent) - .map_err(|error| format!("cannot create `{}`: {error}", parent.display()))?; - let temporary = parent.join(format!( - ".{}.tmp-{}", - path.file_name() - .map(|name| name.to_string_lossy().to_string()) - .unwrap_or_else(|| "analysis.json".to_string()), - std::process::id() - )); - std::fs::write(&temporary, bytes) - .map_err(|error| format!("cannot write `{}`: {error}", temporary.display()))?; - if let Err(error) = std::fs::rename(&temporary, path) { - let _ = std::fs::remove_file(&temporary); - return Err(format!("cannot publish `{}`: {error}", path.display())); - } - Ok(()) -} - -fn lock_digest(project: &LoadedProject) -> Value { - let path = project.root.join(marqdo_package::LOCK_FILE); - match std::fs::read(path) { - Ok(bytes) => Value::String(format!("sha256:{}", sha256_hex(&bytes))), - Err(_) => Value::String(String::new()), - } -} - -fn resources_json(module_id: &ModuleId, module: &Module) -> Vec { - let mut formula_index = 0usize; - let mut code_index = 0usize; - module - .resources - .iter() - .map(|resource| match resource { - Resource::Formula { - unit, - latex, - display, - span, - } => { - formula_index += 1; - json!({ - "id": format!("{module_id}#resource:formula-{formula_index}"), - "module_id": module_id.to_string(), - "unit_id": unit.to_string(), - "kind": "formula", - "span": span_json(*span), - "content_digest": sha256_hex(latex.as_bytes()), - "language": null, - "display": display, - }) - } - Resource::Code { - unit, - language, - source: _, - content_hash, - span, - } => { - code_index += 1; - json!({ - "id": format!("{module_id}#resource:code-{code_index}"), - "module_id": module_id.to_string(), - "unit_id": unit.to_string(), - "kind": "code", - "span": span_json(*span), - "content_digest": content_hash, - "language": language, - }) - } - }) - .collect() -} - -fn diagnostics_json(project: &LoadedProject) -> Vec { - project - .diagnostics - .iter() - .map(|item| { - let (line, column) = item - .line_col() - .map(|(line, column)| (Value::from(line), Value::from(column))) - .unwrap_or((Value::Null, Value::Null)); - json!({ - "module": item.module_id.to_string(), - "relative_path": item.module_id.relative_path, - "span": item.diagnostic.span.map(span_json), - "line": line, - "column": column, - "severity": if item.diagnostic.is_error() { "error" } else { "warning" }, - "code": item.diagnostic.code, - "message": item.diagnostic.message, - "hints": item.diagnostic.hints, - }) - }) - .collect() -} - -fn units_json(module: &Module) -> Vec { - module - .units - .iter() - .map(|unit| { - let kind = match unit.kind { - UnitKind::Root => "root", - UnitKind::Namespace => "namespace", - UnitKind::Function => "function", - UnitKind::Knowledge => "knowledge", - UnitKind::Section => "section", - }; - json!({ - "id": unit.id.to_string(), - "kind": kind, - "name": unit.name, - "level": unit.level, - "span": span_json(unit.span), - "function": unit.function.as_ref().map(ToString::to_string), - }) - }) - .collect() -} - -fn function_json(function: &Function) -> Value { - json!({ - "id": function.id.to_string(), - "unit_id": function.unit.to_string(), - "local_name": function.local_name, - "namespace": function.namespace, - "span": span_json(function.span), - "heading_span": span_json(function.heading_span), - "signature": { - "kind": match function.signature { - SignatureKind::Explicit => "explicit", - SignatureKind::Inferred => "inferred", - }, - "params": function.params.iter().map(|param| json!({ - "name": param.name, - "required": param.default.is_none(), - "type": param.type_annotation, - "default": param.default.as_ref().map(expr_json), - "span": span_json(param.span), - })).collect::>(), - }, - "effects": ["unknown"], - "body": function.body.iter().map(stmt_json).collect::>(), - }) -} - -/// Project an assignment place. Local targets keep the v1 string form; the new -/// index target is an additive object so existing consumers that compare the -/// local `target` string are unaffected (Analysis v3, ADR-0022). -fn place_json(place: &PlaceTarget) -> Value { - match place { - PlaceTarget::Local { name, .. } => Value::String(name.clone()), - PlaceTarget::Index { base, index, span } => json!({ - "kind": "index", - "base": expr_json(base), - "index": expr_json(index), - "span": span_json(*span), - }), - } -} - -fn stmt_json(stmt: &Stmt) -> Value { - match stmt { - Stmt::Assign { - target, - value, - span, - .. - } => json!({ - "kind": "assign", - "target": place_json(target), - "value": expr_json(value), - "span": span_json(*span), - }), - Stmt::Eval { expr, span } => json!({ - "kind": "expression", - "value": expr_json(expr), - "span": span_json(*span), - }), - Stmt::Branch { arms, span } => json!({ - "kind": "branch", - "arms": arms.iter().map(|arm| json!({ - "condition": expr_json(&arm.condition), - "condition_span": span_json(arm.condition_span), - "body": arm.body.iter().map(stmt_json).collect::>(), - "span": span_json(arm.span), - })).collect::>(), - "span": span_json(*span), - }), - Stmt::Loop { - condition, - condition_span, - body, - span, - } => json!({ - "kind": "loop", - "condition": expr_json(condition), - "condition_span": span_json(*condition_span), - "body": body.iter().map(stmt_json).collect::>(), - "span": span_json(*span), - }), - Stmt::Break { span } => json!({"kind": "break", "span": span_json(*span)}), - Stmt::Continue { span } => json!({"kind": "continue", "span": span_json(*span)}), - Stmt::Return { value, span } => json!({ - "kind": "return", - "value": expr_json(value), - "span": span_json(*span), - }), - } -} - -fn expr_json(expr: &Expr) -> Value { - let span = span_json(expr.span()); - match expr { - Expr::Int(value) => { - json!({"kind":"literal","type":"int","value":value.to_string(),"span":span}) - } - Expr::Float(value) => json!({"kind":"literal","type":"float","value":value,"span":span}), - Expr::Text(value) => json!({"kind":"literal","type":"text","value":value,"span":span}), - Expr::Bool(value) => json!({"kind":"literal","type":"bool","value":value,"span":span}), - Expr::None => json!({"kind":"literal","type":"none","span":span}), - Expr::Ident(ident) => { - json!({"kind":"variable","name":ident.name,"span":span_json(ident.span)}) - } - Expr::List(items) => { - json!({"kind":"list","items":items.iter().map(expr_json).collect::>(),"span":span}) - } - Expr::Record(entries) => json!({ - "kind":"record", - "entries": entries.iter().map(|entry| json!({ - "key": entry.key, - "key_span": span_json(entry.key_span), - "value": expr_json(&entry.value), - })).collect::>(), - "span":span - }), - Expr::Unary { op, operand, .. } => json!({ - "kind":"unary", - "op": unary_name(*op), - "operand": expr_json(operand), - "span":span - }), - Expr::Binary { - op, left, right, .. - } => json!({ - "kind":"binary", - "op": binary_name(*op), - "left": expr_json(left), - "right": expr_json(right), - "span":span - }), - Expr::Member { base, name, .. } => json!({ - "kind":"member", - "base": expr_json(base), - "field": name, - "span":span - }), - Expr::Index { base, index, .. } => json!({ - "kind":"index", - "base": expr_json(base), - "index": expr_json(index), - "span":span - }), - Expr::Call { callee, args, .. } => json!({ - "kind":"call", - "callee": expr_json(callee), - "args": args.iter().map(arg_json).collect::>(), - "span":span - }), - } -} - -fn arg_json(arg: &marqdo_expression::Arg) -> Value { - json!({ - "name": arg.name, - "value": expr_json(&arg.value), - "span": span_json(arg.span), - }) -} - -fn reference_edges(project: &LoadedProject, module_id: &marqdo_ir::ModuleId) -> Vec { - let Some(file) = project.files.get(module_id) else { - return Vec::new(); - }; - let parent = file.path.parent().unwrap_or_else(|| Path::new(".")); - let mut edges = Vec::new(); - file.analysis.document.root.walk(&mut |node| { - let marqdo_markdown::MdKind::Link { url, .. } = &node.kind else { - return; - }; - edges.push(resolve_reference( - project, - module_id, - &file.analysis.units, - parent, - url, - node.span, - )); - }); - edges.sort_by_key(|edge| { - edge.get("span") - .and_then(|span| span.get("start")) - .and_then(Value::as_u64) - .unwrap_or(0) - }); - edges -} - -fn resolve_reference( - project: &LoadedProject, - source_module: &marqdo_ir::ModuleId, - units: &marqdo_frontend::UnitIndex, - parent: &Path, - url: &str, - span: Span, -) -> Value { - if let Some(fragment) = url.strip_prefix('#') { - let unit = units.anchors.get(fragment).or_else(|| { - units - .units - .iter() - .find(|unit| unit.name == fragment) - .map(|unit| &unit.id) - }); - return json!({ - "source": source_module.to_string(), - "url": url, - "span": span_json(span), - "state": if unit.is_some() { "resolved" } else { "unresolved" }, - "target_module": source_module.to_string(), - "target_unit": unit.map(ToString::to_string), - }); - } - if url.starts_with("http://") || url.starts_with("https://") { - return json!({ - "source": source_module.to_string(), - "url": url, - "span": span_json(span), - "state": "external", - "target_module": null, - "target_unit": null, - }); - } - let (path_part, fragment) = match url.split_once('#') { - Some((path, fragment)) => (path, Some(fragment)), - None => (url, None), - }; - let candidate = parent.join(path_part); - let Some(target_module) = project.module_id_for_path(&candidate) else { - return json!({ - "source": source_module.to_string(), - "url": url, - "span": span_json(span), - "state": "unresolved", - "target_module": null, - "target_unit": null, - }); - }; - let target_units = project - .files - .get(&target_module) - .map(|file| &file.analysis.units); - let resolved = match (fragment, target_units) { - (None, _) => Some(None), - (Some(fragment), Some(units)) => units - .anchors - .get(fragment) - .or_else(|| { - units - .units - .iter() - .find(|unit| unit.name == fragment) - .map(|unit| &unit.id) - }) - .map(|unit| Some(unit.to_string())), - (Some(_), None) => None, - }; - let (state, target_unit) = match resolved { - Some(unit) => ("resolved", unit), - None => ("unresolved", None), - }; - json!({ - "source": source_module.to_string(), - "url": url, - "span": span_json(span), - "state": state, - "target_module": target_module.to_string(), - "target_unit": target_unit, - }) -} - -fn calls_json(project: &LoadedProject, module: &Module, function: &Function) -> Vec { - let mut calls = Vec::new(); - collect_calls(project, module, function, &function.body, &mut calls); - calls.sort_by_key(|call| { - call.get("span") - .and_then(|span| span.get("start")) - .and_then(Value::as_u64) - .unwrap_or(0) - }); - calls -} - -fn collect_calls( - project: &LoadedProject, - module: &Module, - function: &Function, - body: &[Stmt], - calls: &mut Vec, -) { - for stmt in body { - match stmt { - Stmt::Assign { target, value, .. } => { - if let PlaceTarget::Index { base, index, .. } = target { - expr_calls(project, module, function, base, calls); - expr_calls(project, module, function, index, calls); - } - expr_calls(project, module, function, value, calls); - } - Stmt::Eval { expr: value, .. } => expr_calls(project, module, function, value, calls), - Stmt::Return { value, .. } => expr_calls(project, module, function, value, calls), - Stmt::Branch { arms, .. } => { - for arm in arms { - expr_calls(project, module, function, &arm.condition, calls); - collect_calls(project, module, function, &arm.body, calls); - } - } - Stmt::Loop { - condition, body, .. - } => { - expr_calls(project, module, function, condition, calls); - collect_calls(project, module, function, body, calls); - } - Stmt::Break { .. } | Stmt::Continue { .. } => {} - } - } -} - -fn expr_calls( - project: &LoadedProject, - module: &Module, - function: &Function, - expr: &Expr, - calls: &mut Vec, -) { - match expr { - Expr::Call { callee, args, span } => { - let (state, target) = resolve_callee(project, module, function, *span); - calls.push(json!({ - "function": function.id.to_string(), - "span": span_json(*span), - "callee": callee_json(callee), - "state": state, - "target": target, - })); - for arg in args { - expr_calls(project, module, function, &arg.value, calls); - } - } - Expr::Unary { operand, .. } => expr_calls(project, module, function, operand, calls), - Expr::Binary { left, right, .. } => { - expr_calls(project, module, function, left, calls); - expr_calls(project, module, function, right, calls); - } - Expr::List(items) => { - for item in items { - expr_calls(project, module, function, item, calls); - } - } - Expr::Record(entries) => { - for entry in entries { - expr_calls(project, module, function, &entry.value, calls); - } - } - Expr::Member { base, .. } => expr_calls(project, module, function, base, calls), - Expr::Index { base, index, .. } => { - expr_calls(project, module, function, base, calls); - expr_calls(project, module, function, index, calls); - } - _ => {} - } -} - -/// Project the authoritative call binding into the Analysis `state`/`target` -/// fields. -/// -/// Analysis is a read-only projection of the same prepared binding the runtime -/// consumes (RFC-EXT-0001 §4/§9): there is no second name-resolution algorithm -/// here. `state` keeps its v1 vocabulary (`function`, `builtin`, `plugin`, -/// `unresolved`); official stdlib aliases such as `打印` therefore appear as -/// `function` targets because that is the implementation that actually runs. -fn resolve_callee( - project: &LoadedProject, - _module: &Module, - function: &Function, - span: Span, -) -> (&'static str, Value) { - let key = marqdo_ir::call_binding::CallSiteKey::new(function.id.clone(), span); - match project.program.call_bindings.get(&key) { - Some(marqdo_ir::call_binding::BoundTarget::Builtin { canonical_name }) => { - ("builtin", json!(canonical_name)) - } - Some(marqdo_ir::call_binding::BoundTarget::Marqdo { function }) => { - ("function", json!(function.to_string())) - } - Some(marqdo_ir::call_binding::BoundTarget::AbiPlugin { export, .. }) => { - ("plugin", json!(export)) - } - Some(marqdo_ir::call_binding::BoundTarget::DynamicValue) | None => { - ("unresolved", Value::Null) - } - } -} - -fn callee_json(callee: &Expr) -> Value { - match callee { - Expr::Ident(ident) => json!({"kind":"ident","name":ident.name}), - Expr::Member { base, name, .. } => { - json!({"kind":"member","base":callee_json(base),"field":name}) - } - other => json!({"kind":"expression","span":span_json(other.span())}), - } -} - -fn span_json(span: Span) -> Value { - json!({"start": span.start, "end": span.end}) -} - -fn unary_name(op: UnaryOp) -> &'static str { - match op { - UnaryOp::Not => "not", - UnaryOp::Neg => "neg", - UnaryOp::Pos => "pos", - } -} - -fn binary_name(op: BinaryOp) -> &'static str { - match op { - BinaryOp::Or => "or", - BinaryOp::And => "and", - BinaryOp::Eq => "eq", - BinaryOp::Ne => "ne", - BinaryOp::Lt => "lt", - BinaryOp::Le => "le", - BinaryOp::Gt => "gt", - BinaryOp::Ge => "ge", - BinaryOp::Add => "add", - BinaryOp::Sub => "sub", - BinaryOp::Mul => "mul", - BinaryOp::Div => "div", - BinaryOp::FloorDiv => "floor_div", - BinaryOp::Mod => "mod", - BinaryOp::Pow => "pow", - } -} - -fn sha256_hex(bytes: &[u8]) -> String { - let mut hasher = Sha256::new(); - hasher.update(bytes); - hex::encode(hasher.finalize()) -} diff --git a/crates/cli/src/analysis/document.rs b/crates/cli/src/analysis/document.rs new file mode 100644 index 0000000..4b355da --- /dev/null +++ b/crates/cli/src/analysis/document.rs @@ -0,0 +1,115 @@ +//! Explicit projector from the canonical Markdown AST to the public document +//! shape (spec/markdown-profile.md §5, spec/analysis.md §3.1). +//! +//! The same projector is used by Analysis and `inspect --ast`; there is no +//! second tree and no serde dump of an internal Rust enum. + +use marqdo_markdown::{MdKind, MdNode}; +use marqdo_span::Span; +use serde_json::{json, Map, Value}; + +/// Project one document root. The root span is normalised to the whole source +/// (including a tolerated BOM); child spans keep their parser coordinates. +pub fn document_json(root: &MdNode, source_len: usize) -> Value { + node_json(root, Some(Span::new(0, source_len))) +} + +fn node_json(node: &MdNode, span_override: Option) -> Value { + let span = span_override.unwrap_or(node.span); + let mut object = Map::new(); + object.insert("kind".to_string(), json!(node.kind.tag())); + object.insert( + "span".to_string(), + json!({"start": span.start, "end": span.end}), + ); + let children: Vec = node + .children + .iter() + .map(|child| node_json(child, None)) + .collect(); + object.insert("children".to_string(), Value::Array(children)); + match &node.kind { + MdKind::Document + | MdKind::BlockQuote + | MdKind::Paragraph + | MdKind::Strong + | MdKind::Emph + | MdKind::Strikethrough + | MdKind::TableCell + | MdKind::ThematicBreak + | MdKind::SoftBreak + | MdKind::LineBreak => {} + MdKind::FrontMatter => { + object.insert( + "literal".to_string(), + Value::String(node.literal.clone().unwrap_or_default()), + ); + } + MdKind::Text | MdKind::MathBlock | MdKind::HtmlBlock | MdKind::HtmlInline => { + object.insert( + "literal".to_string(), + Value::String(node.literal.clone().unwrap_or_default()), + ); + } + MdKind::Code { ticks } => { + object.insert("ticks".to_string(), json!(ticks)); + object.insert( + "literal".to_string(), + Value::String(node.literal.clone().unwrap_or_default()), + ); + } + MdKind::CodeBlock { fenced, info } => { + object.insert("fenced".to_string(), json!(fenced)); + object.insert("info".to_string(), json!(info)); + object.insert( + "literal".to_string(), + Value::String(node.literal.clone().unwrap_or_default()), + ); + } + MdKind::Math { display } => { + object.insert("display".to_string(), json!(display)); + object.insert( + "literal".to_string(), + Value::String(node.literal.clone().unwrap_or_default()), + ); + } + MdKind::Heading { level, setext } => { + object.insert("level".to_string(), json!(level)); + object.insert("setext".to_string(), json!(setext)); + } + MdKind::List { + ordered, + start, + tight, + } => { + object.insert("ordered".to_string(), json!(ordered)); + object.insert("start".to_string(), json!(start)); + object.insert("tight".to_string(), json!(tight)); + } + MdKind::Item { task } => { + object.insert("task".to_string(), json!(task)); + } + MdKind::Link { url, title } | MdKind::Image { url, title } => { + object.insert("url".to_string(), json!(url)); + object.insert("title".to_string(), json!(title)); + } + MdKind::Table { alignments } => { + object.insert("alignments".to_string(), json!(alignments)); + } + MdKind::TableRow { header } => { + object.insert("header".to_string(), json!(header)); + } + MdKind::FootnoteDefinition { .. } | MdKind::FootnoteReference { .. } => { + // The frozen profile disables footnotes; the semantic validator + // rejects them if a future parser change ever emits one. + object.insert("tag".to_string(), json!(node.kind.tag())); + } + MdKind::Other { tag } => { + object.insert("tag".to_string(), json!(tag)); + if let Some(literal) = &node.literal { + object.insert("literal".to_string(), Value::String(literal.clone())); + } + } + } + Value::Object(object) +} diff --git a/crates/cli/src/analysis/mod.rs b/crates/cli/src/analysis/mod.rs new file mode 100644 index 0000000..4640c94 --- /dev/null +++ b/crates/cli/src/analysis/mod.rs @@ -0,0 +1,1374 @@ +//! Public Analysis projection (spec/analysis.md, ADR-0069). +//! +//! One typed projection is built from the same `project_prepare::prepare` +//! facts consumed by `check`, `inspect`, `run` and `call`; the canonical +//! encoder is shared by the file writer and the Observation digest. The +//! exporter is read-only and never executes a document, opens an extension or +//! reads a link target outside the explicitly prepared catalog. + +mod document; +mod model; + +use std::collections::{BTreeMap, BTreeSet}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use marqdo_expression::{BinaryOp, Expr, UnaryOp}; +use marqdo_ir::{Function, Module, ModuleId, PlaceTarget, Resource, SignatureKind, Stmt, UnitKind}; +use marqdo_span::Span; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; + +use crate::document_refs::{self, ReferenceMode, TargetKind}; +use crate::loader::{FileDiagnostic, LoadedProject}; +use crate::project_prepare::PreparedProgram; + +pub use model::*; + +/// Schema name and version. +pub const SCHEMA: &str = "marqdo.analysis"; +/// Current public revision. +pub const SCHEMA_VERSION: u32 = 3; +/// Markdown profile recorded by the producer. +const MARKDOWN_PROFILE: &str = "marqdo.md.v1"; + +/// Projection shared with `inspect --ast`. +pub fn document_projection(root: &marqdo_markdown::MdNode, source_len: usize) -> Value { + document::document_json(root, source_len) +} + +/// Projection shared with `inspect --refs`. +pub fn reference_projection(reference: document_refs::Reference) -> ReferenceRecord { + reference_record(reference) +} + +/// Projection shared with `inspect --units`. +pub fn units_projection(index: &marqdo_frontend::UnitIndex, source_len: usize) -> Vec { + units_json(index, source_len) +} + +/// Build and semantically validate the deterministic public projection. +pub fn build(prepared: &PreparedProgram) -> Result { + let loaded = &prepared.loaded; + let references = document_refs::references_for_project(loaded, ReferenceMode::LoadedOnly); + let mut modules = Vec::with_capacity(loaded.files.len()); + for (module_id, file) in &loaded.files { + let source = &file.source; + let unit_index = &file.analysis.units; + let module = &file.analysis.module; + let references = references + .by_module + .get(module_id) + .cloned() + .unwrap_or_default() + .into_iter() + .map(reference_record) + .collect(); + modules.push(ModuleAnalysis { + id: module_id.to_string(), + package_instance_id: module_id.instance.clone(), + relative_path: module_id.relative_path.clone(), + source_digest: sha256_hex(source.as_bytes()), + source: source.clone(), + document: document::document_json(&file.analysis.document.root, source.len()), + units: units_json(unit_index, source.len()), + anchors: anchors_json(unit_index), + functions: module.functions.iter().map(function_record).collect(), + imports: module + .imports + .iter() + .map(|import| ImportRecord { + alias: import.alias.clone(), + target: import.target.clone(), + span: import.span.into(), + resolved: loaded + .program + .resolve_import(module_id, &import.alias) + .map(ToString::to_string), + }) + .collect(), + references, + calls: calls_json(loaded, module), + resources: resources_json(module_id, module), + }); + } + modules.sort_by(|left, right| left.id.cmp(&right.id)); + + let analysis = Analysis { + schema: SCHEMA, + schema_version: SCHEMA_VERSION, + producer: Producer { + name: "marqdo", + version: env!("CARGO_PKG_VERSION"), + markdown_profile: MARKDOWN_PROFILE, + }, + project: Project { + root_id: loaded.identity.root_id(), + identity_kind: loaded.identity.kind(), + entry_module_id: loaded.entry.to_string(), + lock_digest: loaded.lock_digest.clone(), + manifest_digest: loaded.manifest_digest.clone(), + stdlib: loaded.stdlib.as_ref().map(|stdlib| Stdlib { + version: stdlib.version.clone(), + digest: stdlib.digest.clone(), + instance_id: stdlib.instance_id.clone(), + }), + extensions: extensions_json(prepared), + }, + modules, + diagnostics: diagnostics_json(&loaded.diagnostics), + }; + validate(&analysis)?; + Ok(analysis) +} + +/// Encode exactly the bytes written by `check --emit`. +pub fn encode(prepared: &PreparedProgram) -> Result, String> { + let analysis = build(prepared)?; + serde_json::to_vec_pretty(&analysis).map_err(|error| format!("cannot encode analysis: {error}")) +} + +/// SHA-256 of the exact emitted Analysis bytes. +pub fn digest(prepared: &PreparedProgram) -> Result { + encode(prepared).map(|bytes| format!("sha256:{}", sha256_hex(&bytes))) +} + +/// Atomically write the projection through an owner-only temporary file. +/// +/// An error never leaves a partial artifact and never touches an input source. +pub fn write(prepared: &PreparedProgram, path: &Path) -> Result<(), String> { + let bytes = encode(prepared)?; + let parent = output_parent(path); + std::fs::create_dir_all(&parent) + .map_err(|error| format!("cannot create `{}`: {error}", parent.display()))?; + ensure_safe_output(prepared, path)?; + let temporary = create_temporary(&parent, path)?; + let write_result = (|| -> Result<(), String> { + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&temporary) + .map_err(|error| format!("cannot create `{}`: {error}", temporary.display()))?; + restrict_permissions(&file)?; + file.write_all(&bytes) + .map_err(|error| format!("cannot write `{}`: {error}", temporary.display()))?; + file.sync_all() + .map_err(|error| format!("cannot flush `{}`: {error}", temporary.display()))?; + drop(file); + std::fs::rename(&temporary, path) + .map_err(|error| format!("cannot publish `{}`: {error}", path.display())) + })(); + if write_result.is_err() { + let _ = std::fs::remove_file(&temporary); + } + write_result +} + +/// Remove a previous success artifact after a failed check. +/// +/// The same output guards apply: an input source, manifest, lock file, a +/// directory or a symlink is never removed. +pub fn discard(prepared: &PreparedProgram, path: &Path) -> Result<(), String> { + ensure_safe_output(prepared, path)?; + remove_if_present(path) +} + +/// Remove a stale output when preparation itself failed (no PreparedProgram). +/// +/// The entry source is explicitly protected even when it is the requested +/// output path, and a directory/symlink destination is refused. +pub fn discard_without_prepare(entry: Option<&Path>, path: &Path) -> Result<(), String> { + let metadata = match std::fs::symlink_metadata(path) { + Ok(metadata) => Some(metadata), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(format!("cannot inspect `{}`: {error}", path.display())), + }; + if let Some(metadata) = &metadata { + if metadata.file_type().is_symlink() { + return Err(format!( + "refusing to remove `{}`: it is a symbolic link", + path.display() + )); + } + if metadata.is_dir() { + return Err(format!( + "refusing to remove `{}`: it is a directory", + path.display() + )); + } + } + if let Some(entry) = entry { + if let (Ok(entry), Ok(target)) = (entry.canonicalize(), path.canonicalize()) { + if entry == target { + return Err(format!( + "refusing to remove `{}`: it is the input document", + path.display() + )); + } + } + } + remove_if_present(path) +} + +fn remove_if_present(path: &Path) -> Result<(), String> { + match std::fs::remove_file(path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(format!("cannot remove `{}`: {error}", path.display())), + } +} + +fn output_parent(path: &Path) -> PathBuf { + path.parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")) + .to_path_buf() +} + +static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0); + +fn create_temporary(parent: &Path, path: &Path) -> Result { + let name = path + .file_name() + .map(|name| name.to_string_lossy().to_string()) + .unwrap_or_else(|| "analysis.json".to_string()); + for _ in 0..64 { + let nonce = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed); + let candidate = parent.join(format!(".{name}.tmp-{}-{nonce}", std::process::id())); + match std::fs::symlink_metadata(&candidate) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(candidate), + Ok(_) => continue, + Err(error) => return Err(format!("cannot inspect temporary path: {error}")), + } + } + Err("cannot create a unique temporary file for the Analysis output".to_string()) +} + +#[cfg(unix)] +fn restrict_permissions(file: &std::fs::File) -> Result<(), String> { + use std::os::unix::fs::PermissionsExt; + file.set_permissions(std::fs::Permissions::from_mode(0o600)) + .map_err(|error| format!("cannot restrict Analysis permissions: {error}")) +} + +#[cfg(not(unix))] +fn restrict_permissions(_file: &std::fs::File) -> Result<(), String> { + Ok(()) +} + +/// Refuse to overwrite a loaded source, manifest, lock file, a hard link to +/// one, a directory or a symlink at the destination. +fn ensure_safe_output(prepared: &PreparedProgram, path: &Path) -> Result<(), String> { + let loaded = &prepared.loaded; + let metadata = match std::fs::symlink_metadata(path) { + Ok(metadata) => Some(metadata), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(format!("cannot inspect `{}`: {error}", path.display())), + }; + if let Some(metadata) = &metadata { + if metadata.file_type().is_symlink() { + return Err(format!( + "refusing to write `{}`: the destination is a symbolic link", + path.display() + )); + } + if metadata.is_dir() { + return Err(format!( + "refusing to write `{}`: the destination is a directory", + path.display() + )); + } + } + let parent = output_parent(path); + let parent = parent.canonicalize().unwrap_or_else(|_| parent.clone()); + let target = parent.join( + path.file_name() + .ok_or_else(|| format!("`{}` has no file name", path.display()))?, + ); + let mut protected: Vec = loaded + .files + .values() + .map(|file| file.path.clone()) + .collect(); + protected.push(loaded.root.join(marqdo_package::MANIFEST_FILE)); + protected.push(loaded.root.join(marqdo_package::LOCK_FILE)); + for source in protected { + let canonical = source.canonicalize().unwrap_or_else(|_| source.clone()); + if canonical == target { + return Err(format!( + "refusing to write `{}`: it is an input source, manifest or lock file", + path.display() + )); + } + if let Some(existing) = &metadata { + if is_hard_link_to(existing, &source) { + return Err(format!( + "refusing to write `{}`: it is a hard link to an input source", + path.display() + )); + } + } + } + Ok(()) +} + +#[cfg(unix)] +fn is_hard_link_to(metadata: &std::fs::Metadata, source: &Path) -> bool { + use std::os::unix::fs::MetadataExt; + let Ok(source_metadata) = std::fs::metadata(source) else { + return false; + }; + metadata.dev() == source_metadata.dev() && metadata.ino() == source_metadata.ino() +} + +#[cfg(not(unix))] +fn is_hard_link_to(_metadata: &std::fs::Metadata, _source: &Path) -> bool { + false +} + +fn units_json(index: &marqdo_frontend::UnitIndex, source_len: usize) -> Vec { + let mut units = Vec::with_capacity(index.units.len()); + for unit in &index.units { + let heading = index + .headings + .iter() + .find(|heading| heading.path == unit.id.path); + let (mode, mode_origin, mode_source, heading_span, span) = match heading { + Some(heading) => ( + mode_name(heading.mode), + heading.mode_origin.as_str(), + heading.mode_source_unit_id.to_string(), + Some(heading.span.into()), + heading.full_span.into(), + ), + None => ( + "knowledge", + "default", + unit.id.to_string(), + None, + Span::new(0, source_len).into(), + ), + }; + units.push(UnitRecord { + id: unit.id.to_string(), + path: unit.id.path.clone(), + parent_id: heading.map(|heading| heading.parent_id.to_string()), + kind: unit_kind_name(unit.kind), + name: unit.name.clone(), + level: unit.level, + mode, + mode_origin, + mode_source_unit_id: mode_source, + heading_span, + span, + function: unit.function.as_ref().map(ToString::to_string), + }); + } + units +} + +fn anchors_json(index: &marqdo_frontend::UnitIndex) -> Vec { + index + .anchors + .iter() + .map(|(anchor, unit)| AnchorRecord { + anchor: anchor.clone(), + unit_id: unit.to_string(), + }) + .collect() +} + +fn unit_kind_name(kind: UnitKind) -> &'static str { + match kind { + UnitKind::Root => "root", + UnitKind::Namespace => "namespace", + UnitKind::Function => "function", + UnitKind::Knowledge => "knowledge", + UnitKind::Section => "section", + } +} + +fn mode_name(mode: marqdo_frontend::units::SemanticMode) -> &'static str { + match mode { + marqdo_frontend::units::SemanticMode::Knowledge => "knowledge", + marqdo_frontend::units::SemanticMode::Exec => "exec", + } +} + +fn reference_record(reference: document_refs::Reference) -> ReferenceRecord { + ReferenceRecord { + source: reference.source.to_string(), + source_unit: reference.source_unit.to_string(), + url: reference.url, + span: reference.span.into(), + state: reference.state.as_str(), + target_kind: reference.target_kind.map(TargetKind::as_str), + target_module: reference.target_module.map(|module| module.to_string()), + target_unit: reference.target_unit.map(|unit| unit.to_string()), + candidate_package_instance_id: reference.candidate_package_instance_id, + candidate_path: reference.candidate_path, + fragment: reference.fragment, + candidates: reference + .candidates + .into_iter() + .map(|unit| unit.to_string()) + .collect(), + } +} + +fn function_record(function: &Function) -> FunctionRecord { + FunctionRecord { + id: function.id.to_string(), + unit_id: function.unit.to_string(), + local_name: function.local_name.clone(), + namespace: function.namespace.clone(), + span: function.span.into(), + heading_span: function.heading_span.into(), + signature: SignatureRecord { + kind: match function.signature { + SignatureKind::Explicit => "explicit", + SignatureKind::Inferred => "inferred", + }, + params: function + .params + .iter() + .map(|param| ParamRecord { + name: param.name.clone(), + required: param.default.is_none(), + r#type: param.type_annotation.clone(), + default: param.default.as_ref().map(expr_json), + span: param.span.into(), + }) + .collect(), + }, + effects: vec!["unknown"], + body: function.body.iter().map(stmt_json).collect(), + } +} + +fn resources_json(module_id: &ModuleId, module: &Module) -> Vec { + let mut formula_index = 0usize; + let mut code_index = 0usize; + module + .resources + .iter() + .map(|resource| match resource { + Resource::Formula { + unit, + latex, + display, + span, + } => { + formula_index += 1; + ResourceRecord { + id: format!("{module_id}#resource:formula-{formula_index}"), + module_id: module_id.to_string(), + unit_id: unit.to_string(), + kind: "formula", + span: (*span).into(), + content_digest: sha256_hex(latex.as_bytes()), + language: None, + display: Some(*display), + } + } + Resource::Code { + unit, + language, + source: _, + content_hash, + span, + } => { + code_index += 1; + ResourceRecord { + id: format!("{module_id}#resource:code-{code_index}"), + module_id: module_id.to_string(), + unit_id: unit.to_string(), + kind: "code", + span: (*span).into(), + content_digest: content_hash.clone(), + language: Some(language.clone()), + display: None, + } + } + }) + .collect() +} + +fn diagnostics_json(diagnostics: &[FileDiagnostic]) -> Vec { + diagnostics + .iter() + .map(|item| { + let (line, column) = item + .line_col() + .map(|(line, column)| (Some(line), Some(column))) + .unwrap_or((None, None)); + DiagnosticRecord { + module: item.module_id.to_string(), + relative_path: item.module_id.relative_path.clone(), + span: item.diagnostic.span.map(Into::into), + line, + column, + severity: if item.diagnostic.is_error() { + "error" + } else { + "warning" + }, + code: item.diagnostic.code.clone(), + message: item.diagnostic.message.clone(), + hints: item.diagnostic.hints.clone(), + } + }) + .collect() +} + +fn extensions_json(prepared: &PreparedProgram) -> Vec { + let mut extensions: Vec = prepared + .extension_identities + .iter() + .map(|identity| Extension { + kind: identity.kind.as_str(), + name: identity.name.clone(), + version: identity.version.clone(), + logical_owner: identity.logical_owner.clone(), + source: identity.source.clone(), + manifest_digest: wire_digest(&identity.manifest_digest), + artifact_digest: wire_digest(&identity.artifact_digest), + selected_target: identity.selected_target.clone(), + }) + .collect(); + for plugin in &prepared.plugins.plugins { + extensions.push(Extension { + kind: "plugin", + name: plugin.package.clone(), + version: plugin.version.clone(), + logical_owner: "cli".to_string(), + source: "--plugin".to_string(), + manifest_digest: wire_digest(&plugin.manifest_sha256), + artifact_digest: wire_digest(&plugin.artifact_sha256), + selected_target: plugin.artifact_target.clone(), + }); + } + extensions.sort_by(|left, right| { + ( + left.kind, + &left.name, + &left.logical_owner, + &left.manifest_digest, + ) + .cmp(&( + right.kind, + &right.name, + &right.logical_owner, + &right.manifest_digest, + )) + }); + extensions.dedup(); + extensions +} + +fn wire_digest(raw: &str) -> String { + if raw.starts_with("sha256:") { + raw.to_string() + } else { + format!("sha256:{raw}") + } +} + +fn place_json(place: &PlaceTarget) -> Value { + match place { + PlaceTarget::Local { name, .. } => Value::String(name.clone()), + PlaceTarget::Index { base, index, span } => json!({ + "kind": "index", + "base": expr_json(base), + "index": expr_json(index), + "span": span_json(*span), + }), + } +} + +fn stmt_json(stmt: &Stmt) -> Value { + match stmt { + Stmt::Assign { + target, + value, + span, + .. + } => json!({ + "kind": "assign", + "target": place_json(target), + "value": expr_json(value), + "span": span_json(*span), + }), + Stmt::Eval { expr, span } => json!({ + "kind": "expression", + "value": expr_json(expr), + "span": span_json(*span), + }), + Stmt::Branch { arms, span } => json!({ + "kind": "branch", + "arms": arms.iter().map(|arm| json!({ + "condition": expr_json(&arm.condition), + "condition_span": span_json(arm.condition_span), + "body": arm.body.iter().map(stmt_json).collect::>(), + "span": span_json(arm.span), + })).collect::>(), + "span": span_json(*span), + }), + Stmt::Loop { + condition, + condition_span, + body, + span, + } => json!({ + "kind": "loop", + "condition": expr_json(condition), + "condition_span": span_json(*condition_span), + "body": body.iter().map(stmt_json).collect::>(), + "span": span_json(*span), + }), + Stmt::Break { span } => json!({"kind": "break", "span": span_json(*span)}), + Stmt::Continue { span } => json!({"kind": "continue", "span": span_json(*span)}), + Stmt::Return { value, span } => json!({ + "kind": "return", + "value": expr_json(value), + "span": span_json(*span), + }), + } +} + +fn expr_json(expr: &Expr) -> Value { + let span = span_json(expr.span()); + match expr { + Expr::Int(value) => { + json!({"kind":"literal","type":"int","value":value.to_string(),"span":span}) + } + Expr::Float(value) => json!({"kind":"literal","type":"float","value":value,"span":span}), + Expr::Text(value) => json!({"kind":"literal","type":"text","value":value,"span":span}), + Expr::Bool(value) => json!({"kind":"literal","type":"bool","value":value,"span":span}), + Expr::None => json!({"kind":"literal","type":"none","span":span}), + Expr::Ident(ident) => { + json!({"kind":"variable","name":ident.name,"span":span_json(ident.span)}) + } + Expr::List(items) => { + json!({"kind":"list","items":items.iter().map(expr_json).collect::>(),"span":span}) + } + Expr::Record(entries) => json!({ + "kind":"record", + "entries": entries.iter().map(|entry| json!({ + "key": entry.key, + "key_span": span_json(entry.key_span), + "value": expr_json(&entry.value), + })).collect::>(), + "span":span + }), + Expr::Unary { op, operand, .. } => json!({ + "kind":"unary", + "op": unary_name(*op), + "operand": expr_json(operand), + "span":span + }), + Expr::Binary { + op, left, right, .. + } => json!({ + "kind":"binary", + "op": binary_name(*op), + "left": expr_json(left), + "right": expr_json(right), + "span":span + }), + Expr::Member { base, name, .. } => json!({ + "kind":"member", + "base": expr_json(base), + "field": name, + "span":span + }), + Expr::Index { base, index, .. } => json!({ + "kind":"index", + "base": expr_json(base), + "index": expr_json(index), + "span":span + }), + Expr::Call { callee, args, .. } => json!({ + "kind":"call", + "callee": expr_json(callee), + "args": args.iter().map(arg_json).collect::>(), + "span":span + }), + } +} + +fn arg_json(arg: &marqdo_expression::Arg) -> Value { + json!({ + "name": arg.name, + "value": expr_json(&arg.value), + "span": span_json(arg.span), + }) +} + +fn calls_json(project: &LoadedProject, module: &Module) -> Vec { + let mut calls = Vec::new(); + for function in &module.functions { + collect_calls(project, function, &function.body, &mut calls); + } + calls.sort_by_key(|call| call.span.start); + calls +} + +fn collect_calls( + project: &LoadedProject, + function: &Function, + body: &[Stmt], + calls: &mut Vec, +) { + for stmt in body { + match stmt { + Stmt::Assign { target, value, .. } => { + if let PlaceTarget::Index { base, index, .. } = target { + expr_calls(project, function, base, calls); + expr_calls(project, function, index, calls); + } + expr_calls(project, function, value, calls); + } + Stmt::Eval { expr: value, .. } => expr_calls(project, function, value, calls), + Stmt::Return { value, .. } => expr_calls(project, function, value, calls), + Stmt::Branch { arms, .. } => { + for arm in arms { + expr_calls(project, function, &arm.condition, calls); + collect_calls(project, function, &arm.body, calls); + } + } + Stmt::Loop { + condition, body, .. + } => { + expr_calls(project, function, condition, calls); + collect_calls(project, function, body, calls); + } + Stmt::Break { .. } | Stmt::Continue { .. } => {} + } + } +} + +fn expr_calls( + project: &LoadedProject, + function: &Function, + expr: &Expr, + calls: &mut Vec, +) { + match expr { + Expr::Call { callee, args, span } => { + let key = marqdo_ir::call_binding::CallSiteKey::new(function.id.clone(), *span); + let binding = project.program.call_bindings.get(&key); + let (state, target, target_kind, target_owner, reason) = match binding { + Some(marqdo_ir::call_binding::BoundTarget::Builtin { canonical_name }) => ( + "builtin", + Some(canonical_name.clone()), + Some("builtin"), + None, + None, + ), + Some(marqdo_ir::call_binding::BoundTarget::Marqdo { function }) => ( + "function", + Some(function.to_string()), + Some("function"), + None, + None, + ), + Some(marqdo_ir::call_binding::BoundTarget::AbiPlugin { + package, + export, + digest, + .. + }) => ( + "plugin", + Some(export.clone()), + Some("plugin"), + Some(TargetOwner { + kind: "plugin", + package: package.clone(), + digest: wire_digest(digest), + }), + None, + ), + Some(marqdo_ir::call_binding::BoundTarget::DynamicValue) => { + ("unresolved", None, None, None, Some("dynamic")) + } + None => ("unresolved", None, None, None, Some("unbound")), + }; + calls.push(CallRecord { + function: function.id.to_string(), + span: (*span).into(), + callee: callee_json(callee), + state, + target, + target_kind, + target_owner, + reason, + }); + for arg in args { + expr_calls(project, function, &arg.value, calls); + } + } + Expr::Unary { operand, .. } => expr_calls(project, function, operand, calls), + Expr::Binary { left, right, .. } => { + expr_calls(project, function, left, calls); + expr_calls(project, function, right, calls); + } + Expr::List(items) => { + for item in items { + expr_calls(project, function, item, calls); + } + } + Expr::Record(entries) => { + for entry in entries { + expr_calls(project, function, &entry.value, calls); + } + } + Expr::Member { base, .. } => expr_calls(project, function, base, calls), + Expr::Index { base, index, .. } => { + expr_calls(project, function, base, calls); + expr_calls(project, function, index, calls); + } + _ => {} + } +} + +fn callee_json(callee: &Expr) -> Value { + match callee { + Expr::Ident(ident) => json!({"kind":"ident","name":ident.name}), + Expr::Member { base, name, .. } => { + json!({"kind":"member","base":callee_json(base),"field":name}) + } + other => json!({"kind":"expression","span":span_json(other.span())}), + } +} + +fn span_json(span: Span) -> Value { + json!({"start": span.start, "end": span.end}) +} + +fn unary_name(op: UnaryOp) -> &'static str { + match op { + UnaryOp::Not => "not", + UnaryOp::Neg => "neg", + UnaryOp::Pos => "pos", + } +} + +fn binary_name(op: BinaryOp) -> &'static str { + match op { + BinaryOp::Or => "or", + BinaryOp::And => "and", + BinaryOp::Eq => "eq", + BinaryOp::Ne => "ne", + BinaryOp::Lt => "lt", + BinaryOp::Le => "le", + BinaryOp::Gt => "gt", + BinaryOp::Ge => "ge", + BinaryOp::Add => "add", + BinaryOp::Sub => "sub", + BinaryOp::Mul => "mul", + BinaryOp::Div => "div", + BinaryOp::FloorDiv => "floor_div", + BinaryOp::Mod => "mod", + BinaryOp::Pow => "pow", + } +} + +fn sha256_hex(bytes: &[u8]) -> String { + let mut hasher = Sha256::new(); + hasher.update(bytes); + hex::encode(hasher.finalize()) +} + +/// Check the cross-record invariants that JSON Schema cannot express. +fn validate(analysis: &Analysis) -> Result<(), String> { + if analysis.schema != SCHEMA || analysis.schema_version != SCHEMA_VERSION { + return Err("analysis schema/revision mismatch".to_string()); + } + if analysis.producer.name != "marqdo" || analysis.producer.markdown_profile != MARKDOWN_PROFILE + { + return Err("analysis producer identity mismatch".to_string()); + } + if !analysis.project.lock_digest.is_empty() + && !analysis.project.lock_digest.starts_with("sha256:") + { + return Err("project.lock_digest must be empty or sha256:".to_string()); + } + if !analysis.project.manifest_digest.is_empty() + && !analysis.project.manifest_digest.starts_with("sha256:") + { + return Err("project.manifest_digest must be empty or sha256:".to_string()); + } + let mut module_ids = BTreeSet::new(); + let mut sources: BTreeMap<&str, &str> = BTreeMap::new(); + let mut module_units: BTreeMap<&str, BTreeSet> = BTreeMap::new(); + let mut function_ids: BTreeSet = BTreeSet::new(); + let mut previous = None; + for module in &analysis.modules { + if let Some(previous) = previous { + if previous >= module.id.as_str() { + return Err(format!( + "modules are not strictly sorted by id: `{previous}` then `{}`", + module.id + )); + } + } + previous = Some(module.id.as_str()); + if !module_ids.insert(module.id.as_str()) { + return Err(format!("duplicate module id `{}`", module.id)); + } + if module.source_digest != sha256_hex(module.source.as_bytes()) { + return Err(format!("source_digest mismatch in `{}`", module.id)); + } + sources.insert(module.id.as_str(), module.source.as_str()); + let mut units = BTreeSet::new(); + for unit in &module.units { + if !units.insert(unit.id.clone()) { + return Err(format!("duplicate unit id `{}`", unit.id)); + } + } + module_units.insert(module.id.as_str(), units); + for function in &module.functions { + if !function_ids.insert(function.id.clone()) { + return Err(format!("duplicate function id `{}`", function.id)); + } + } + } + if !module_ids.contains(analysis.project.entry_module_id.as_str()) { + return Err("project.entry_module_id does not name a module".to_string()); + } + for module in &analysis.modules { + let source = module.source.as_str(); + validate_span( + module.document.get("span"), + source.len(), + source, + &format!("{}.document", module.id), + )?; + validate_ast(&module.document, source.len(), source, &module.id)?; + if module.document.get("kind").and_then(Value::as_str) != Some("document") { + return Err(format!("{} document root has wrong kind", module.id)); + } + let root_span = module.document.get("span").cloned().unwrap_or_default(); + if root_span.get("start").and_then(Value::as_u64) != Some(0) + || root_span.get("end").and_then(Value::as_u64) != Some(source.len() as u64) + { + return Err(format!( + "{} document root does not cover the source", + module.id + )); + } + + let mut unit_by_id: BTreeMap<&str, &UnitRecord> = BTreeMap::new(); + for unit in &module.units { + unit_by_id.insert(unit.id.as_str(), unit); + if unit.id != unit_id_string(&module.id, &unit.path) { + return Err(format!("unit id/path mismatch in `{}`", module.id)); + } + validate_span( + Some(&json!({"start": unit.span.start, "end": unit.span.end})), + source.len(), + source, + &format!("{}.units.{}", module.id, unit.id), + )?; + if let Some(heading) = &unit.heading_span { + validate_span( + Some(&json!({"start": heading.start, "end": heading.end})), + source.len(), + source, + &format!("{}.heading_span", unit.id), + )?; + } + if unit.level == 0 { + if unit.parent_id.is_some() || !unit.path.is_empty() { + return Err(format!("root unit `{}` has a parent or path", unit.id)); + } + } else { + let parent = unit + .parent_id + .as_deref() + .and_then(|parent| unit_by_id.get(parent)) + .ok_or_else(|| format!("unit `{}` has a missing parent", unit.id))?; + let mut expected = parent.path.clone(); + expected.push(unit.name.clone()); + if expected != unit.path { + return Err(format!("unit `{}` path does not match its parent", unit.id)); + } + if unit.span.start > parent.span.end || unit.span.end < parent.span.start { + return Err(format!("unit `{}` escapes its parent span", unit.id)); + } + } + } + // Mode source must be the unit itself or an ancestor. + for unit in &module.units { + let mut current = Some(unit); + let mut found = false; + while let Some(candidate) = current { + if candidate.id == unit.mode_source_unit_id { + found = true; + break; + } + current = candidate + .parent_id + .as_deref() + .and_then(|parent| unit_by_id.get(parent).copied()); + } + if !found { + return Err(format!( + "unit `{}` mode_source_unit_id is not an ancestor", + unit.id + )); + } + } + let mut previous_anchor: Option<&str> = None; + for anchor in &module.anchors { + if let Some(previous) = previous_anchor { + if previous >= anchor.anchor.as_str() { + return Err(format!("anchors are not sorted in `{}`", module.id)); + } + } + previous_anchor = Some(&anchor.anchor); + if !unit_by_id.contains_key(anchor.unit_id.as_str()) { + return Err(format!("anchor `{}` names a missing unit", anchor.anchor)); + } + } + let mut unit_function: BTreeMap = BTreeMap::new(); + for unit in &module.units { + if let Some(function) = &unit.function { + if let Some(existing) = unit_function.insert(unit.id.clone(), function.clone()) { + if &existing != function { + return Err(format!("unit `{}` has two functions", unit.id)); + } + } + if unit.function.as_deref().is_some_and(|function| { + !module + .functions + .iter() + .any(|candidate| candidate.id == function) + }) { + return Err(format!("unit `{}` names a missing function", unit.id)); + } + } + } + for function in &module.functions { + if !unit_by_id.contains_key(function.unit_id.as_str()) { + return Err(format!("function `{}` names a missing unit", function.id)); + } + let unit = unit_by_id[function.unit_id.as_str()]; + if unit.kind != "function" { + return Err(format!( + "function `{}` is not attached to an Exec H2 unit", + function.id + )); + } + if unit.function.as_deref() != Some(function.id.as_str()) { + return Err(format!("function/unit link mismatch for `{}`", function.id)); + } + validate_span( + Some(&json!({"start": function.span.start, "end": function.span.end})), + source.len(), + source, + &format!("{}.span", function.id), + )?; + validate_span( + Some( + &json!({"start": function.heading_span.start, "end": function.heading_span.end}), + ), + source.len(), + source, + &format!("{}.heading_span", function.id), + )?; + for statement in &function.body { + validate_json_spans(statement, source.len(), source, &function.id)?; + } + } + for import in &module.imports { + validate_span( + Some(&json!({"start": import.span.start, "end": import.span.end})), + source.len(), + source, + &format!("{}.import", module.id), + )?; + if let Some(resolved) = &import.resolved { + if !module_ids.contains(resolved.as_str()) { + return Err(format!( + "import `{}` resolves to a module outside the artifact", + import.target + )); + } + } + } + for reference in &module.references { + validate_span( + Some(&json!({"start": reference.span.start, "end": reference.span.end})), + source.len(), + source, + &format!("{}.reference", module.id), + )?; + if !unit_by_id.contains_key(reference.source_unit.as_str()) { + return Err(format!( + "reference `{}` names a missing source unit", + reference.url + )); + } + validate_reference(reference, &module_ids, &module_units)?; + } + let mut call_spans = BTreeSet::new(); + for call in &module.calls { + validate_span( + Some(&json!({"start": call.span.start, "end": call.span.end})), + source.len(), + source, + &format!("{}.call", module.id), + )?; + if !call_spans.insert((call.function.clone(), call.span.start, call.span.end)) { + return Err(format!("duplicate call record at {}", call.span.start)); + } + if !function_ids.contains(&call.function) { + return Err(format!("call names a missing function `{}`", call.function)); + } + match call.state { + "function" if call.target_kind == Some("function") => { + if let Some(target) = &call.target { + if !function_ids.contains(target) { + return Err(format!("call target `{target}` does not exist")); + } + } else { + return Err("resolved function call has no target".to_string()); + } + } + "builtin" if call.target_kind == Some("builtin") => {} + "plugin" => { + if call.target_kind != Some("plugin") || call.target_owner.is_none() { + return Err("plugin call lacks its static owner".to_string()); + } + } + "unresolved" => { + if call.target.is_some() || call.target_kind.is_some() { + return Err("unresolved call carries a target".to_string()); + } + } + _ => return Err(format!("invalid call state `{}`", call.state)), + } + } + let mut resource_ids = BTreeSet::new(); + for resource in &module.resources { + if !resource_ids.insert(&resource.id) { + return Err(format!("duplicate resource id `{}`", resource.id)); + } + if resource.module_id != module.id { + return Err("resource module mismatch".to_string()); + } + if !unit_by_id.contains_key(resource.unit_id.as_str()) { + return Err(format!("resource `{}` names a missing unit", resource.id)); + } + validate_span( + Some(&json!({"start": resource.span.start, "end": resource.span.end})), + source.len(), + source, + &resource.id, + )?; + if resource.content_digest.len() != 64 { + return Err(format!("resource `{}` has a bad digest", resource.id)); + } + match resource.kind { + "formula" if resource.display.is_none() => { + return Err("formula resource has no display flag".to_string()); + } + "code" if resource.display.is_some() => { + return Err("code resource has a display flag".to_string()); + } + "formula" | "code" => {} + _ => return Err("unknown resource kind".to_string()), + } + } + } + let module_ids: BTreeSet<&str> = analysis + .modules + .iter() + .map(|module| module.id.as_str()) + .collect(); + for diagnostic in &analysis.diagnostics { + if !module_ids.contains(diagnostic.module.as_str()) { + return Err(format!( + "diagnostic names a missing module `{}`", + diagnostic.module + )); + } + if let Some(span) = &diagnostic.span { + if span.start > span.end { + return Err("diagnostic span is reversed".to_string()); + } + } + if diagnostic.severity == "error" { + return Err(format!( + "successful Analysis contains error diagnostic `{}`", + diagnostic.code + )); + } + } + Ok(()) +} + +fn unit_id_string(module_id: &str, path: &[String]) -> String { + let mut out = format!("{module_id}#"); + for (index, segment) in path.iter().enumerate() { + if index > 0 { + out.push('/'); + } + out.push_str(&marqdo_ir::escape_identity_segment(segment)); + } + out +} + +fn validate_reference( + reference: &ReferenceRecord, + modules: &BTreeSet<&str>, + module_units: &BTreeMap<&str, BTreeSet>, +) -> Result<(), String> { + match reference.state { + "resolved" => match reference.target_kind { + Some("module") => { + let target = reference + .target_module + .as_deref() + .ok_or_else(|| "resolved module reference has no target module".to_string())?; + if !modules.contains(target) { + return Err(format!( + "resolved reference names missing module `{target}`" + )); + } + if let Some(unit) = &reference.target_unit { + let units = module_units + .get(target) + .ok_or_else(|| "missing target unit table".to_string())?; + if !units.contains(unit) { + return Err(format!("resolved reference names missing unit `{unit}`")); + } + } + } + Some("file") => { + if reference.target_module.is_some() || reference.target_unit.is_some() { + return Err("file reference must not name a module/unit".to_string()); + } + } + _ => return Err("resolved reference has no target kind".to_string()), + }, + "not_loaded" | "external" | "outside_scope" | "invalid" => { + if reference.target_module.is_some() + || reference.target_unit.is_some() + || reference.target_kind.is_some() + { + return Err(format!( + "reference state `{}` carries a target", + reference.state + )); + } + } + "missing" => { + if reference.target_unit.is_some() { + return Err("missing reference carries a target unit".to_string()); + } + } + "ambiguous" => { + if reference.target_unit.is_some() || reference.candidates.len() < 2 { + return Err("ambiguous reference must carry several candidates".to_string()); + } + } + other => return Err(format!("unknown reference state `{other}`")), + } + Ok(()) +} + +fn validate_span( + span: Option<&Value>, + source_len: usize, + source: &str, + owner: &str, +) -> Result<(), String> { + let Some(span) = span else { + return Ok(()); + }; + let Some(start) = span.get("start").and_then(Value::as_u64) else { + return Err(format!("{owner} span has no integer start")); + }; + let Some(end) = span.get("end").and_then(Value::as_u64) else { + return Err(format!("{owner} span has no integer end")); + }; + let (start, end) = (start as usize, end as usize); + if start > end || end > source_len { + return Err(format!( + "{owner} span {start}..{end} is outside 0..{source_len}" + )); + } + if !source.is_char_boundary(start) || !source.is_char_boundary(end) { + return Err(format!("{owner} span is not on UTF-8 boundaries")); + } + Ok(()) +} + +fn validate_ast(node: &Value, source_len: usize, source: &str, module: &str) -> Result<(), String> { + let Some(kind) = node.get("kind").and_then(Value::as_str) else { + return Err(format!("{module} AST node has no kind")); + }; + if kind.starts_with("footnote") { + return Err(format!("{module} AST contains a disabled `{kind}` node")); + } + validate_span( + node.get("span"), + source_len, + source, + &format!("{module}.document.{kind}"), + )?; + let children = node + .get("children") + .and_then(Value::as_array) + .ok_or_else(|| format!("{module} AST `{kind}` has no children array"))?; + if matches!( + kind, + "text" + | "code" + | "code_block" + | "math" + | "math_block" + | "html_block" + | "html_inline" + | "front_matter" + | "thematic_break" + | "soft_break" + | "line_break" + ) && !children.is_empty() + { + return Err(format!("{module} AST leaf `{kind}` has children")); + } + for child in children { + validate_ast(child, source_len, source, module)?; + } + Ok(()) +} + +fn validate_json_spans( + value: &Value, + source_len: usize, + source: &str, + owner: &str, +) -> Result<(), String> { + match value { + Value::Object(object) => { + if let Some(span) = object.get("span") { + validate_span(Some(span), source_len, source, owner)?; + } + for nested in object.values() { + validate_json_spans(nested, source_len, source, owner)?; + } + } + Value::Array(items) => { + for item in items { + validate_json_spans(item, source_len, source, owner)?; + } + } + _ => {} + } + Ok(()) +} diff --git a/crates/cli/src/analysis/model.rs b/crates/cli/src/analysis/model.rs new file mode 100644 index 0000000..6077f4c --- /dev/null +++ b/crates/cli/src/analysis/model.rs @@ -0,0 +1,340 @@ +//! Typed public Analysis DTO (spec/analysis.md). +//! +//! These types are the boundary model, not a dump of internal IR: every field +//! is projected explicitly from the prepared program. The canonical encoder +//! serializes this model once; the file writer and the Observation digest use +//! the same bytes. + +use serde::Serialize; +use serde_json::Value; + +/// Half-open UTF-8 byte span in the owning module's `source`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct SpanJson { + /// Inclusive byte offset. + pub start: usize, + /// Exclusive byte offset. + pub end: usize, +} + +impl From for SpanJson { + fn from(span: marqdo_span::Span) -> Self { + Self { + start: span.start, + end: span.end, + } + } +} + +/// Root Analysis document. +#[derive(Debug, Clone, Serialize)] +pub struct Analysis { + /// `marqdo.analysis`. + pub schema: &'static str, + /// Current revision. + pub schema_version: u32, + /// Producer identity. + pub producer: Producer, + /// Project snapshot and entry context. + pub project: Project, + /// Loaded modules, sorted by id. + pub modules: Vec, + /// Deterministic diagnostics. + pub diagnostics: Vec, +} + +/// Producer identity. +#[derive(Debug, Clone, Serialize)] +pub struct Producer { + /// Always `marqdo`. + pub name: &'static str, + /// Product version. + pub version: &'static str, + /// Markdown profile id. + pub markdown_profile: &'static str, +} + +/// Project snapshot identity. +#[derive(Debug, Clone, Serialize)] +pub struct Project { + /// Logical root id. + pub root_id: String, + /// `manifest` or `workspace_snapshot`. + pub identity_kind: &'static str, + /// Module loaded from the CLI entry. + pub entry_module_id: String, + /// Captured lock digest, empty when no lock exists. + pub lock_digest: String, + /// Captured manifest digest, empty when no manifest exists. + pub manifest_digest: String, + /// Verified stdlib identity, if any. + pub stdlib: Option, + /// Static extension identities that participated in preparation. + pub extensions: Vec, +} + +/// Verified bundled stdlib identity. +#[derive(Debug, Clone, Serialize)] +pub struct Stdlib { + /// Declared version. + pub version: String, + /// Verified content digest. + pub digest: String, + /// Package instance id. + pub instance_id: String, +} + +/// One static extension identity. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Extension { + /// `plugin`, `kernel` or `provider`. + pub kind: &'static str, + /// Declared package/provider name. + pub name: String, + /// Declared version. + pub version: String, + /// Logical owner package instance. + pub logical_owner: String, + /// Declared activation source, or `--plugin`. + pub source: String, + /// Manifest digest (`sha256:`). + pub manifest_digest: String, + /// Selected artifact digest (`sha256:`). + pub artifact_digest: String, + /// Selected host target triple. + pub selected_target: String, +} + +/// One loaded module. +#[derive(Debug, Clone, Serialize)] +pub struct ModuleAnalysis { + /// Canonical module id. + pub id: String, + /// Package instance. + pub package_instance_id: String, + /// Package-relative path with `/` separators. + pub relative_path: String, + /// SHA-256 of the exact source bytes. + pub source_digest: String, + /// Exact UTF-8 source text. + pub source: String, + /// Public Markdown AST. + pub document: Value, + /// Heading units in document order. + pub units: Vec, + /// Anchor map sorted by anchor. + pub anchors: Vec, + /// Exec H2 functions in document order. + pub functions: Vec, + /// Explicit imports in document order. + pub imports: Vec, + /// Markdown references in source order. + pub references: Vec, + /// Static call bindings in source order. + pub calls: Vec, + /// Inert resources in document order. + pub resources: Vec, +} + +/// One addressable heading range. +#[derive(Debug, Clone, Serialize)] +pub struct UnitRecord { + /// Canonical unit id. + pub id: String, + /// Structured canonical path. + pub path: Vec, + /// Parent unit id, root `null`. + pub parent_id: Option, + /// `root`, `namespace`, `function`, `knowledge` or `section`. + pub kind: &'static str, + /// Normalised heading name. + pub name: String, + /// Heading level, root 0. + pub level: u8, + /// Effective mode. + pub mode: &'static str, + /// `default`, `explicit` or `inherited`. + pub mode_origin: &'static str, + /// Unit that provided the effective mode. + pub mode_source_unit_id: String, + /// Original heading span, root `null`. + pub heading_span: Option, + /// Complete section range. + pub span: SpanJson, + /// Owning function id. + pub function: Option, +} + +/// One anchor entry. +#[derive(Debug, Clone, Serialize)] +pub struct AnchorRecord { + /// GitHub-style anchor. + pub anchor: String, + /// Addressable unit. + pub unit_id: String, +} + +/// One Exec H2 function. +#[derive(Debug, Clone, Serialize)] +pub struct FunctionRecord { + /// Canonical function id. + pub id: String, + /// Addressable unit. + pub unit_id: String, + /// Local function name. + pub local_name: String, + /// Enclosing namespace. + pub namespace: Option, + /// Declaration span. + pub span: SpanJson, + /// Heading span. + pub heading_span: SpanJson, + /// Signature. + pub signature: SignatureRecord, + /// Conservative effects. + pub effects: Vec<&'static str>, + /// Statements. + pub body: Vec, +} + +/// Function signature. +#[derive(Debug, Clone, Serialize)] +pub struct SignatureRecord { + /// `explicit` or `inferred`. + pub kind: &'static str, + /// Parameters. + pub params: Vec, +} + +/// One function parameter. +#[derive(Debug, Clone, Serialize)] +pub struct ParamRecord { + /// Parameter name. + pub name: String, + /// Whether no default value exists. + pub required: bool, + /// Declared type annotation. + pub r#type: Option, + /// Default expression. + pub default: Option, + /// Declaration span. + pub span: SpanJson, +} + +/// One explicit import. +#[derive(Debug, Clone, Serialize)] +pub struct ImportRecord { + /// Local alias. + pub alias: String, + /// Declared target. + pub target: String, + /// Declaration span. + pub span: SpanJson, + /// Resolved module id. + pub resolved: Option, +} + +/// One resolved document reference. +#[derive(Debug, Clone, Serialize)] +pub struct ReferenceRecord { + /// Source module. + pub source: String, + /// Innermost owning unit. + pub source_unit: String, + /// Raw URL. + pub url: String, + /// Link span. + pub span: SpanJson, + /// Resolver state. + pub state: &'static str, + /// `module`, `file` or `null`. + pub target_kind: Option<&'static str>, + /// Resolved module. + pub target_module: Option, + /// Resolved unit. + pub target_unit: Option, + /// Logical candidate package instance. + pub candidate_package_instance_id: Option, + /// Normalised package-relative candidate. + pub candidate_path: Option, + /// Decoded fragment. + pub fragment: Option, + /// Ambiguous exact candidates. + pub candidates: Vec, +} + +/// One static call record. +#[derive(Debug, Clone, Serialize)] +pub struct CallRecord { + /// Caller function id. + pub function: String, + /// Call expression span. + pub span: SpanJson, + /// Callee shape. + pub callee: Value, + /// Function, builtin, plugin or unresolved. + pub state: &'static str, + /// Bound target value. + pub target: Option, + /// `function`, `builtin`, `plugin` or `null`. + pub target_kind: Option<&'static str>, + /// Static plugin owner, if any. + pub target_owner: Option, + /// `dynamic`, `unbound` or `null`. + pub reason: Option<&'static str>, +} + +/// Static plugin owner of a bound export. +#[derive(Debug, Clone, Serialize)] +pub struct TargetOwner { + /// Always `plugin`. + pub kind: &'static str, + /// Plugin package. + pub package: String, + /// Verified artifact digest. + pub digest: String, +} + +/// One inert resource. +#[derive(Debug, Clone, Serialize)] +pub struct ResourceRecord { + /// Module-local ordinal id. + pub id: String, + /// Owning module. + pub module_id: String, + /// Innermost owning unit. + pub unit_id: String, + /// `formula` or `code`. + pub kind: &'static str, + /// AST node span. + pub span: SpanJson, + /// Payload digest. + pub content_digest: String, + /// Code fence language. + pub language: Option, + /// Formula display mode (`null` for code). + pub display: Option, +} + +/// One diagnostic. +#[derive(Debug, Clone, Serialize)] +pub struct DiagnosticRecord { + /// Owning module. + pub module: String, + /// Package-relative path. + pub relative_path: String, + /// Primary span. + pub span: Option, + /// 1-based line. + pub line: Option, + /// 1-based column. + pub column: Option, + /// `error` or `warning`. + pub severity: &'static str, + /// Stable code. + pub code: String, + /// Message. + pub message: String, + /// Hints. + pub hints: Vec, +} diff --git a/crates/cli/src/commands.rs b/crates/cli/src/commands.rs index cee70bc..2061070 100644 --- a/crates/cli/src/commands.rs +++ b/crates/cli/src/commands.rs @@ -64,38 +64,6 @@ pub(super) fn prepare_project( } } -/// `marqdo check`. -fn validate_refs(project: &LoadedProject) -> Vec { - let mut diagnostics = Vec::new(); - for file in project.files.values() { - let parent = file.path.parent().unwrap_or_else(|| Path::new(".")); - let mut unresolved: Vec = Vec::new(); - file.analysis.document.root.walk(&mut |node| { - let marqdo_markdown::MdKind::Link { url, .. } = &node.kind else { - return; - }; - let (resolved, _, _) = resolve_link(project, &file.analysis.units, parent, url); - if !resolved { - unresolved.push(node.span); - } - }); - for span in unresolved { - diagnostics.push(FileDiagnostic { - module_id: file.module_id.clone(), - path: file.path.clone(), - source: file.source.clone(), - diagnostic: marqdo_value::Diagnostic::error( - marqdo_value::codes::REF_UNRESOLVED, - Some(span), - "reference target could not be resolved", - ) - .with_hint("fix the link target or add the missing heading/file"), - }); - } - } - diagnostics -} - fn summary_json(project: &LoadedProject) -> serde_json::Value { let entry = project.entry_file(); json!({ @@ -130,94 +98,6 @@ fn signatures_json(module: &marqdo_ir::Module) -> serde_json::Value { ) } -fn refs_json(project: &LoadedProject) -> serde_json::Value { - let entry = project.entry_file(); - let parent = entry.path.parent().unwrap_or_else(|| Path::new(".")); - let mut edges = Vec::new(); - entry.analysis.document.root.walk(&mut |node| { - let marqdo_markdown::MdKind::Link { url, .. } = &node.kind else { - return; - }; - let (resolved, target_module, target_unit) = - resolve_link(project, &entry.analysis.units, parent, url); - edges.push(json!({ - "source": entry.module_id.to_string(), - "url": url, - "span": node.span, - "resolved": resolved, - "target_module": target_module, - "target_unit": target_unit, - })); - }); - serde_json::Value::Array(edges) -} - -fn resolve_link( - project: &LoadedProject, - units: &marqdo_frontend::UnitIndex, - parent: &Path, - url: &str, -) -> (bool, Option, Option) { - if let Some(fragment) = url.strip_prefix('#') { - let unit = units.anchors.get(fragment).or_else(|| { - units - .units - .iter() - .find(|unit| unit.name == fragment) - .map(|unit| &unit.id) - }); - return match unit { - Some(unit) => ( - true, - Some(project.entry.to_string()), - Some(unit.to_string()), - ), - None => (false, None, None), - }; - } - if url.starts_with("http://") || url.starts_with("https://") { - return (true, None, None); - } - let (path_part, fragment) = match url.split_once('#') { - Some((path, fragment)) => (path, Some(fragment)), - None => (url, None), - }; - let candidate = parent.join(path_part); - let Ok(candidate) = candidate.canonicalize() else { - return (false, None, None); - }; - let Some(module_id) = project.module_id_for_path(&candidate) else { - return (false, None, None); - }; - let analyzed; - let target_units = match project.files.get(&module_id) { - Some(target_file) => &target_file.analysis.units, - None => { - // Links may reference documents that are not imported. Analyse the - // target statically for reference checking; nothing executes. - let Ok(source) = std::fs::read_to_string(&candidate) else { - return (false, None, None); - }; - analyzed = marqdo_frontend::analyze_source(&module_id.to_string(), &source); - &analyzed.units - } - }; - let Some(fragment) = fragment else { - return (true, Some(module_id.to_string()), None); - }; - let resolved = target_units.anchors.get(fragment).or_else(|| { - target_units - .units - .iter() - .find(|unit| unit.name == fragment) - .map(|unit| &unit.id) - }); - match resolved { - Some(unit) => (true, Some(module_id.to_string()), Some(unit.to_string())), - None => (false, Some(module_id.to_string()), None), - } -} - /// Machine-readable routing decision for one captured strict execution. #[derive(Debug, PartialEq, Eq)] enum StrictRoute { diff --git a/crates/cli/src/commands/check.rs b/crates/cli/src/commands/check.rs index 5602ba4..afd36c3 100644 --- a/crates/cli/src/commands/check.rs +++ b/crates/cli/src/commands/check.rs @@ -13,28 +13,48 @@ pub fn check( Ok(prepared) => prepared, Err(code) => { // A failed check never leaves a success artifact behind: a consumer - // must not be able to bind `run` to a previous Analysis after the - // project stopped loading or compiling. + // must not bind `run` to a previous Analysis after the project + // stopped loading. The input document is never the cleanup target. if let Some(path) = emit { - let _ = std::fs::remove_file(path); + if let Err(error) = crate::analysis::discard_without_prepare(file, path) { + eprintln!("error: {error}"); + return 2; + } } return code; } }; - let mut project = prepared.loaded; + let mut prepared = prepared; if refs { - let ref_diagnostics = validate_refs(&project); - project.diagnostics.extend(ref_diagnostics); + let report = crate::document_refs::references_for_project( + &prepared.loaded, + crate::document_refs::ReferenceMode::VerifyLocal, + ); + for issue in report.issues { + let Some(file) = prepared.loaded.files.get(&issue.module) else { + continue; + }; + prepared.loaded.diagnostics.push(FileDiagnostic { + module_id: issue.module, + path: file.path.clone(), + source: file.source.clone(), + diagnostic: issue.diagnostic, + }); + } } - let errors = output::error_count(&project.diagnostics); + let errors = output::error_count(&prepared.loaded.diagnostics); if let Some(path) = emit { if errors > 0 { - let _ = std::fs::remove_file(path); - } else if let Err(error) = crate::analysis::write(&project, path) { + if let Err(error) = crate::analysis::discard(&prepared, path) { + eprintln!("error: {error}"); + return 2; + } + } else if let Err(error) = crate::analysis::write(&prepared, path) { eprintln!("error: {error}"); return 2; } } + let project = &prepared.loaded; if json { output::print_json(&json!({ "command": "check", diff --git a/crates/cli/src/commands/inspect.rs b/crates/cli/src/commands/inspect.rs index ebaa51d..1e48fc9 100644 --- a/crates/cli/src/commands/inspect.rs +++ b/crates/cli/src/commands/inspect.rs @@ -46,13 +46,20 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: & if flags.ast { object.insert( "ast".into(), - serde_json::to_value(&entry.analysis.document.root).unwrap_or_default(), + crate::analysis::document_projection( + &entry.analysis.document.root, + entry.source.len(), + ), ); } if flags.units { object.insert( "units".into(), - serde_json::to_value(&entry.analysis.units.units).unwrap_or_default(), + serde_json::to_value(crate::analysis::units_projection( + &entry.analysis.units, + entry.source.len(), + )) + .unwrap_or_default(), ); } if flags.signature { @@ -65,7 +72,9 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: & ); } if flags.refs { - object.insert("refs".into(), json!(refs_json(project))); + let (references, issues) = refs_json(&prepared, &entry.module_id); + object.insert("refs".into(), references); + object.insert("reference_issues".into(), issues); } if flags.platform { object.insert( @@ -106,13 +115,21 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: & if flags.ast { println!( "{}", - serde_json::to_string_pretty(&entry.analysis.document.root).unwrap_or_default() + serde_json::to_string_pretty(&crate::analysis::document_projection( + &entry.analysis.document.root, + entry.source.len() + )) + .unwrap_or_default() ); } if flags.units { println!( "{}", - serde_json::to_string_pretty(&entry.analysis.units.units).unwrap_or_default() + serde_json::to_string_pretty(&crate::analysis::units_projection( + &entry.analysis.units, + entry.source.len() + )) + .unwrap_or_default() ); } if flags.signature { @@ -128,9 +145,14 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: & ); } if flags.refs { + let (references, issues) = refs_json(&prepared, &entry.module_id); println!( "{}", - serde_json::to_string_pretty(&refs_json(project)).unwrap_or_default() + serde_json::to_string_pretty(&json!({ + "refs": references, + "reference_issues": issues, + })) + .unwrap_or_default() ); } if flags.platform { @@ -149,6 +171,41 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: & 0 } +/// Resolve the entry module's links through the one document resolver and the +/// explicit `--refs` catalog. `inspect` never executes a target. +fn refs_json( + prepared: &crate::project_prepare::PreparedProgram, + entry: &marqdo_ir::ModuleId, +) -> (serde_json::Value, serde_json::Value) { + let report = crate::document_refs::references_for_project( + &prepared.loaded, + crate::document_refs::ReferenceMode::VerifyLocal, + ); + let references: Vec = report + .by_module + .get(entry) + .cloned() + .unwrap_or_default() + .into_iter() + .map(crate::analysis::reference_projection) + .collect(); + let references = serde_json::to_value(references).unwrap_or_default(); + let issues = report + .issues + .iter() + .filter(|issue| &issue.module == entry) + .map(|issue| { + json!({ + "code": issue.diagnostic.code, + "severity": if issue.diagnostic.is_error() { "error" } else { "warning" }, + "span": issue.diagnostic.span.map(|span| json!({"start": span.start, "end": span.end})), + "message": issue.diagnostic.message, + }) + }) + .collect::>(); + (references, serde_json::Value::Array(issues)) +} + /// Static extension identity projection for `inspect --extensions`. /// /// Reports declared sources, lock identity, static plugin descriptors and diff --git a/crates/cli/src/commands/run.rs b/crates/cli/src/commands/run.rs index 7a7ddcd..8da96e2 100644 --- a/crates/cli/src/commands/run.rs +++ b/crates/cli/src/commands/run.rs @@ -58,12 +58,10 @@ pub fn execute( Ok(prepared) => prepared, Err(error) => return fail_prepare(stream, "prepare", &error), }; - let extension_sources = prepared.loaded.extension_sources.clone(); - let project = prepared.loaded; - let static_plugins = prepared.plugins; - if project.has_errors() { + if prepared.loaded.has_errors() { if let Some(stream) = stream { - let code = project + let code = prepared + .loaded .diagnostics .iter() .find(|item| item.diagnostic.is_error()) @@ -77,10 +75,24 @@ pub fn execute( return transport_failure(&error); } } - eprint!("{}", output::render_text(&project.diagnostics)); + eprint!("{}", output::render_text(&prepared.loaded.diagnostics)); eprintln!("error: refusing to run a project with compile errors"); return 1; } + // Bind the Observation snapshot to the exact bytes of the ordinary + // Analysis for these static options. Build it before moving the prepared + // program apart, but only when an observation destination is requested. + let analysis_digest = if stream.is_some() { + match crate::analysis::digest(&prepared) { + Ok(digest) => Some(digest), + Err(error) => return fail(stream, "prepare", "cli.analysis_failed", &error, 1), + } + } else { + None + }; + let extension_sources = prepared.loaded.extension_sources.clone(); + let project = prepared.loaded; + let static_plugins = prepared.plugins; let warnings: Vec = project .diagnostics .iter() @@ -342,15 +354,12 @@ pub fn execute( }; if let Some(stream) = stream { let entry = format!("{}::{}", project.entry, function_name); - let analysis_digest = match crate::analysis::digest(&project) { - Ok(digest) => digest, - Err(error) => return fail(Some(stream), "prepare", "cli.analysis_failed", &error, 1), - }; + let analysis_digest = analysis_digest.as_deref().unwrap_or_default(); if let Err(error) = stream.started( &entry, mode.as_str(), &project.identity.root_id(), - &analysis_digest, + analysis_digest, ) { return transport_failure(&error); } diff --git a/crates/cli/src/document_refs.rs b/crates/cli/src/document_refs.rs index 320bca5..10e646b 100644 --- a/crates/cli/src/document_refs.rs +++ b/crates/cli/src/document_refs.rs @@ -10,9 +10,9 @@ //! All states are explicit: a local candidate outside the catalog is //! `not_loaded` (unverified), never `missing`. -use std::collections::{BTreeMap, BTreeSet}; use marqdo_span::Span; use marqdo_value::{codes, Diagnostic}; +use std::collections::{BTreeMap, BTreeSet}; use crate::loader::LoadedProject; @@ -99,11 +99,18 @@ pub struct Reference { } impl Reference { - fn placeholder(source: &marqdo_ir::ModuleId, units: &UnitIndexView, url: &str, span: Span) -> Self { - let source_unit = units.unit_containing_span(span).unwrap_or_else(|| marqdo_ir::UnitId { - module: source.clone(), - path: Vec::new(), - }); + fn placeholder( + source: &marqdo_ir::ModuleId, + units: &marqdo_frontend::UnitIndex, + url: &str, + span: Span, + ) -> Self { + let source_unit = units + .unit_containing_span(span) + .unwrap_or_else(|| marqdo_ir::UnitId { + module: source.clone(), + path: Vec::new(), + }); Self { source: source.clone(), source_unit, @@ -124,33 +131,10 @@ impl Reference { /// Facts needed to resolve a fragment in one document. #[derive(Debug, Clone)] pub struct ModuleFacts { - /// Canonical module identity. - pub module: marqdo_ir::ModuleId, /// Anchor map (same namespace as `UnitIndex.anchors`). pub anchors: BTreeMap, /// Exact canonical names in document order. pub names: BTreeMap>, - /// Complete unit ranges, root first. - pub ranges: Vec<(marqdo_ir::UnitId, Span)>, -} - -/// Minimal source-unit view needed while collecting references. -pub enum UnitIndexView<'a> { - /// The frontend heading index. - Index(&'a marqdo_frontend::UnitIndex), - /// Only a root unit was available. - Root(marqdo_ir::UnitId, Span), -} - -impl UnitIndexView<'_> { - fn unit_containing_span(&self, span: Span) -> Option { - match self { - UnitIndexView::Index(index) => index.unit_containing_span(span), - UnitIndexView::Root(id, range) => { - (range.start <= span.start && span.end <= range.end).then(|| id.clone()) - } - } - } } /// An explicit catalog of documents available to the resolver. @@ -176,15 +160,18 @@ impl DocumentCatalog { } /// Add one analysed document's facts. - pub fn insert_module(&mut self, module: marqdo_ir::ModuleId, units: &marqdo_frontend::UnitIndex) { + pub fn insert_module( + &mut self, + module: marqdo_ir::ModuleId, + units: &marqdo_frontend::UnitIndex, + ) { let mut names: BTreeMap> = BTreeMap::new(); - let mut ranges = Vec::with_capacity(units.units.len()); for unit in &units.units { if !unit.name.is_empty() { - names.entry(unit.name.clone()).or_default().push(unit.id.clone()); - } - if let Some(range) = units.unit_range(&unit.id) { - ranges.push((unit.id.clone(), range)); + names + .entry(unit.name.clone()) + .or_default() + .push(unit.id.clone()); } } self.path_index.insert( @@ -194,10 +181,8 @@ impl DocumentCatalog { self.modules.insert( module.clone(), ModuleFacts { - module, anchors: units.anchors.clone(), names, - ranges, }, ); } @@ -207,7 +192,8 @@ impl DocumentCatalog { } fn module_for(&self, instance: &str, relative_path: &str) -> Option<&marqdo_ir::ModuleId> { - self.path_index.get(&(instance.to_string(), relative_path.to_string())) + self.path_index + .get(&(instance.to_string(), relative_path.to_string())) } fn has_instance(&self, instance: &str) -> bool { @@ -265,11 +251,15 @@ pub fn references_for_project(project: &LoadedProject, mode: ReferenceMode) -> R if !attempted.insert((instance.to_string(), path.to_string())) { continue; } - if let Err(error) = extend_for_reference(project, &mut catalog, reference, &mut budget) { + if let Err(error) = extend_for_reference(project, &mut catalog, reference, &mut budget) + { let mut diagnostic = Diagnostic::error( codes::REF_INVALID, Some(reference.span), - format!("cannot verify reference target `{}`: {error}", reference.url), + format!( + "cannot verify reference target `{}`: {error}", + reference.url + ), ); diagnostic = diagnostic.with_hint( "fix the link target, or remove the broken link from the explicit refs check", @@ -340,7 +330,10 @@ fn reference_issues( ReferenceState::OutsideScope | ReferenceState::Invalid => ( "error", codes::REF_INVALID, - format!("reference `{}` is not a valid in-scope target", reference.url), + format!( + "reference `{}` is not a valid in-scope target", + reference.url + ), ), }; let hint = match reference.state { @@ -412,15 +405,7 @@ fn collect_links(project: &LoadedProject) -> Vec> { fn resolve_all(catalog: &DocumentCatalog, raw: &[RawLink<'_>]) -> Vec { raw.iter() - .map(|link| { - resolve_link( - catalog, - link.module, - UnitIndexView::Index(link.units), - link.url, - link.span, - ) - }) + .map(|link| resolve_link(catalog, link.module, link.units, link.url, link.span)) .collect() } @@ -428,7 +413,7 @@ fn resolve_all(catalog: &DocumentCatalog, raw: &[RawLink<'_>]) -> Vec pub fn resolve_link( catalog: &DocumentCatalog, source: &marqdo_ir::ModuleId, - units: UnitIndexView<'_>, + units: &marqdo_frontend::UnitIndex, url: &str, span: Span, ) -> Reference { @@ -708,10 +693,10 @@ pub fn percent_decode(raw: &str) -> Result { if index + 2 >= bytes.len() { return Err("truncated percent escape".to_string()); } - let high = hex_value(bytes[index + 1]) - .ok_or_else(|| "invalid percent escape".to_string())?; - let low = hex_value(bytes[index + 2]) - .ok_or_else(|| "invalid percent escape".to_string())?; + let high = + hex_value(bytes[index + 1]).ok_or_else(|| "invalid percent escape".to_string())?; + let low = + hex_value(bytes[index + 2]).ok_or_else(|| "invalid percent escape".to_string())?; out.push((high << 4) | low); index += 3; } else { @@ -860,9 +845,7 @@ mod tests { let mut catalog = DocumentCatalog::default(); for (id, source) in documents { let (module_id, analysis) = module(source, id); - catalog - .instances - .insert(module_id.instance.clone()); + catalog.instances.insert(module_id.instance.clone()); catalog.insert_module(module_id, &analysis.units); } catalog @@ -874,13 +857,7 @@ mod tests { analysis: &marqdo_frontend::AnalysisResult, url: &str, ) -> Reference { - resolve_link( - catalog, - source, - UnitIndexView::Index(&analysis.units), - url, - Span::new(0, 1), - ) + resolve_link(catalog, source, &analysis.units, url, Span::new(0, 1)) } #[test] @@ -915,9 +892,7 @@ mod tests { let target = "# @knowledge a\n\n## @knowledge A B\n\n# @knowledge b\n\n## @knowledge A B\n"; let (target_id, target_analysis) = module(target, "theories.mq.md"); let mut catalog = catalog_of(&[("index.mq.md", source), ("theories.mq.md", target)]); - catalog - .instances - .insert(target_id.instance.clone()); + catalog.instances.insert(target_id.instance.clone()); catalog.insert_module(target_id.clone(), &target_analysis.units); // The exact slug resolves deterministically to the first occurrence. let exact = resolve(&catalog, &module_id, &analysis, "./theories.mq.md#a-b"); @@ -937,9 +912,7 @@ mod tests { let target = "# @knowledge Namespace\n\n## @knowledge A B\n"; let (target_id, target_analysis) = module(target, "targets.mq.md"); let mut catalog = catalog_of(&[("index.mq.md", source), ("targets.mq.md", target)]); - catalog - .instances - .insert(target_id.instance.clone()); + catalog.instances.insert(target_id.instance.clone()); catalog.insert_module(target_id, &target_analysis.units); let reference = resolve(&catalog, &module_id, &analysis, "./targets.mq.md#A B"); assert_eq!(reference.state, ReferenceState::Resolved, "{reference:?}"); @@ -988,10 +961,11 @@ mod tests { let (module_id, analysis) = module(source, "index.mq.md"); let (target_id, target_analysis) = module("## @knowledge formula\n\n正文\n", "theory.mq.md"); - let mut catalog = catalog_of(&[("index.mq.md", source), ("theory.mq.md", "## @knowledge formula\n\n正文\n")]); - catalog - .instances - .insert(target_id.instance.clone()); + let mut catalog = catalog_of(&[ + ("index.mq.md", source), + ("theory.mq.md", "## @knowledge formula\n\n正文\n"), + ]); + catalog.instances.insert(target_id.instance.clone()); catalog.insert_module(target_id.clone(), &target_analysis.units); let reference = resolve(&catalog, &module_id, &analysis, "./theory.mq.md#formula"); assert_eq!(reference.state, ReferenceState::Resolved); @@ -1004,10 +978,11 @@ mod tests { let source = "## @exec main\n\n[x](./theory.mq.md#nope)\n"; let (module_id, analysis) = module(source, "index.mq.md"); let (target_id, target_analysis) = module("## @knowledge formula\n", "theory.mq.md"); - let mut catalog = catalog_of(&[("index.mq.md", source), ("theory.mq.md", "## @knowledge formula\n")]); - catalog - .instances - .insert(target_id.instance.clone()); + let mut catalog = catalog_of(&[ + ("index.mq.md", source), + ("theory.mq.md", "## @knowledge formula\n"), + ]); + catalog.instances.insert(target_id.instance.clone()); catalog.insert_module(target_id.clone(), &target_analysis.units); let reference = resolve(&catalog, &module_id, &analysis, "./theory.mq.md#nope"); assert_eq!(reference.state, ReferenceState::Missing); @@ -1019,6 +994,9 @@ mod tests { assert_eq!(percent_decode("%E8%AE%A1%E7%AE%97").unwrap(), "计算"); assert_eq!(percent_decode("a%2520b").unwrap(), "a%20b"); assert!(percent_decode("%zz").is_err()); - assert_eq!(percent_decode("100%").unwrap_err(), "truncated percent escape"); + assert_eq!( + percent_decode("100%").unwrap_err(), + "truncated percent escape" + ); } } diff --git a/crates/cli/src/loader.rs b/crates/cli/src/loader.rs index 0cc63b0..a28f78c 100644 --- a/crates/cli/src/loader.rs +++ b/crates/cli/src/loader.rs @@ -216,29 +216,6 @@ impl LoadedProject { column: position.column, }) } - - /// Resolve a physical path to its loaded or statically addressable module. - pub fn module_id_for_path(&self, path: &Path) -> Option { - let canonical = path.canonicalize().ok()?; - let mut best: Option<(&String, &PathBuf)> = None; - for (instance, root) in &self.packages { - if canonical.starts_with(root) - && best - .as_ref() - .map(|(_, current)| root.components().count() > current.components().count()) - .unwrap_or(true) - { - best = Some((instance, root)); - } - } - let (instance, root) = best?; - let relative = canonical.strip_prefix(root).ok()?; - let mut parts = Vec::new(); - for component in relative.components() { - parts.push(component.as_os_str().to_string_lossy().to_string()); - } - Some(ModuleId::new(instance.clone(), parts.join("/"))) - } } struct Loader { @@ -274,8 +251,8 @@ pub fn load(entry: &Path) -> Result { .map_err(|error| format!("cannot read {MANIFEST_FILE}: {error}"))?; let yaml = String::from_utf8(bytes.clone()) .map_err(|error| format!("{MANIFEST_FILE} is not valid UTF-8: {error}"))?; - let manifest = Manifest::from_yaml(&yaml) - .map_err(|error| format!("{MANIFEST_FILE}: {error}"))?; + let manifest = + Manifest::from_yaml(&yaml).map_err(|error| format!("{MANIFEST_FILE}: {error}"))?; (Some(manifest), bytes_digest(&bytes)) } else { (None, String::new()) @@ -286,8 +263,7 @@ pub fn load(entry: &Path) -> Result { .map_err(|error| format!("cannot read {LOCK_FILE}: {error}"))?; let yaml = String::from_utf8(bytes.clone()) .map_err(|error| format!("{LOCK_FILE} is not valid UTF-8: {error}"))?; - let lock = LockFile::from_yaml(&yaml) - .map_err(|error| format!("{LOCK_FILE}: {error}"))?; + let lock = LockFile::from_yaml(&yaml).map_err(|error| format!("{LOCK_FILE}: {error}"))?; if let Some(manifest) = &manifest { lock.validate_root(manifest) .map_err(|error| format!("{LOCK_FILE}: {error}"))?; @@ -724,10 +700,8 @@ mod tests { fn temp_project(files: &[(&str, &str)]) -> PathBuf { let id = COUNTER.fetch_add(1, Ordering::Relaxed); - let root = std::env::temp_dir().join(format!( - "marqdo-loader-test-{}-{id}", - std::process::id() - )); + let root = + std::env::temp_dir().join(format!("marqdo-loader-test-{}-{id}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).unwrap(); for (name, source) in files { diff --git a/crates/cli/tests/analysis_observation.rs b/crates/cli/tests/analysis_observation.rs index 36658f1..39b54d6 100644 --- a/crates/cli/tests/analysis_observation.rs +++ b/crates/cli/tests/analysis_observation.rs @@ -267,9 +267,16 @@ print(1) assert_eq!(code["language"], "python"); assert_eq!(formula["content_digest"].as_str().unwrap().len(), 64); assert_eq!(code["content_digest"].as_str().unwrap().len(), 64); - assert!( - !analysis.to_string().contains("A = x + 1"), - "resource payloads stay in source, not Analysis" + let source = analysis["modules"][0]["source"] + .as_str() + .expect("exact source is public"); + assert!(source.contains("A = x + 1")); + assert_eq!( + source.len(), + analysis["modules"][0]["source_digest"] + .as_str() + .map(|_| source.len()) + .unwrap_or(0) ); } diff --git a/crates/cli/tests/integration_cli.rs b/crates/cli/tests/integration_cli.rs index 9682e86..f7a3981 100644 --- a/crates/cli/tests/integration_cli.rs +++ b/crates/cli/tests/integration_cli.rs @@ -663,7 +663,7 @@ fn inspect_outputs_ast_units_signatures_ir_and_refs() { assert_exit(&refs, 0, "inspect --refs"); let value = json_stdout(&refs); let edges = value["refs"].as_array().expect("refs array"); - assert!(edges.iter().any(|edge| edge["resolved"] == true)); + assert!(edges.iter().any(|edge| edge["state"] == "resolved")); // A broken #anchor is reported as unresolved by `inspect --refs`. let dir = TempDir::new("refs"); @@ -677,7 +677,8 @@ fn inspect_outputs_ast_units_signatures_ir_and_refs() { let edges = value["refs"].as_array().expect("refs array"); assert_eq!(edges.len(), 1); assert_eq!(edges[0]["url"], "#不存在的标题"); - assert_eq!(edges[0]["resolved"], false); + assert_eq!(edges[0]["state"], "missing"); + assert_eq!(edges[0]["target_unit"], serde_json::Value::Null); } #[test]