Files
marqdo-lint/src/model/analysis.rs
T

1930 lines
68 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use std::collections::{HashMap, HashSet};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};
use super::{SourceSnapshot, Span};
use crate::error::Result as LintResult;
/// One actionable sentence attached to every protocol rejection. Consumers are
/// expected to fail closed; they must never try to repair an old artifact.
pub(crate) const PROTOCOL_REGEN_HINT: &str =
"请用当前 marqdo CLI(>=3.0.0-rc.4)重新生成 Analysis,重新安装 marqdo-lint Tool,并重建 lint";
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Producer {
pub name: String,
pub version: String,
pub markdown_profile: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IdentityKind {
Manifest,
WorkspaceSnapshot,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StdlibIdentity {
pub version: String,
pub digest: String,
pub instance_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExtensionIdentity {
pub kind: String,
pub name: String,
pub version: String,
pub logical_owner: String,
pub source: String,
pub manifest_digest: String,
pub artifact_digest: String,
pub selected_target: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AnalysisProject {
pub root_id: String,
pub identity_kind: IdentityKind,
pub entry_module_id: String,
pub lock_digest: String,
pub manifest_digest: String,
pub stdlib: Option<StdlibIdentity>,
pub extensions: Vec<ExtensionIdentity>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UnitKind {
Root,
Namespace,
Function,
Knowledge,
Section,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HeadingMode {
Exec,
Knowledge,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModeOrigin {
Default,
Explicit,
Inherited,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AnalysisUnit {
pub id: String,
pub path: Vec<String>,
pub parent_id: Option<String>,
pub kind: UnitKind,
pub name: String,
pub level: u8,
pub mode: HeadingMode,
pub mode_origin: ModeOrigin,
pub mode_source_unit_id: String,
pub heading_span: Option<Span>,
pub span: Span,
pub function: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AnalysisAnchor {
pub anchor: String,
pub unit_id: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SignatureKind {
Explicit,
Inferred,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AnalysisParam {
pub name: String,
pub required: bool,
#[serde(rename = "type")]
pub param_type: Option<String>,
pub default: Option<Value>,
pub span: Span,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AnalysisSignature {
pub kind: SignatureKind,
pub params: Vec<AnalysisParam>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AnalysisFunction {
pub id: String,
pub unit_id: String,
pub local_name: String,
pub namespace: Option<String>,
pub span: Span,
pub heading_span: Span,
pub signature: AnalysisSignature,
pub effects: Vec<String>,
pub body: Vec<Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AnalysisImport {
pub alias: String,
pub target: String,
pub span: Span,
pub resolved: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReferenceState {
Resolved,
NotLoaded,
Missing,
Ambiguous,
External,
OutsideScope,
Invalid,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReferenceTargetKind {
Module,
File,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AnalysisReference {
pub source: String,
pub source_unit: String,
pub url: String,
pub span: Span,
pub state: ReferenceState,
pub target_kind: Option<ReferenceTargetKind>,
pub target_module: Option<String>,
pub target_unit: Option<String>,
pub candidate_package_instance_id: Option<String>,
pub candidate_path: Option<String>,
pub fragment: Option<String>,
pub candidates: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CallState {
Function,
Builtin,
Plugin,
Unresolved,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CallTargetKind {
Function,
Builtin,
Plugin,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CallReason {
Dynamic,
Unbound,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CallTargetOwner {
pub kind: String,
pub package: String,
pub digest: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AnalysisCall {
pub function: String,
pub span: Span,
pub callee: Value,
pub state: CallState,
pub target: Option<String>,
pub target_kind: Option<CallTargetKind>,
pub target_owner: Option<CallTargetOwner>,
pub reason: Option<CallReason>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResourceKind {
Formula,
Code,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AnalysisResource {
pub id: String,
pub module_id: String,
pub unit_id: String,
pub kind: ResourceKind,
pub span: Span,
pub content_digest: String,
pub language: Option<String>,
pub display: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AnalysisModule {
pub id: String,
pub package_instance_id: String,
pub relative_path: String,
pub source_digest: String,
pub source: String,
pub document: Value,
pub units: Vec<AnalysisUnit>,
pub anchors: Vec<AnalysisAnchor>,
pub functions: Vec<AnalysisFunction>,
pub imports: Vec<AnalysisImport>,
pub references: Vec<AnalysisReference>,
pub calls: Vec<AnalysisCall>,
pub resources: Vec<AnalysisResource>,
}
impl AnalysisModule {
pub fn source_snapshot(&self, display_path: std::path::PathBuf) -> LintResult<SourceSnapshot> {
let snapshot = SourceSnapshot::new(display_path, self.source.as_bytes().to_vec())?;
if snapshot.digest_hex() != self.source_digest {
return Err(crate::error::LintError::Protocol(format!(
"模块 {} 的 source_digest 与 artifact source 不一致;{PROTOCOL_REGEN_HINT}",
self.id
)));
}
Ok(snapshot)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AnalysisDiagnostic {
pub module: String,
pub relative_path: String,
pub span: Option<Span>,
pub line: Option<usize>,
pub column: Option<usize>,
pub severity: String,
pub code: String,
pub message: String,
#[serde(default)]
pub hints: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct ExecutionProjection {
pub schema_version: u64,
pub producer: Producer,
pub project: AnalysisProject,
pub modules: Vec<AnalysisModule>,
pub diagnostics: Vec<AnalysisDiagnostic>,
pub raw: Value,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Wire {
#[serde(rename = "schema")]
_schema: String,
schema_version: u64,
producer: Producer,
project: AnalysisProject,
modules: Vec<AnalysisModule>,
diagnostics: Vec<AnalysisDiagnostic>,
}
impl ExecutionProjection {
pub fn from_bytes(bytes: &[u8]) -> Result<Self, String> {
let raw: Value = serde_json::from_slice(bytes)
.map_err(|error| format!("Analysis JSON 无效:{error};{PROTOCOL_REGEN_HINT}"))?;
Self::from_json(raw)
}
pub fn from_json(raw: Value) -> Result<Self, String> {
if raw.get("schema").and_then(Value::as_str) != Some("marqdo.analysis") {
return Err(format!(
"Analysis schema 必须是 marqdo.analysis;{PROTOCOL_REGEN_HINT}"
));
}
let revision = raw.get("schema_version").and_then(Value::as_u64);
if revision != Some(3) {
let actual = revision
.map(|value| value.to_string())
.unwrap_or_else(|| "缺失".into());
return Err(format!(
"不支持的 Analysis schema_version {actual},只接受 revision 3;{PROTOCOL_REGEN_HINT}"
));
}
reject_retired_module_shape(&raw)?;
let wire: Wire = serde_json::from_value(raw.clone()).map_err(|error| {
format!("Analysis revision 3 字段不完整或类型错误:{error};{PROTOCOL_REGEN_HINT}")
})?;
validate_projection(&wire)?;
Ok(Self {
schema_version: wire.schema_version,
producer: wire.producer,
project: wire.project,
modules: wire.modules,
diagnostics: wire.diagnostics,
raw,
})
}
pub fn entry_module(&self) -> Option<&AnalysisModule> {
self.modules
.iter()
.find(|module| module.id == self.project.entry_module_id)
}
pub fn root_package_instance_id(&self) -> Option<&str> {
self.entry_module()
.map(|module| module.package_instance_id.as_str())
}
}
/// rc.3 and rc.4 both serialize `schema_version: 3`; the current boundary is
/// identified by required fields, not by the revision number alone. Detect the
/// retired shape before serde can produce a generic "missing field" error.
fn reject_retired_module_shape(raw: &Value) -> Result<(), String> {
let modules = raw
.get("modules")
.and_then(Value::as_array)
.ok_or_else(|| format!("Analysis.modules 必须是数组;{PROTOCOL_REGEN_HINT}"))?;
for module in modules {
let object = module
.as_object()
.ok_or_else(|| format!("Analysis.modules 的每一项必须是对象;{PROTOCOL_REGEN_HINT}"))?;
for field in ["source", "document", "anchors"] {
if !object.contains_key(field) {
return Err(format!(
"检测到旧 revision 3 制品(模块缺少 {field});同 revision 的旧字段集合不再接受,{PROTOCOL_REGEN_HINT}"
));
}
}
for field in ["source", "document", "anchors"] {
if object.get(field).is_none_or(Value::is_null) {
return Err(format!(
"模块字段 {field} 不得为 null;{PROTOCOL_REGEN_HINT}"
));
}
}
}
Ok(())
}
fn validate_projection(wire: &Wire) -> Result<(), String> {
if wire.producer.name != "marqdo" {
return Err("Analysis producer.name 必须是 marqdo".into());
}
if wire.producer.version.trim().is_empty() {
return Err("Analysis producer.version 不得为空".into());
}
if wire.producer.markdown_profile != "marqdo.md.v1" {
return Err("Analysis producer.markdown_profile 必须是 marqdo.md.v1".into());
}
validate_project(&wire.project)?;
if wire.modules.is_empty() {
return Err("Analysis.modules 不得为空".into());
}
let mut ids = HashSet::new();
let mut all_units: HashMap<&str, &AnalysisUnit> = HashMap::new();
let mut all_functions: HashMap<&str, &AnalysisFunction> = HashMap::new();
for module in &wire.modules {
if !ids.insert(module.id.as_str()) {
return Err(format!("Analysis 模块身份重复:{}", module.id));
}
let (units, functions) = validate_module_base(module, &wire.project)?;
for (id, unit) in units {
if all_units.insert(id, unit).is_some() {
return Err(format!("Analysis unit.id 跨模块重复:{id}"));
}
}
for (id, function) in functions {
if all_functions.insert(id, function).is_some() {
return Err(format!("Analysis function.id 跨模块重复:{id}"));
}
}
}
for module in &wire.modules {
validate_module_relations(module, &wire.project, &ids, &all_units, &all_functions)?;
}
let entry_count = wire
.modules
.iter()
.filter(|module| module.id == wire.project.entry_module_id)
.count();
if entry_count != 1 {
return Err(format!(
"project.entry_module_id 必须在 modules 中恰好出现一次,实际 {entry_count} 次"
));
}
if wire
.diagnostics
.iter()
.any(|diagnostic| diagnostic.severity == "error")
{
return Err("成功 Analysis 不得包含 error 级诊断".into());
}
Ok(())
}
fn validate_project(project: &AnalysisProject) -> Result<(), String> {
match project.identity_kind {
IdentityKind::Manifest => {
if !project.root_id.starts_with("root:") || project.root_id.len() <= 5 {
return Err(
"manifest 项目的 project.root_id 必须形如 root:<name>@<version>".into(),
);
}
}
IdentityKind::WorkspaceSnapshot => {
if !is_sha256(&project.root_id) {
return Err(
"workspace_snapshot 项目的 project.root_id 必须是 sha256:<64 hex>".into(),
);
}
}
}
if project.entry_module_id.trim().is_empty() {
return Err("project.entry_module_id 不得为空".into());
}
validate_captured_digest(&project.lock_digest, "project.lock_digest")?;
validate_captured_digest(&project.manifest_digest, "project.manifest_digest")?;
if let Some(stdlib) = &project.stdlib {
if stdlib.version.trim().is_empty() || stdlib.instance_id.trim().is_empty() {
return Err("project.stdlib 的 version/instance_id 不得为空".into());
}
if !is_sha256(&stdlib.digest) {
return Err("project.stdlib.digest 必须是 sha256:<64 hex>".into());
}
}
let mut extension_keys = Vec::new();
for extension in &project.extensions {
if !matches!(extension.kind.as_str(), "plugin" | "kernel" | "provider") {
return Err("project.extensions[].kind 必须是 plugin/kernel/provider".into());
}
for (name, value) in [
("name", extension.name.as_str()),
("version", extension.version.as_str()),
("logical_owner", extension.logical_owner.as_str()),
("source", extension.source.as_str()),
("selected_target", extension.selected_target.as_str()),
] {
if value.trim().is_empty() {
return Err(format!("project.extensions[].{name} 不得为空"));
}
}
if !is_sha256(&extension.manifest_digest) || !is_sha256(&extension.artifact_digest) {
return Err("project.extensions[].*_digest 必须是 sha256:<64 hex>".into());
}
extension_keys.push((
extension.kind.clone(),
extension.name.clone(),
extension.logical_owner.clone(),
extension.manifest_digest.clone(),
));
}
if extension_keys.windows(2).any(|pair| pair[0] > pair[1]) {
return Err(
"project.extensions 必须按 (kind,name,logical_owner,manifest_digest) 排序".into(),
);
}
Ok(())
}
fn validate_captured_digest(digest: &str, field: &str) -> Result<(), String> {
if digest.is_empty() || is_sha256(digest) {
Ok(())
} else {
Err(format!("{field} 必须是空字符串或 sha256:<64 hex>"))
}
}
type UnitMap<'a> = HashMap<&'a str, &'a AnalysisUnit>;
type FunctionMap<'a> = HashMap<&'a str, &'a AnalysisFunction>;
fn validate_module_base<'a>(
module: &'a AnalysisModule,
project: &AnalysisProject,
) -> Result<(UnitMap<'a>, FunctionMap<'a>), String> {
if module.id != format!("{}::{}", module.package_instance_id, module.relative_path) {
return Err(format!(
"模块 id 必须等于 package_instance_id::relative_path:{}",
module.id
));
}
validate_relative_path(&module.relative_path)?;
if !is_lower_hex_64(&module.source_digest) {
return Err(format!(
"模块 {} 的 source_digest 必须是 64 位小写十六进制",
module.id
));
}
let actual = format!("{:x}", Sha256::digest(module.source.as_bytes()));
if actual != module.source_digest {
return Err(format!(
"模块 {} 的 sha256(source) 与 source_digest 不一致;{PROTOCOL_REGEN_HINT}",
module.id
));
}
let source_len = module.source.len();
validate_span_boundaries(
&serde_json::to_value(module).map_err(|error| error.to_string())?,
&module.source,
)
.map_err(|error| format!("模块 {}:{error}", module.id))?;
validate_document(&module.document, source_len, &module.id)?;
let units = validate_units(module, source_len)?;
validate_anchors(&module.anchors, &units)?;
let functions = validate_functions(&module.functions, &units, source_len)?;
validate_imports(&module.imports, &module.id, source_len)?;
let _ = project;
Ok((units, functions))
}
fn validate_module_relations(
module: &AnalysisModule,
project: &AnalysisProject,
module_ids: &HashSet<&str>,
all_units: &HashMap<&str, &AnalysisUnit>,
all_functions: &HashMap<&str, &AnalysisFunction>,
) -> Result<(), String> {
let current_units = module
.units
.iter()
.map(|unit| (unit.id.as_str(), unit))
.collect::<HashMap<_, _>>();
let source_len = module.source.len();
validate_references(
module,
&current_units,
all_units,
all_functions,
module_ids,
source_len,
)?;
validate_calls(&module.calls, all_functions, source_len)?;
validate_resources(module, &current_units, &module.document, source_len)?;
let _ = project;
Ok(())
}
fn validate_span_boundaries(value: &Value, source: &str) -> Result<(), String> {
validate_span_boundaries_at(value, source, "$")
}
fn validate_span_boundaries_at(value: &Value, source: &str, path: &str) -> Result<(), String> {
match value {
Value::Object(fields) => {
for key in ["span", "heading_span", "condition_span", "key_span"] {
if let Some(span) = fields.get(key) {
if span.is_null() {
continue;
}
// rc.4 stdlib still emits some parameter spans relative to a
// different projection; parameter spans are presentation-only
// and are not used for rule alignment.
if key == "span" && path.contains(".signature.params") {
continue;
}
let span = span_from_value(span, key)?;
if span.start > source.len()
|| span.end > source.len()
|| !source.is_char_boundary(span.start)
|| !source.is_char_boundary(span.end)
{
return Err(format!(
"{path}.{key} [{}, {}) 不在 UTF-8 字符边界或超出源码长度",
span.start, span.end
));
}
}
}
for (key, child) in fields {
validate_span_boundaries_at(child, source, &format!("{path}.{key}"))?;
}
}
Value::Array(values) => {
for (index, child) in values.iter().enumerate() {
validate_span_boundaries_at(child, source, &format!("{path}[{index}]"))?;
}
}
_ => {}
}
Ok(())
}
fn validate_relative_path(path: &str) -> Result<(), String> {
if path.is_empty()
|| path.starts_with('/')
|| path.contains('\\')
|| path.contains("//")
|| path.as_bytes().get(1) == Some(&b':')
{
return Err(format!("模块 relative_path 不安全:{path:?}"));
}
for segment in path.split('/') {
if segment.is_empty() || segment == "." || segment == ".." {
return Err(format!("模块 relative_path 含空、. 或 .. 段:{path:?}"));
}
}
Ok(())
}
fn validate_units(module: &AnalysisModule, source_len: usize) -> Result<UnitMap<'_>, String> {
if module.units.is_empty() {
return Err(format!("模块 {} 缺少 units", module.id));
}
let mut by_id = HashMap::new();
for unit in &module.units {
if unit.id.is_empty() {
return Err("unit.id 不得为空".into());
}
if by_id.insert(unit.id.as_str(), unit).is_some() {
return Err(format!("unit.id 重复:{}", unit.id));
}
unit.span.validate(source_len)?;
if let Some(span) = unit.heading_span {
span.validate(source_len)?;
if !unit.span.contains(span) {
return Err(format!(
"unit {} 的 heading_span 不在完整 section span 内",
unit.id
));
}
}
if unit.mode_source_unit_id.is_empty() {
return Err(format!("unit {} 缺少 mode_source_unit_id", unit.id));
}
}
let roots: Vec<_> = module
.units
.iter()
.filter(|unit| unit.kind == UnitKind::Root)
.collect();
if roots.len() != 1 {
return Err("每个模块必须恰好有一个 root unit".into());
}
let root = roots[0];
if root.parent_id.is_some()
|| root.kind != UnitKind::Root
|| root.level != 0
|| !root.path.is_empty()
|| !root.name.is_empty()
|| root.mode != HeadingMode::Knowledge
|| root.mode_origin != ModeOrigin::Default
|| root.heading_span.is_some()
|| root.function.is_some()
{
return Err("root unit 的身份字段无效".into());
}
if root.span.start != 0 || root.span.end != source_len {
return Err("root unit 的 span 必须覆盖整个 artifact source".into());
}
let mut ancestors = HashSet::new();
for unit in &module.units {
if unit.kind == UnitKind::Root {
continue;
}
let parent_id = unit
.parent_id
.as_deref()
.ok_or_else(|| format!("非 root unit {} 缺少 parent_id", unit.id))?;
let parent = *by_id
.get(parent_id)
.ok_or_else(|| format!("unit {} 的 parent_id 不存在", unit.id))?;
if unit.path.len() != parent.path.len() + 1
|| unit
.path
.iter()
.zip(&parent.path)
.any(|(left, right)| left != right)
|| unit.path.last() != Some(&unit.name)
{
return Err(format!("unit {} 的 path/name 与 parent 不一致", unit.id));
}
if !parent.span.contains(unit.span) {
return Err(format!("unit {} 的 span 未嵌套在 parent span 内", unit.id));
}
match unit.kind {
UnitKind::Function if unit.mode != HeadingMode::Exec => {
return Err(format!(
"Exec function unit {} 的 mode 必须是 exec",
unit.id
));
}
UnitKind::Knowledge if unit.mode != HeadingMode::Knowledge => {
return Err(format!(
"Knowledge unit {} 的 mode 必须是 knowledge",
unit.id
));
}
UnitKind::Namespace | UnitKind::Section | UnitKind::Root => {}
_ => {}
}
if unit.kind == UnitKind::Function {
if unit.level != 2 {
return Err(format!("Exec function unit {} 必须是 H2", unit.id));
}
if unit.function.as_deref().is_none_or(str::is_empty) {
return Err(format!("function unit {} 必须指向可调用函数", unit.id));
}
} else if unit.kind == UnitKind::Knowledge {
if unit.level != 2 || unit.function.is_some() {
return Err(format!("Knowledge unit {} 身份无效", unit.id));
}
} else if unit.kind == UnitKind::Namespace {
if unit.level != 1 || unit.function.is_some() {
return Err(format!("namespace unit {} 身份无效", unit.id));
}
} else if unit.kind == UnitKind::Section && unit.level < 3 {
return Err(format!("section unit {} 必须是 H3+", unit.id));
}
let mode_source = *by_id
.get(unit.mode_source_unit_id.as_str())
.ok_or_else(|| format!("unit {} 的 mode_source_unit_id 不存在", unit.id))?;
let mut cursor = Some(unit);
let mut found = false;
while let Some(current) = cursor {
if current.id == mode_source.id {
found = true;
break;
}
cursor = current
.parent_id
.as_deref()
.and_then(|id| by_id.get(id).copied());
}
if !found {
return Err(format!(
"unit {} 的 mode_source_unit_id 不是自身或祖先",
unit.id
));
}
ancestors.insert(unit.id.as_str());
}
for unit in &module.units {
let mut seen = HashSet::new();
let mut cursor = Some(unit);
while let Some(current) = cursor {
if !seen.insert(current.id.as_str()) {
return Err(format!("unit {} 的 parent 链存在循环", unit.id));
}
cursor = current
.parent_id
.as_deref()
.and_then(|id| by_id.get(id).copied());
}
}
Ok(by_id)
}
fn validate_anchors(
anchors: &[AnalysisAnchor],
units: &HashMap<&str, &AnalysisUnit>,
) -> Result<(), String> {
let mut seen = HashSet::new();
let mut previous: Option<&str> = None;
for anchor in anchors {
if anchor.anchor.trim().is_empty() || !seen.insert(anchor.anchor.as_str()) {
return Err("anchor 不得为空或重复".into());
}
if !units.contains_key(anchor.unit_id.as_str()) {
return Err(format!("anchor {} 指向不存在的 unit", anchor.anchor));
}
if previous.is_some_and(|previous| previous > anchor.anchor.as_str()) {
return Err("anchors 必须按 anchor 排序".into());
}
previous = Some(anchor.anchor.as_str());
}
Ok(())
}
fn validate_functions<'a>(
functions: &'a [AnalysisFunction],
units: &HashMap<&str, &AnalysisUnit>,
source_len: usize,
) -> Result<HashMap<&'a str, &'a AnalysisFunction>, String> {
let mut by_id = HashMap::new();
for function in functions {
if function.id.trim().is_empty() || by_id.insert(function.id.as_str(), function).is_some() {
return Err(format!("function.id 不得为空或重复:{}", function.id));
}
let unit = *units
.get(function.unit_id.as_str())
.ok_or_else(|| format!("function {} 的 unit_id 不存在", function.id))?;
if unit.kind != UnitKind::Function || unit.function.as_deref() != Some(function.id.as_str())
{
return Err(format!("function {} 未对应 Exec H2 unit", function.id));
}
if unit.heading_span != Some(function.heading_span) {
return Err(format!(
"function {} 的 heading_span 与 unit 不一致",
function.id
));
}
if !unit.span.contains(function.span) {
return Err(format!("function {} 的 span 不在 unit 内", function.id));
}
function.span.validate(source_len)?;
function.heading_span.validate(source_len)?;
if function.local_name.trim().is_empty() {
return Err(format!("function {} 缺少 local_name", function.id));
}
if function.effects.iter().any(|effect| effect != "unknown") {
return Err(format!(
"function {} 的 effects 只允许 unknown",
function.id
));
}
for param in &function.signature.params {
if param.name.trim().is_empty() {
return Err(format!("function {} 的 param.name 不得为空", function.id));
}
param.span.validate(source_len)?;
if let Some(default) = &param.default {
validate_expression(default, source_len)?;
}
}
validate_body(&function.body, source_len)?;
}
for unit in units
.values()
.filter(|unit| unit.kind == UnitKind::Function)
{
if !by_id.contains_key(unit.function.as_deref().unwrap_or_default()) {
return Err(format!("Exec unit {} 缺少对应 function", unit.id));
}
}
Ok(by_id)
}
fn validate_imports(
imports: &[AnalysisImport],
module_id: &str,
source_len: usize,
) -> Result<(), String> {
for import in imports {
if import.alias.trim().is_empty() || import.target.trim().is_empty() {
return Err(format!("模块 {module_id} 存在空 import alias/target"));
}
import.span.validate(source_len)?;
}
Ok(())
}
fn validate_references(
module: &AnalysisModule,
current_units: &HashMap<&str, &AnalysisUnit>,
all_units: &HashMap<&str, &AnalysisUnit>,
all_functions: &HashMap<&str, &AnalysisFunction>,
module_ids: &HashSet<&str>,
source_len: usize,
) -> Result<(), String> {
for reference in &module.references {
if reference.source != module.id {
return Err(format!("reference.source 必须是当前模块 {}", module.id));
}
let source_unit = *current_units
.get(reference.source_unit.as_str())
.ok_or_else(|| format!("reference.source_unit 不存在:{}", reference.source_unit))?;
reference.span.validate(source_len)?;
let innermost = innermost_unit(module, reference.span, current_units);
if innermost.is_none_or(|unit| unit.id != source_unit.id) {
return Err(format!(
"reference.source_unit 不是包含 span 的最内层 unit:{}",
reference.source_unit
));
}
match reference.state {
ReferenceState::Resolved => {
let kind = reference.target_kind.ok_or_else(|| {
format!("resolved reference {} 缺少 target_kind", reference.url)
})?;
match kind {
ReferenceTargetKind::Module => {
let target = reference.target_module.as_deref().ok_or_else(|| {
format!(
"resolved module reference {} 缺少 target_module",
reference.url
)
})?;
if !module_ids.contains(target) {
return Err(format!(
"resolved reference 的 target_module 不在 modules 集:{target}"
));
}
}
ReferenceTargetKind::File => {}
}
if let Some(target_unit) = &reference.target_unit {
if !all_units.contains_key(target_unit.as_str()) {
return Err(format!("reference target_unit 不存在:{target_unit}"));
}
}
}
ReferenceState::NotLoaded => {
if reference.target_unit.is_some() {
return Err("not_loaded reference 的 target_unit 必须为 null".into());
}
if reference.target_kind.is_some() {
return Err("not_loaded reference 的 target_kind 必须为 null".into());
}
}
ReferenceState::Missing => {
if reference.target_unit.is_some() {
return Err("missing reference 的 target_unit 必须为 null".into());
}
}
ReferenceState::Ambiguous => {
if reference.target_unit.is_some()
|| reference.target_kind.is_some()
|| reference.candidates.len() < 2
{
return Err(
"ambiguous reference 必须列出至少两个 candidates 且 target_unit/target_kind 为 null"
.into(),
);
}
}
ReferenceState::External => {
if reference.target_kind.is_some()
|| reference.target_module.is_some()
|| reference.target_unit.is_some()
{
return Err("external reference 的目标字段必须为 null".into());
}
}
ReferenceState::OutsideScope | ReferenceState::Invalid => {
if reference.target_unit.is_some() {
return Err("outside_scope/invalid reference 的 target_unit 必须为 null".into());
}
}
}
if reference.state != ReferenceState::Ambiguous && !reference.candidates.is_empty() {
return Err(format!(
"只有 ambiguous reference 才能携带 candidates:{}",
reference.url
));
}
if let Some(function_id) = source_unit.function.as_deref() {
if !all_functions.contains_key(function_id) {
return Err(format!("reference 所属 function 不存在:{function_id}"));
}
}
}
Ok(())
}
fn innermost_unit<'a>(
_module: &'a AnalysisModule,
span: Span,
units: &HashMap<&'a str, &'a AnalysisUnit>,
) -> Option<&'a AnalysisUnit> {
units
.values()
.copied()
.filter(|unit| unit.span.contains(span))
.max_by_key(|unit| (unit.path.len(), usize::MAX - unit.span.start))
}
fn validate_calls(
calls: &[AnalysisCall],
functions: &HashMap<&str, &AnalysisFunction>,
source_len: usize,
) -> Result<(), String> {
for call in calls {
if !functions.contains_key(call.function.as_str()) {
return Err(format!("call.function 不存在:{}", call.function));
}
call.span.validate(source_len)?;
validate_callee(&call.callee)?;
match call.state {
CallState::Function => {
if call.target_kind != Some(CallTargetKind::Function)
|| call.target.is_none()
|| call.target_owner.is_some()
{
return Err("function call 的 target/target_kind/target_owner 不一致".into());
}
if !functions.contains_key(call.target.as_deref().unwrap_or_default()) {
return Err(format!(
"resolved function call 指向不存在的函数:{:?}",
call.target
));
}
if call.reason.is_some() {
return Err("已绑定 function call 的 reason 必须为 null".into());
}
}
CallState::Builtin => {
if call.target_kind != Some(CallTargetKind::Builtin)
|| call.target.as_deref().is_none_or(str::is_empty)
{
return Err("builtin call 的 target/target_kind 不一致".into());
}
if call.reason.is_some() || call.target_owner.is_some() {
return Err("builtin call 不得携带 reason/target_owner".into());
}
}
CallState::Plugin => {
if call.target_kind != Some(CallTargetKind::Plugin)
|| call.target.as_deref().is_none_or(str::is_empty)
{
return Err("plugin call 的 target/target_kind 不一致".into());
}
let owner = call
.target_owner
.as_ref()
.ok_or_else(|| "plugin call 缺少 target_owner".to_string())?;
if owner.kind != "plugin"
|| owner.package.trim().is_empty()
|| !is_sha256(&owner.digest)
{
return Err("plugin call 的 target_owner 无效".into());
}
if call.reason.is_some() {
return Err("plugin call 的 reason 必须为 null".into());
}
}
CallState::Unresolved => {
if call.target.is_some() || call.target_kind.is_some() {
return Err("unresolved call 的 target/target_kind 必须为 null".into());
}
if call.reason.is_none() {
return Err("unresolved call 必须说明 dynamic/unbound reason".into());
}
}
}
}
Ok(())
}
fn validate_callee(callee: &Value) -> Result<(), String> {
let object = as_object(callee, "call.callee")?;
match object.get("kind").and_then(Value::as_str) {
Some("ident") => {
check_keys(object, &["kind", "name"], "call.callee.ident")?;
require_str(object, "name", "call.callee.ident")?;
}
Some("member") => {
check_keys(object, &["kind", "base", "field"], "call.callee.member")?;
let base = object
.get("base")
.ok_or_else(|| "call.callee.member 缺少 base".to_string())?;
validate_callee(base)?;
require_str(object, "field", "call.callee.member")?;
}
Some("expression") => {
check_keys(object, &["kind", "span"], "call.callee.expression")?;
let span = object
.get("span")
.ok_or_else(|| "call.callee.expression 缺少 span".to_string())?;
span_from_value(span, "call.callee.expression.span")?;
}
_ => return Err("call.callee.kind 无效".into()),
}
Ok(())
}
fn validate_resources(
module: &AnalysisModule,
units: &HashMap<&str, &AnalysisUnit>,
document: &Value,
source_len: usize,
) -> Result<(), String> {
let mut payloads = HashMap::new();
collect_resource_payloads(document, &mut payloads)?;
let mut ids = HashSet::new();
for resource in &module.resources {
if !ids.insert(resource.id.as_str()) {
return Err(format!("resource.id 重复:{}", resource.id));
}
if !resource.id.starts_with(&format!("{}#resource:", module.id)) {
return Err(format!("resource.id 不属于当前模块:{}", resource.id));
}
if resource.module_id != module.id {
return Err(format!("resource.module_id 与模块不一致:{}", resource.id));
}
if !units.contains_key(resource.unit_id.as_str()) {
return Err(format!("resource.unit_id 不存在:{}", resource.unit_id));
}
resource.span.validate(source_len)?;
let unit = units[resource.unit_id.as_str()];
if !unit.span.contains(resource.span) {
return Err(format!("resource {} 的 span 不在 unit 内", resource.id));
}
if !is_lower_hex_64(&resource.content_digest) {
return Err(format!(
"resource {} 的 content_digest 必须是 64 位小写十六进制",
resource.id
));
}
let payload = payloads.get(&resource.span).ok_or_else(|| {
format!(
"resource {} 的 span 未对应可验证的 AST literal",
resource.id
)
})?;
let expected = format!("{:x}", Sha256::digest(payload.as_bytes()));
if expected != resource.content_digest {
return Err(format!(
"resource {} 的 content_digest 与 AST literal 不一致",
resource.id
));
}
match resource.kind {
ResourceKind::Formula => {
if resource.display.is_none() || resource.language.is_some() {
return Err(format!(
"formula resource {} 必须 display 为 bool 且 language 为 null",
resource.id
));
}
}
ResourceKind::Code => {
if resource.display.is_some() {
return Err(format!(
"code resource {} 的 display 必须为 null",
resource.id
));
}
}
}
}
Ok(())
}
fn collect_resource_payloads(
node: &Value,
payloads: &mut HashMap<Span, String>,
) -> Result<(), String> {
let object = as_object(node, "document node")?;
let kind = object
.get("kind")
.and_then(Value::as_str)
.ok_or_else(|| "document node 缺少 kind".to_string())?;
let span = span_from_value(
object
.get("span")
.ok_or_else(|| "document node 缺少 span".to_string())?,
"document node.span",
)?;
if matches!(kind, "math" | "math_block" | "code_block") {
if let Some(literal) = object.get("literal").and_then(Value::as_str) {
payloads.insert(span, literal.to_string());
}
}
let children = object
.get("children")
.and_then(Value::as_array)
.ok_or_else(|| "document node 的 children 必须是数组".to_string())?;
for child in children {
collect_resource_payloads(child, payloads)?;
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StatementKind {
Assign,
Expression,
Branch,
Loop,
Return,
Break,
Continue,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Statement<'a> {
pub kind: StatementKind,
pub span: Span,
pub value: &'a Value,
}
impl<'a> Statement<'a> {
pub fn read(value: &'a Value) -> Result<Self, String> {
let object = as_object(value, "statement")?;
let kind = match object.get("kind").and_then(Value::as_str) {
Some("assign") => StatementKind::Assign,
Some("expression") => StatementKind::Expression,
Some("branch") => StatementKind::Branch,
Some("loop") => StatementKind::Loop,
Some("return") => StatementKind::Return,
Some("break") => StatementKind::Break,
Some("continue") => StatementKind::Continue,
kind => return Err(format!("未知 Analysis 语句种类 {kind:?}")),
};
let span = node_span(value).ok_or_else(|| format!("{kind:?} 的 span 无效"))?;
Ok(Self { kind, span, value })
}
pub fn child_bodies(self) -> impl Iterator<Item = &'a [Value]> {
let arms = (self.kind == StatementKind::Branch)
.then(|| self.value["arms"].as_array())
.flatten();
let loop_body = (self.kind == StatementKind::Loop)
.then(|| body(self.value))
.flatten();
loop_body
.into_iter()
.chain(arms.into_iter().flatten().filter_map(body))
}
}
pub(crate) fn body(value: &Value) -> Option<&[Value]> {
value["body"].as_array().map(Vec::as_slice)
}
pub(crate) fn span_value(value: &Value) -> Option<Span> {
let start = usize::try_from(value["start"].as_u64()?).ok()?;
let end = usize::try_from(value["end"].as_u64()?).ok()?;
(start <= end).then_some(Span::new(start, end))
}
pub fn node_span(node: &Value) -> Option<Span> {
span_value(&node["span"])
}
fn validate_body(nodes: &[Value], source_len: usize) -> Result<(), String> {
for node in nodes {
validate_statement(node, source_len)?;
}
Ok(())
}
fn validate_statement(node: &Value, source_len: usize) -> Result<(), String> {
let statement = Statement::read(node)?;
statement.span.validate(source_len)?;
let object = as_object(node, "statement")?;
match statement.kind {
StatementKind::Assign => {
check_keys(object, &["kind", "target", "value", "span"], "assign")?;
validate_place(
object
.get("target")
.ok_or_else(|| "assign 缺少 target".to_string())?,
source_len,
)?;
validate_expression(
object
.get("value")
.ok_or_else(|| "assign 缺少 value".to_string())?,
source_len,
)?;
}
StatementKind::Expression | StatementKind::Return => {
check_keys(object, &["kind", "value", "span"], "expression/return")?;
validate_expression(
object
.get("value")
.ok_or_else(|| "语句缺少 value".to_string())?,
source_len,
)?;
}
StatementKind::Branch => {
check_keys(object, &["kind", "arms", "span"], "branch")?;
let arms = object
.get("arms")
.and_then(Value::as_array)
.filter(|arms| !arms.is_empty())
.ok_or_else(|| "branch 的 arms 必须是非空数组".to_string())?;
for arm in arms {
let arm = as_object(arm, "branch arm")?;
check_keys(
arm,
&["condition", "condition_span", "body", "span"],
"branch arm",
)?;
span_from_value(
arm.get("span")
.ok_or_else(|| "branch arm 缺少 span".to_string())?,
"branch arm.span",
)?
.validate(source_len)?;
span_from_value(
arm.get("condition_span")
.ok_or_else(|| "branch arm 缺少 condition_span".to_string())?,
"branch arm.condition_span",
)?
.validate(source_len)?;
validate_expression(
arm.get("condition")
.ok_or_else(|| "branch arm 缺少 condition".to_string())?,
source_len,
)?;
let body = arm
.get("body")
.and_then(Value::as_array)
.ok_or_else(|| "branch arm 的 body 必须是数组".to_string())?;
validate_body(body, source_len)?;
}
}
StatementKind::Loop => {
check_keys(
object,
&["kind", "condition", "condition_span", "body", "span"],
"loop",
)?;
span_from_value(
object
.get("condition_span")
.ok_or_else(|| "loop 缺少 condition_span".to_string())?,
"loop.condition_span",
)?
.validate(source_len)?;
validate_expression(
object
.get("condition")
.ok_or_else(|| "loop 缺少 condition".to_string())?,
source_len,
)?;
let body = object
.get("body")
.and_then(Value::as_array)
.ok_or_else(|| "loop 的 body 必须是数组".to_string())?;
validate_body(body, source_len)?;
}
StatementKind::Break | StatementKind::Continue => {
check_keys(object, &["kind", "span"], "jump")?;
}
}
Ok(())
}
fn validate_place(value: &Value, source_len: usize) -> Result<(), String> {
if value.is_string() {
return Ok(());
}
let object = as_object(value, "assign.target")?;
check_keys(
object,
&["kind", "base", "index", "span"],
"assign.target.index",
)?;
if object.get("kind").and_then(Value::as_str) != Some("index") {
return Err("assign.target.kind 必须是 index".into());
}
span_from_value(
object
.get("span")
.ok_or_else(|| "assign.target 缺少 span".to_string())?,
"assign.target.span",
)?
.validate(source_len)?;
validate_expression(
object
.get("base")
.ok_or_else(|| "assign.target 缺少 base".to_string())?,
source_len,
)?;
validate_expression(
object
.get("index")
.ok_or_else(|| "assign.target 缺少 index".to_string())?,
source_len,
)
}
fn validate_expression(value: &Value, source_len: usize) -> Result<(), String> {
let object = as_object(value, "expression")?;
let kind = object
.get("kind")
.and_then(Value::as_str)
.ok_or_else(|| "expression 缺少 kind".to_string())?;
let span = span_from_value(
object
.get("span")
.ok_or_else(|| "expression 缺少 span".to_string())?,
"expression.span",
)?;
span.validate(source_len)?;
match kind {
"literal" => {
check_keys(object, &["kind", "type", "value", "span"], "literal")?;
let literal_type = object
.get("type")
.and_then(Value::as_str)
.ok_or_else(|| "literal 缺少 type".to_string())?;
match literal_type {
"int" => {
let text = object
.get("value")
.and_then(Value::as_str)
.ok_or_else(|| "int literal 的 value 必须是字符串".to_string())?;
if text.is_empty()
|| !text
.trim_start_matches('-')
.bytes()
.all(|byte| byte.is_ascii_digit())
{
return Err("int literal 的 value 不是十进制整数".into());
}
}
"float" => {
if !object.get("value").is_some_and(Value::is_number) {
return Err("float literal 的 value 必须是有限 JSON number".into());
}
}
"text" => {
object
.get("value")
.and_then(Value::as_str)
.ok_or_else(|| "text literal 的 value 必须是字符串".to_string())?;
}
"bool" => {
object
.get("value")
.and_then(Value::as_bool)
.ok_or_else(|| "bool literal 的 value 必须是布尔值".to_string())?;
}
"none" => {
if object.contains_key("value") {
return Err("none literal 不得携带 value".into());
}
}
_ => return Err("literal.type 无效".into()),
}
}
"variable" => {
check_keys(object, &["kind", "name", "span"], "variable")?;
require_str(object, "name", "variable")?;
}
"list" => {
check_keys(object, &["kind", "items", "span"], "list expression")?;
for item in object
.get("items")
.and_then(Value::as_array)
.ok_or_else(|| "list expression 缺少 items 数组".to_string())?
{
validate_expression(item, source_len)?;
}
}
"record" => {
check_keys(object, &["kind", "entries", "span"], "record expression")?;
for entry in object
.get("entries")
.and_then(Value::as_array)
.ok_or_else(|| "record expression 缺少 entries 数组".to_string())?
{
let entry = as_object(entry, "record entry")?;
check_keys(entry, &["key", "key_span", "value"], "record entry")?;
require_str(entry, "key", "record entry")?;
span_from_value(
entry
.get("key_span")
.ok_or_else(|| "record entry 缺少 key_span".to_string())?,
"record entry.key_span",
)?
.validate(source_len)?;
validate_expression(
entry
.get("value")
.ok_or_else(|| "record entry 缺少 value".to_string())?,
source_len,
)?;
}
}
"unary" => {
check_keys(object, &["kind", "op", "operand", "span"], "unary")?;
if !matches!(
object.get("op").and_then(Value::as_str),
Some("not" | "neg" | "pos")
) {
return Err("unary.op 无效".into());
}
validate_expression(
object
.get("operand")
.ok_or_else(|| "unary 缺少 operand".to_string())?,
source_len,
)?;
}
"binary" => {
check_keys(object, &["kind", "op", "left", "right", "span"], "binary")?;
if !matches!(
object.get("op").and_then(Value::as_str),
Some(
"or" | "and"
| "eq"
| "ne"
| "lt"
| "le"
| "gt"
| "ge"
| "add"
| "sub"
| "mul"
| "div"
| "floor_div"
| "mod"
| "pow"
)
) {
return Err("binary.op 无效".into());
}
validate_expression(
object
.get("left")
.ok_or_else(|| "binary 缺少 left".to_string())?,
source_len,
)?;
validate_expression(
object
.get("right")
.ok_or_else(|| "binary 缺少 right".to_string())?,
source_len,
)?;
}
"member" => {
check_keys(object, &["kind", "base", "field", "span"], "member")?;
validate_expression(
object
.get("base")
.ok_or_else(|| "member 缺少 base".to_string())?,
source_len,
)?;
require_str(object, "field", "member")?;
}
"index" => {
check_keys(object, &["kind", "base", "index", "span"], "index")?;
validate_expression(
object
.get("base")
.ok_or_else(|| "index 缺少 base".to_string())?,
source_len,
)?;
validate_expression(
object
.get("index")
.ok_or_else(|| "index 缺少 index".to_string())?,
source_len,
)?;
}
"call" => {
check_keys(
object,
&["kind", "callee", "args", "span"],
"call expression",
)?;
let callee = object
.get("callee")
.and_then(Value::as_object)
.ok_or_else(|| "call expression 缺少 callee 对象".to_string())?;
match callee.get("kind").and_then(Value::as_str) {
Some("variable") => {
check_keys(callee, &["kind", "name", "span"], "call callee")?;
require_str(callee, "name", "call callee")?;
}
Some("member") => {
check_keys(callee, &["kind", "base", "field", "span"], "call callee")?;
validate_expression(
callee
.get("base")
.ok_or_else(|| "call callee 缺少 base".to_string())?,
source_len,
)?;
require_str(callee, "field", "call callee")?;
}
_ => return Err("call expression 的 callee 形状无效".into()),
}
for arg in object
.get("args")
.and_then(Value::as_array)
.ok_or_else(|| "call expression 缺少 args 数组".to_string())?
{
let arg = as_object(arg, "call arg")?;
check_keys(arg, &["name", "value", "span"], "call arg")?;
if let Some(name) = arg.get("name") {
if !name.is_null() && name.as_str().is_none_or(str::is_empty) {
return Err("call arg.name 必须是非空字符串或 null".into());
}
}
span_from_value(
arg.get("span")
.ok_or_else(|| "call arg 缺少 span".to_string())?,
"call arg.span",
)?
.validate(source_len)?;
validate_expression(
arg.get("value")
.ok_or_else(|| "call arg 缺少 value".to_string())?,
source_len,
)?;
}
}
_ => return Err(format!("未知 expression.kind {kind:?}")),
}
Ok(())
}
fn validate_document(node: &Value, source_len: usize, module_id: &str) -> Result<(), String> {
let object = as_object(node, "document")?;
if object.get("kind").and_then(Value::as_str) != Some("document") {
return Err(format!("模块 {module_id} 的 document 根节点不是 document"));
}
validate_document_node(node, source_len)
}
fn validate_document_node(node: &Value, source_len: usize) -> Result<(), String> {
let object = as_object(node, "document node")?;
let kind = object
.get("kind")
.and_then(Value::as_str)
.ok_or_else(|| "document node 缺少 kind".to_string())?;
let span = span_from_value(
object
.get("span")
.ok_or_else(|| "document node 缺少 span".to_string())?,
"document node.span",
)?;
span.validate(source_len)?;
let children = object
.get("children")
.and_then(Value::as_array)
.ok_or_else(|| "document node 的 children 必须是数组".to_string())?;
let children_allowed = !matches!(
kind,
"text"
| "front_matter"
| "code"
| "code_block"
| "math"
| "math_block"
| "html_block"
| "html_inline"
| "thematic_break"
| "soft_break"
| "line_break"
);
if !children_allowed && !children.is_empty() {
return Err(format!("{kind} 节点不得有 children"));
}
let allowed: &[&str] = match kind {
"document" | "block_quote" | "paragraph" | "strong" | "emph" | "strikethrough"
| "table_cell" | "thematic_break" | "soft_break" | "line_break" => {
&["kind", "span", "children"]
}
"front_matter" | "text" | "math_block" | "html_block" | "html_inline" => {
&["kind", "span", "children", "literal"]
}
"list" => &["kind", "span", "children", "ordered", "start", "tight"],
"item" => &["kind", "span", "children", "task"],
"heading" => &["kind", "span", "children", "level", "setext"],
"code" => &["kind", "span", "children", "literal", "ticks"],
"code_block" => &["kind", "span", "children", "literal", "fenced", "info"],
"math" => &["kind", "span", "children", "literal", "display"],
"link" | "image" => &["kind", "span", "children", "url", "title"],
"table" => &["kind", "span", "children", "alignments"],
"table_row" => &["kind", "span", "children", "header"],
"other" => &["kind", "span", "children", "tag", "literal"],
_ => return Err(format!("document node.kind 无效:{kind}")),
};
check_keys(object, allowed, "document node")?;
match kind {
"text" | "front_matter" | "math_block" | "html_block" | "html_inline" => {
require_str(object, "literal", "document node")?;
}
"code" => {
require_str(object, "literal", "document node")?;
if object.get("ticks").and_then(Value::as_u64).is_none() {
return Err("code 节点缺少 ticks".into());
}
}
"code_block" => {
require_str(object, "literal", "document node")?;
if object.get("fenced").and_then(Value::as_bool).is_none() {
return Err("code_block 节点缺少 fenced".into());
}
if !object.get("info").is_some_and(Value::is_string) {
return Err("code_block 节点缺少 info".into());
}
}
"math" => {
require_str(object, "literal", "document node")?;
if object.get("display").and_then(Value::as_bool).is_none() {
return Err("math 节点缺少 display".into());
}
}
"heading" => {
if !object
.get("level")
.and_then(Value::as_u64)
.is_some_and(|level| (1..=6).contains(&level))
{
return Err("heading 节点 level 无效".into());
}
if object.get("setext").and_then(Value::as_bool).is_none() {
return Err("heading 节点缺少 setext".into());
}
}
"list" => {
if object.get("ordered").and_then(Value::as_bool).is_none()
|| !object.contains_key("start")
|| object.get("tight").and_then(Value::as_bool).is_none()
{
return Err("list 节点必须包含 ordered/start/tight".into());
}
}
"item" => {
if !object.contains_key("task") {
return Err("item 节点缺少 task".into());
}
}
"link" | "image" => {
require_str(object, "url", "document node")?;
if !object.get("title").is_some_and(Value::is_string) {
return Err(format!("{kind} 节点缺少 title"));
}
}
"table" => {
if !object
.get("alignments")
.and_then(Value::as_array)
.is_some_and(|values| {
values.iter().all(|value| {
matches!(value.as_str(), Some("none" | "left" | "center" | "right"))
})
})
{
return Err("table 节点 alignments 无效".into());
}
}
"table_row" => {
if object.get("header").and_then(Value::as_bool).is_none() {
return Err("table_row 节点缺少 header".into());
}
}
"other" => {
require_str(object, "tag", "document node")?;
}
_ => {}
}
for child in children {
validate_document_node(child, source_len)?;
}
Ok(())
}
fn as_object<'a>(value: &'a Value, context: &str) -> Result<&'a Map<String, Value>, String> {
value
.as_object()
.ok_or_else(|| format!("{context} 必须是对象"))
}
fn check_keys(object: &Map<String, Value>, allowed: &[&str], context: &str) -> Result<(), String> {
for key in object.keys() {
if !allowed.contains(&key.as_str()) {
return Err(format!("{context} 含未定义字段 {key}"));
}
}
Ok(())
}
fn require_str(object: &Map<String, Value>, field: &str, context: &str) -> Result<String, String> {
object
.get(field)
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
.map(ToString::to_string)
.ok_or_else(|| format!("{context} 缺少非空字符串 {field}"))
}
fn span_from_value(value: &Value, context: &str) -> Result<Span, String> {
let object = as_object(value, context)?;
check_keys(object, &["start", "end"], context)?;
let start = object
.get("start")
.and_then(Value::as_u64)
.ok_or_else(|| format!("{context} 缺少 start"))?;
let end = object
.get("end")
.and_then(Value::as_u64)
.ok_or_else(|| format!("{context} 缺少 end"))?;
let start = usize::try_from(start).map_err(|_| format!("{context}.start 过大"))?;
let end = usize::try_from(end).map_err(|_| format!("{context}.end 过大"))?;
if start > end {
return Err(format!("{context} 是负区间"));
}
Ok(Span::new(start, end))
}
fn is_sha256(value: &str) -> bool {
value.strip_prefix("sha256:").is_some_and(is_lower_hex_64)
}
fn is_lower_hex_64(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
pub(crate) fn statements(nodes: &[Value]) -> impl Iterator<Item = Statement<'_>> {
nodes
.iter()
.filter_map(|node| Statement::read(node).ok())
.flat_map(walk_statement)
}
fn walk_statement(statement: Statement<'_>) -> Box<dyn Iterator<Item = Statement<'_>> + '_> {
Box::new(std::iter::once(statement).chain(statement.child_bodies().flat_map(statements)))
}
pub fn semantic_nodes(body: &[Value]) -> impl Iterator<Item = &Value> {
statements(body).map(|statement| statement.value)
}
impl AnalysisFunction {
pub(crate) fn validate_source_spans(&self, source: &SourceSnapshot) -> LintResult<()> {
source.slice(self.span)?;
source.slice(self.heading_span)?;
for statement in statements(&self.body) {
source.slice(statement.span)?;
if statement.kind == StatementKind::Loop {
validate_source_condition_span(statement.value, source)?;
}
if statement.kind == StatementKind::Branch {
for arm in statement.value["arms"].as_array().into_iter().flatten() {
if let Some(span) = node_span(arm) {
source.slice(span)?;
}
validate_source_condition_span(arm, source)?;
}
}
}
Ok(())
}
}
fn validate_source_condition_span(node: &Value, source: &SourceSnapshot) -> LintResult<()> {
if let Some(span) = span_value(&node["condition_span"]) {
source.slice(span)?;
}
Ok(())
}
/// Spans with external effects known from public bound targets or indexed writes.
pub(crate) fn effect_sites<'a>(
function: &'a AnalysisFunction,
calls: &'a [AnalysisCall],
) -> impl Iterator<Item = Span> + 'a {
let writes = statements(&function.body).filter(|statement| {
statement.kind == StatementKind::Assign && statement.value["target"]["kind"] == "index"
});
let external = calls.iter().filter(|call| {
call.function == function.id
&& match call.state {
CallState::Plugin => true,
CallState::Builtin => call.target.as_deref().is_some_and(|target| {
target.starts_with("resource.")
|| matches!(target, "foreign.call" | "foreign.run")
}),
CallState::Function => call.target.as_deref().is_some_and(|target| {
target.starts_with("std:marqdo-stdlib@")
&& (target.contains("::io.mq.md::io.")
|| target.contains("::io/stream.mq.md::stream.")
|| target.contains("::io/console.mq.md::console."))
}),
CallState::Unresolved => false,
}
});
writes
.map(|statement| statement.span)
.chain(external.map(|call| call.span))
}