feat: decode Analysis v2 and v3 through a shared statement view

This commit is contained in:
cflmy committed 2026-11-23 23:41:53 +08:00
1 parent 58cea75bab
commit bcd07a43af
13 files changed
+1622 -72

No files matched your search

+179 -25
View File
@@ -1,7 +1,8 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::Span;
use super::{SourceSnapshot, Span};
use crate::error::Result as LintResult;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Producer {
@@ -57,6 +58,7 @@ pub struct CoreDiagnostic {
#[derive(Debug, Clone)]
pub struct ExecutionProjection {
pub schema_version: u64,
pub producer: Producer,
pub project: Value,
pub modules: Vec<AnalysisModule>,
@@ -69,8 +71,17 @@ impl ExecutionProjection {
if raw.get("schema").and_then(Value::as_str) != Some("marqdo.analysis") {
return Err("Analysis schema 不是 marqdo.analysis".into());
}
if raw.get("schema_version").and_then(Value::as_u64) != Some(2) {
return Err("只支持 Analysis schema_version 2".into());
let schema_version = match raw.get("schema_version").and_then(Value::as_u64) {
Some(version @ (2 | 3)) => version,
version => {
return Err(format!(
"不支持的 Analysis schema_version {version:?},需要 2 或 3"
))
}
};
let profile = raw["producer"]["markdown_profile"].as_str();
if profile != Some("marqdo.md.v1") {
return Err(format!("不支持的 Markdown Profile {profile:?}"));
}
#[derive(Deserialize)]
struct Wire {
@@ -81,13 +92,17 @@ impl ExecutionProjection {
diagnostics: Vec<CoreDiagnostic>,
}
let wire: Wire = serde_json::from_value(raw.clone()).map_err(|error| error.to_string())?;
if wire.producer.markdown_profile != "marqdo.md.v1" {
return Err(format!(
"不支持的 Markdown Profile {}",
wire.producer.markdown_profile
));
if wire.project["root_id"].as_str().is_none_or(str::is_empty) {
return Err("Analysis project.root_id 必须是非空字符串".into());
}
let mut modules = std::collections::HashSet::new();
for module in &wire.modules {
if module.package_instance_id.is_empty()
|| module.id != format!("{}::{}", module.package_instance_id, module.relative_path)
|| !modules.insert(&module.id)
{
return Err(format!("Analysis 模块身份无效或重复:{}", module.id));
}
if module.source_digest.len() != 64
|| !module
.source_digest
@@ -105,8 +120,17 @@ impl ExecutionProjection {
{
return Err(format!("模块 {} 的 relative_path 不安全", module.id));
}
let mut functions = std::collections::HashSet::new();
for function in &module.functions {
if function.id.is_empty() || !functions.insert(&function.id) {
return Err(format!("Analysis 函数身份无效或重复:{}", function.id));
}
validate_body(&function.body, schema_version)
.map_err(|error| format!("{}:{error}", function.id))?;
}
}
Ok(Self {
schema_version,
producer: wire.producer,
project: wire.project,
modules: wire.modules,
@@ -116,24 +140,153 @@ impl ExecutionProjection {
}
}
pub fn semantic_nodes(body: &[Value]) -> impl Iterator<Item = &Value> {
body.iter().flat_map(walk_node)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StatementKind {
Assign,
Expression,
Branch,
Loop,
Return,
Break,
Continue,
}
fn walk_node(node: &Value) -> Box<dyn Iterator<Item = &Value> + '_> {
let mut nested = Vec::new();
if let Some(object) = node.as_object() {
for value in object.values() {
match value {
Value::Object(_) => nested.push(value),
Value::Array(array) => {
nested.extend(array.iter().filter(|value| value.is_object()));
}
_ => {}
#[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 kind = match value["kind"].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], version: u64) -> Result<(), String> {
for node in nodes {
let statement = Statement::read(node)?;
match statement.kind {
StatementKind::Break | StatementKind::Continue if version == 2 => {
return Err(format!("Analysis v2 不支持 {:?}", statement.kind));
}
StatementKind::Loop => {
if body(node).is_none() {
return Err("loop 的 body 必须是数组".into());
}
validate_condition_span(node)?;
}
StatementKind::Branch => {
let arms = node["arms"]
.as_array()
.filter(|arms| !arms.is_empty())
.ok_or("branch 的 arms 必须是非空数组")?;
for arm in arms {
if node_span(arm).is_none() || body(arm).is_none() {
return Err("分支臂必须包含有效的 span 和 body 数组".into());
}
validate_condition_span(arm)?;
}
}
_ => {}
}
for children in statement.child_bodies() {
validate_body(children, version)?;
}
}
Box::new(std::iter::once(node).chain(nested.into_iter().flat_map(|value| walk_node(value))))
Ok(())
}
fn validate_condition_span(value: &Value) -> Result<(), String> {
if value
.get("condition_span")
.is_some_and(|span| span_value(span).is_none())
{
return Err("Analysis condition_span 无效".into());
}
Ok(())
}
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.
@@ -141,8 +294,9 @@ pub(crate) fn effect_sites<'a>(
function: &'a AnalysisFunction,
calls: &'a [Value],
) -> impl Iterator<Item = Span> + 'a {
let writes = semantic_nodes(&function.body)
.filter(|node| node["kind"] == "assign" && node["target"]["kind"] == "index");
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.as_str()
&& match call["state"].as_str() {
@@ -161,6 +315,6 @@ pub(crate) fn effect_sites<'a>(
}
});
writes
.chain(external)
.filter_map(crate::alignment::node_span)
.map(|statement| statement.span)
.chain(external.filter_map(node_span))
}