analysis: project document and program facts through one typed encoder

Replace the program-only projection with ADR-0069's typed model: exact source
and digest, the public document AST, complete heading scopes with parent/mode
origin/range, anchors, functions, imports, references, calls and resources.
Project identity now carries the entry, captured manifest/lock digests, stdlib
and the static extension identities that participated in preparation. Run and
call bind Observation to the same canonical bytes, inspect reuses the same AST,
unit and reference projectors, and the retired duplicate link resolver is
deleted. Emit refuses to overwrite inputs, directories, symlinks or hard links
and publishes through an owner-only exclusive temporary file.
This commit is contained in:
cflmy committed 2026-11-25 10:12:07 +08:00
1 parent 1b214d48da
commit 99789616a4
12 files changed
+2017 -915

No files matched your search

-653
View File
@@ -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::<Vec<_>>(),
"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::<Vec<_>>(),
"references": reference_edges(project, module_id),
"calls": module.functions.iter().flat_map(|function| calls_json(project, module, function)).collect::<Vec<_>>(),
"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<Vec<u8>, 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<String, String> {
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<Value> {
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<Value> {
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<Value> {
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::<Vec<_>>(),
},
"effects": ["unknown"],
"body": function.body.iter().map(stmt_json).collect::<Vec<_>>(),
})
}
/// 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::<Vec<_>>(),
"span": span_json(arm.span),
})).collect::<Vec<_>>(),
"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::<Vec<_>>(),
"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::<Vec<_>>(),"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::<Vec<_>>(),
"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::<Vec<_>>(),
"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<Value> {
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<Value> {
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<Value>,
) {
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<Value>,
) {
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())
}
+115
View File
@@ -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<Span>) -> 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<Value> = 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)
}
File diff suppressed because it is too large. Load diff
+340
View File
@@ -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<marqdo_span::Span> 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<ModuleAnalysis>,
/// Deterministic diagnostics.
pub diagnostics: Vec<DiagnosticRecord>,
}
/// 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<Stdlib>,
/// Static extension identities that participated in preparation.
pub extensions: Vec<Extension>,
}
/// 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:<hex>`).
pub manifest_digest: String,
/// Selected artifact digest (`sha256:<hex>`).
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<UnitRecord>,
/// Anchor map sorted by anchor.
pub anchors: Vec<AnchorRecord>,
/// Exec H2 functions in document order.
pub functions: Vec<FunctionRecord>,
/// Explicit imports in document order.
pub imports: Vec<ImportRecord>,
/// Markdown references in source order.
pub references: Vec<ReferenceRecord>,
/// Static call bindings in source order.
pub calls: Vec<CallRecord>,
/// Inert resources in document order.
pub resources: Vec<ResourceRecord>,
}
/// One addressable heading range.
#[derive(Debug, Clone, Serialize)]
pub struct UnitRecord {
/// Canonical unit id.
pub id: String,
/// Structured canonical path.
pub path: Vec<String>,
/// Parent unit id, root `null`.
pub parent_id: Option<String>,
/// `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<SpanJson>,
/// Complete section range.
pub span: SpanJson,
/// Owning function id.
pub function: Option<String>,
}
/// 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<String>,
/// 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<Value>,
}
/// Function signature.
#[derive(Debug, Clone, Serialize)]
pub struct SignatureRecord {
/// `explicit` or `inferred`.
pub kind: &'static str,
/// Parameters.
pub params: Vec<ParamRecord>,
}
/// 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<String>,
/// Default expression.
pub default: Option<Value>,
/// 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<String>,
}
/// 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<String>,
/// Resolved unit.
pub target_unit: Option<String>,
/// Logical candidate package instance.
pub candidate_package_instance_id: Option<String>,
/// Normalised package-relative candidate.
pub candidate_path: Option<String>,
/// Decoded fragment.
pub fragment: Option<String>,
/// Ambiguous exact candidates.
pub candidates: Vec<String>,
}
/// 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<String>,
/// `function`, `builtin`, `plugin` or `null`.
pub target_kind: Option<&'static str>,
/// Static plugin owner, if any.
pub target_owner: Option<TargetOwner>,
/// `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<String>,
/// Formula display mode (`null` for code).
pub display: Option<bool>,
}
/// 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<SpanJson>,
/// 1-based line.
pub line: Option<usize>,
/// 1-based column.
pub column: Option<usize>,
/// `error` or `warning`.
pub severity: &'static str,
/// Stable code.
pub code: String,
/// Message.
pub message: String,
/// Hints.
pub hints: Vec<String>,
}
-120
View File
@@ -64,38 +64,6 @@ pub(super) fn prepare_project(
}
}
/// `marqdo check`.
fn validate_refs(project: &LoadedProject) -> Vec<FileDiagnostic> {
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<marqdo_span::Span> = 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<String>, Option<String>) {
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 {
+29 -9
View File
@@ -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",
+63 -6
View File
@@ -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<crate::analysis::ReferenceRecord> = 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::<Vec<_>>();
(references, serde_json::Value::Array(issues))
}
/// Static extension identity projection for `inspect --extensions`.
///
/// Reports declared sources, lock identity, static plugin descriptors and
+20 -11
View File
@@ -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<FileDiagnostic> = 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);
}
+58 -80
View File
@@ -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<String, marqdo_ir::UnitId>,
/// Exact canonical names in document order.
pub names: BTreeMap<String, Vec<marqdo_ir::UnitId>>,
/// 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<marqdo_ir::UnitId> {
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<String, Vec<marqdo_ir::UnitId>> = 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<RawLink<'_>> {
fn resolve_all(catalog: &DocumentCatalog, raw: &[RawLink<'_>]) -> Vec<Reference> {
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<Reference>
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<String, String> {
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"
);
}
}
+5 -31
View File
@@ -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<ModuleId> {
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<LoadedProject, String> {
.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<LoadedProject, String> {
.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 {