feat: adopt marqdo 3.0.0-rc.4 public analysis boundary
This commit is contained in:
1 parent
769550b14b
commit
fe18df6c4b
74 files changed
+7618
-5368
No files matched your search
@@ -93,16 +93,12 @@ pub fn align_function(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> R
|
||||
complete: false,
|
||||
issues: Vec::new(),
|
||||
};
|
||||
let mut headings = markdown.headings.iter().filter(|heading| {
|
||||
heading.function == Some(heading.node)
|
||||
&& markdown.nodes[heading.node].span == analysis.heading_span
|
||||
});
|
||||
let function = match (headings.next(), headings.next()) {
|
||||
(Some(heading), None) => heading.node,
|
||||
_ => {
|
||||
let function = match markdown.function_heading(&analysis.id) {
|
||||
Some(node) => node,
|
||||
None => {
|
||||
tree.issues.push(at(
|
||||
analysis.heading_span,
|
||||
"Analysis heading_span 无法唯一对应 Exec H2",
|
||||
"Analysis function_id 无法对应 Exec H2",
|
||||
));
|
||||
return tree;
|
||||
}
|
||||
|
||||
+10
-39
@@ -2,7 +2,7 @@ use std::collections::HashSet;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::model::{body, node_span, span_value, NodeId, Span, Statement, StatementKind};
|
||||
use crate::model::{body, node_span, span_value, NodeId, Statement, StatementKind};
|
||||
|
||||
use super::{
|
||||
at,
|
||||
@@ -136,14 +136,6 @@ impl<'a, 'source> Matcher<'a, 'source> {
|
||||
.is_some_and(|control| self.tree.controls[control].kind == ControlKind::Loop),
|
||||
StatementKind::Break => located.jump == Some(JumpKind::Break),
|
||||
StatementKind::Continue => located.jump == Some(JumpKind::Continue),
|
||||
StatementKind::Expression => {
|
||||
let value = &statement.value["value"];
|
||||
// RC.1 could emit these bare identifiers as variable expressions.
|
||||
located.ordinary
|
||||
|| (located.jump.is_some()
|
||||
&& value["kind"] == "variable"
|
||||
&& value["name"].as_str() == Some(located.carrier.payload.trim()))
|
||||
}
|
||||
_ => located.ordinary,
|
||||
};
|
||||
let primary = index.at(statement.span).filter(eligible);
|
||||
@@ -187,25 +179,19 @@ impl<'a, 'source> Matcher<'a, 'source> {
|
||||
let span =
|
||||
node_span(arm).ok_or_else(|| at(carrier.span, "Analysis 分支臂缺少 span"))?;
|
||||
let condition = span_value(&arm["condition_span"]);
|
||||
let legacy = position == 1
|
||||
&& source_arms.len() == 2
|
||||
&& source_arm.role == ArmRole::Else
|
||||
&& is_legacy_else(&arms[0], arm);
|
||||
if self.source.at(carrier.span).is_none() {
|
||||
return Err(at(carrier.span, "源码分支臂无法唯一对应载体"));
|
||||
}
|
||||
if !legacy {
|
||||
let anchors = [Some(span), condition.filter(|condition| *condition != span)];
|
||||
let mut matches = false;
|
||||
for anchor in anchors.into_iter().flatten() {
|
||||
if !used_spans.insert(anchor) {
|
||||
return Err(at(carrier.span, "Analysis 分支臂 span 重复"));
|
||||
}
|
||||
matches |= anchor == carrier.span;
|
||||
}
|
||||
if !matches {
|
||||
return Err(at(carrier.span, "Analysis 分支臂与载体的位置或顺序不一致"));
|
||||
let anchors = [Some(span), condition.filter(|condition| *condition != span)];
|
||||
let mut matches = false;
|
||||
for anchor in anchors.into_iter().flatten() {
|
||||
if !used_spans.insert(anchor) {
|
||||
return Err(at(carrier.span, "Analysis 分支臂 span 重复"));
|
||||
}
|
||||
matches |= anchor == carrier.span;
|
||||
}
|
||||
if !matches {
|
||||
return Err(at(carrier.span, "Analysis 分支臂与载体的位置或顺序不一致"));
|
||||
}
|
||||
}
|
||||
for (position, arm) in arms.iter().enumerate() {
|
||||
@@ -220,18 +206,3 @@ impl<'a, 'source> Matcher<'a, 'source> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn is_legacy_else(first: &Value, last: &Value) -> bool {
|
||||
let condition = &last["condition"];
|
||||
let Some(first_span) = node_span(first) else {
|
||||
return false;
|
||||
};
|
||||
node_span(last) == Some(first_span)
|
||||
&& span_value(&last["condition_span"]) == Some(first_span)
|
||||
&& span_value(&first["condition_span"]) == Some(first_span)
|
||||
&& body(last).is_some_and(|body| !body.is_empty())
|
||||
&& condition["kind"] == "literal"
|
||||
&& condition["type"] == "bool"
|
||||
&& condition["value"] == true
|
||||
&& node_span(condition) == Some(Span::new(0, 0))
|
||||
}
|
||||
+7
-2
@@ -34,6 +34,11 @@ pub struct Cli {
|
||||
fail_on: FailOnArg,
|
||||
#[arg(long, value_enum, value_name = "MODE")]
|
||||
fix: Option<FixMode>,
|
||||
#[arg(
|
||||
long,
|
||||
help = "显式核验未加载的本地引用;会改变 Analysis bytes,不能用于 run/call 绑定"
|
||||
)]
|
||||
refs: bool,
|
||||
#[arg(long, requires = "fix", help = "校验并显示修复差异")]
|
||||
dry_run: bool,
|
||||
}
|
||||
@@ -114,7 +119,7 @@ pub fn run() -> Result<i32> {
|
||||
if inspected.contains(&entry) {
|
||||
continue;
|
||||
}
|
||||
let mut project = ProjectInput::load(&entry, &runner)?;
|
||||
let mut project = ProjectInput::load(&entry, &runner, cli.refs)?;
|
||||
let refusal = if cli.fix.is_some() {
|
||||
let outcome = fix_project(
|
||||
&project,
|
||||
@@ -123,7 +128,7 @@ pub fn run() -> Result<i32> {
|
||||
&mut std::io::stderr().lock(),
|
||||
)?;
|
||||
if outcome.changed {
|
||||
project = ProjectInput::load(&entry, &runner)?;
|
||||
project = ProjectInput::load(&entry, &runner, cli.refs)?;
|
||||
}
|
||||
outcome.diagnostic
|
||||
} else {
|
||||
|
||||
+6
-9
@@ -10,21 +10,16 @@ use crate::{
|
||||
rules::{self, Severity},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Profile {
|
||||
#[default]
|
||||
Recommended,
|
||||
StrictDoc,
|
||||
Minimal,
|
||||
Migration,
|
||||
}
|
||||
|
||||
impl Default for Profile {
|
||||
fn default() -> Self {
|
||||
Self::Recommended
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum RuleLevel {
|
||||
@@ -271,8 +266,10 @@ mod tests {
|
||||
let mut config = LintConfig::default();
|
||||
config.rules.insert("UNKNOWN".into(), RuleLevel::Off);
|
||||
assert!(config.validate().is_err());
|
||||
let mut config = LintConfig::default();
|
||||
config.min_narrative_ratio = 2.0;
|
||||
let config = LintConfig {
|
||||
min_narrative_ratio: 2.0,
|
||||
..LintConfig::default()
|
||||
};
|
||||
assert!(config.validate().is_err());
|
||||
let mut config = LintConfig::default();
|
||||
config.suppressions.push(Suppression {
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::{
|
||||
diagnostics::Diagnostic,
|
||||
engine::DocumentAnalysis,
|
||||
error::Result,
|
||||
input::{AnalysisStatus, MarkdownOrigin, SourceDocument},
|
||||
input::{AnalysisStatus, SourceDocument},
|
||||
metrics::{FunctionNarrative, MEASUREMENT_VERSION},
|
||||
model::LineColumn,
|
||||
rules::Severity,
|
||||
@@ -58,10 +58,7 @@ impl DocumentReport {
|
||||
mut notices: Vec<String>,
|
||||
core_output: String,
|
||||
) -> Result<Self> {
|
||||
if document.module.is_none()
|
||||
|| document.markdown_origin != MarkdownOrigin::MarqdoInspect
|
||||
|| !analysis.alignment_issues.is_empty()
|
||||
{
|
||||
if document.module.is_none() || !analysis.alignment_issues.is_empty() {
|
||||
analysis_status = AnalysisStatus::AnalysisIncomplete;
|
||||
}
|
||||
notices.append(&mut analysis.alignment_issues);
|
||||
|
||||
+5
-14
@@ -2,11 +2,11 @@ use crate::{
|
||||
alignment::align_function,
|
||||
config::EffectiveConfig,
|
||||
diagnostics::Diagnostic,
|
||||
input::{MarkdownOrigin, SourceDocument},
|
||||
input::SourceDocument,
|
||||
metrics::{measure_module_function, FunctionNarrative},
|
||||
rules::{
|
||||
check_aligned, check_ast_document, check_entry_for_heading, check_entry_without_analysis,
|
||||
check_function_documentation, check_supplemental_function,
|
||||
check_aligned, check_ast_document, check_entry_for_heading, check_function_documentation,
|
||||
check_supplemental_function,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -22,11 +22,7 @@ pub fn analyze_document(document: &SourceDocument, config: &EffectiveConfig) ->
|
||||
let mut diagnostics = check_ast_document(document);
|
||||
let mut metrics = Vec::new();
|
||||
let mut alignment_issues = Vec::new();
|
||||
let module = document
|
||||
.module
|
||||
.as_ref()
|
||||
.filter(|_| document.markdown_origin == MarkdownOrigin::MarqdoInspect);
|
||||
if let Some(module) = module {
|
||||
if let Some(module) = &document.module {
|
||||
for function in &module.functions {
|
||||
let tree = align_function(markdown, function);
|
||||
if !tree.complete {
|
||||
@@ -35,10 +31,7 @@ pub fn analyze_document(document: &SourceDocument, config: &EffectiveConfig) ->
|
||||
.iter()
|
||||
.map(|issue| format!("{}:{}", function.local_name, issue)),
|
||||
);
|
||||
if let Some(heading) = tree
|
||||
.function
|
||||
.and_then(|function| markdown.heading(function))
|
||||
{
|
||||
if let Some(heading) = markdown.function_segment(&function.id) {
|
||||
diagnostics.extend(check_entry_for_heading(markdown, heading));
|
||||
}
|
||||
continue;
|
||||
@@ -61,8 +54,6 @@ pub fn analyze_document(document: &SourceDocument, config: &EffectiveConfig) ->
|
||||
metrics.push(narrative);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
diagnostics.extend(check_entry_without_analysis(document));
|
||||
}
|
||||
diagnostics.sort_by(|left, right| (left.span, &left.id).cmp(&(right.span, &right.id)));
|
||||
DocumentAnalysis {
|
||||
|
||||
@@ -26,6 +26,12 @@ pub enum LintError {
|
||||
|
||||
pub type Result<T> = std::result::Result<T, LintError>;
|
||||
|
||||
impl From<LintError> for String {
|
||||
fn from(error: LintError) -> Self {
|
||||
error.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn io(path: impl Into<PathBuf>, source: std::io::Error) -> LintError {
|
||||
LintError::Io {
|
||||
path: path.into(),
|
||||
|
||||
+57
-119
@@ -15,7 +15,7 @@ use crate::{
|
||||
alignment::align_function,
|
||||
diagnostics::Diagnostic,
|
||||
error::{io, LintError, Result},
|
||||
input::{project_root, AnalysisStatus, MarkdownOrigin, MarqdoRunner, ProjectInput},
|
||||
input::{project_root, AnalysisStatus, MarqdoRunner, ProjectInput},
|
||||
model::Span,
|
||||
};
|
||||
|
||||
@@ -134,16 +134,7 @@ fn verify(project: &ProjectInput, runner: &MarqdoRunner, candidates: &Candidates
|
||||
ensure_sources_unchanged(project)?;
|
||||
let root = project_root(&project.entry);
|
||||
let staged = tempdir().map_err(|error| io("修复验证目录", error))?;
|
||||
for name in ["marqdo.yaml", "marqdo.lock"] {
|
||||
let file = root.join(name);
|
||||
match fs::read(&file) {
|
||||
Ok(bytes) => {
|
||||
fs::write(staged.path().join(name), bytes).map_err(|error| io(&file, error))?
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(io(&file, error)),
|
||||
}
|
||||
}
|
||||
copy_project_metadata(&root, staged.path())?;
|
||||
|
||||
for document in &project.documents {
|
||||
let path = &document.source.path;
|
||||
@@ -159,7 +150,7 @@ fn verify(project: &ProjectInput, runner: &MarqdoRunner, candidates: &Candidates
|
||||
}
|
||||
|
||||
let entry = staged.path().join(relative_to(&project.entry, &root)?);
|
||||
let checked = ProjectInput::load(entry, runner)?;
|
||||
let checked = ProjectInput::load(entry, runner, false)?;
|
||||
require_complete(&checked)?;
|
||||
let original = project
|
||||
.analysis
|
||||
@@ -183,49 +174,66 @@ fn verify(project: &ProjectInput, runner: &MarqdoRunner, candidates: &Candidates
|
||||
|
||||
for document in &project.documents {
|
||||
let path = &document.source.path;
|
||||
let Some(candidate_module) = document.module.as_ref() else {
|
||||
return Err(refusal("候选文档缺少 Analysis 模块"));
|
||||
};
|
||||
if !candidates.contains_key(path) {
|
||||
continue;
|
||||
}
|
||||
let shadow = staged.path().join(relative_to(path, &root)?);
|
||||
let revised = checked
|
||||
let revised_document = checked
|
||||
.documents
|
||||
.iter()
|
||||
.find(|candidate| candidate.source.path == shadow)
|
||||
.find(|candidate| {
|
||||
candidate
|
||||
.module
|
||||
.as_ref()
|
||||
.is_some_and(|module| module.id == candidate_module.id)
|
||||
})
|
||||
.ok_or_else(|| refusal("候选文档缺少 Analysis 模块"))?;
|
||||
let payloads = |document: &crate::input::SourceDocument| {
|
||||
document
|
||||
.markdown
|
||||
.carriers
|
||||
.iter()
|
||||
.map(|carrier| (carrier.kind, carrier.payload.clone()))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
let mut before_ast = runner.inspect(path)?;
|
||||
let mut after_ast = runner.inspect(&shadow)?;
|
||||
let mut before_ast = candidate_module.document.clone();
|
||||
let mut after_ast = revised_document
|
||||
.module
|
||||
.as_ref()
|
||||
.expect("checked by require_complete")
|
||||
.document
|
||||
.clone();
|
||||
strip_spans(&mut before_ast);
|
||||
strip_spans(&mut after_ast);
|
||||
if before_ast != after_ast || payloads(document) != payloads(revised) {
|
||||
if before_ast != after_ast || payloads(document) != payloads(revised_document) {
|
||||
return Err(refusal("Markdown 结构、文字或执行载荷发生变化"));
|
||||
}
|
||||
}
|
||||
ensure_sources_unchanged(project)
|
||||
}
|
||||
|
||||
fn copy_project_metadata(root: &Path, destination: &Path) -> Result<()> {
|
||||
for name in ["marqdo.yaml", "marqdo.lock"] {
|
||||
let file = root.join(name);
|
||||
match fs::read(&file) {
|
||||
Ok(bytes) => {
|
||||
fs::write(destination.join(name), bytes).map_err(|error| io(&file, error))?
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(io(&file, error)),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_complete(project: &ProjectInput) -> Result<()> {
|
||||
if project.analysis_status != AnalysisStatus::Complete || project.analysis.is_none() {
|
||||
return Err(refusal("无法取得完整的 Analysis v2/v3"));
|
||||
return Err(refusal("无法取得完整的 Analysis revision 3"));
|
||||
}
|
||||
for document in &project.documents {
|
||||
if document.markdown_origin != MarkdownOrigin::MarqdoInspect
|
||||
|| document.module.as_ref().is_none_or(|module| {
|
||||
module
|
||||
.functions
|
||||
.iter()
|
||||
.any(|function| !align_function(&document.markdown, function).complete)
|
||||
})
|
||||
let Some(module) = &document.module else {
|
||||
return Err(refusal("文档缺少 Analysis 模块"));
|
||||
};
|
||||
if module
|
||||
.functions
|
||||
.iter()
|
||||
.any(|function| !align_function(&document.markdown, function).complete)
|
||||
{
|
||||
return Err(refusal("公开 AST 与 Analysis 无法完整对齐"));
|
||||
return Err(refusal("公开 document/units 与 Analysis 无法完整对齐"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -245,10 +253,10 @@ fn analysis_fingerprint(analysis: &Value, changed_modules: &[&str]) -> Value {
|
||||
.as_str()
|
||||
.is_some_and(|id| changed_modules.contains(&id))
|
||||
{
|
||||
module
|
||||
.as_object_mut()
|
||||
.expect("module id is a field")
|
||||
.remove("source_digest");
|
||||
let module = module.as_object_mut().expect("module id is a field");
|
||||
for field in ["source_digest", "source", "document", "units", "anchors"] {
|
||||
module.remove(field);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -299,6 +307,15 @@ fn ensure_sources_unchanged(project: &ProjectInput) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn payloads(document: &crate::input::SourceDocument) -> Vec<(crate::model::CarrierKind, String)> {
|
||||
document
|
||||
.markdown
|
||||
.carriers
|
||||
.iter()
|
||||
.map(|carrier| (carrier.kind, carrier.payload.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn prepare_replacement(path: &Path, candidate: &str) -> Result<NamedTempFile> {
|
||||
let mut file = NamedTempFile::new_in(path.parent().expect("canonical path has parent"))
|
||||
.map_err(|error| io(path, error))?;
|
||||
@@ -315,82 +332,3 @@ fn prepare_replacement(path: &Path, candidate: &str) -> Result<NamedTempFile> {
|
||||
fn refusal(message: &str) -> LintError {
|
||||
LintError::UnsafeFix(message.into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn t27_verifier_rejects_a_list_layout_change_even_with_unchanged_execution() {
|
||||
let Some(core) = std::env::var_os("MARQDO_BIN") else {
|
||||
return;
|
||||
};
|
||||
let runner = MarqdoRunner::discover(Some(Path::new(&core))).unwrap();
|
||||
let dir = tempdir().unwrap();
|
||||
let file = dir.path().join("index.mq.md");
|
||||
let original =
|
||||
"## @exec choice\n\n**x = 0**\n\n1. `if true`\n\n **x = 1**\n\n`end`\n\n*return x*\n";
|
||||
let revised = original.replace("1. ", "").replace(" **", "**");
|
||||
fs::write(&file, original).unwrap();
|
||||
let project = ProjectInput::load(&file, &runner).unwrap();
|
||||
let candidates = BTreeMap::from([(project.entry.clone(), revised)]);
|
||||
let error = verify(&project, &runner, &candidates).unwrap_err();
|
||||
assert!(error.to_string().contains("Markdown"), "{error}");
|
||||
assert_eq!(fs::read_to_string(file).unwrap(), original);
|
||||
}
|
||||
#[test]
|
||||
fn safe_fix_checks_whitespace_and_refuses_reassigned_control_bodies() {
|
||||
let Some(core) = std::env::var_os("MARQDO_BIN") else {
|
||||
return;
|
||||
};
|
||||
let runner = MarqdoRunner::discover(Some(Path::new(&core))).unwrap();
|
||||
let rc2 = std::process::Command::new(runner.binary())
|
||||
.arg("--version")
|
||||
.output()
|
||||
.unwrap()
|
||||
.stdout
|
||||
.ends_with(b"3.0.0-rc.2\n");
|
||||
let v2 = "## @exec main\n\n`if false`\n\n*return 1*\n\n`else`\n\n*return 2*\n\n`end`\n";
|
||||
let v3 = "## @exec main\n\n`while false`\n\n`while false`\n\n`break`\n\n`end`\n\n`end`\n";
|
||||
let cases = [
|
||||
(
|
||||
2,
|
||||
v2,
|
||||
v2.replace("`else`\n\n*return 2*", "*return 2*\n\n`else`"),
|
||||
),
|
||||
(3, v3, v3.replace("`break`\n\n`end`", "`end`\n\n`break`")),
|
||||
];
|
||||
for (major, source, different_body) in
|
||||
cases.into_iter().filter(|(major, _, _)| *major == 2 || rc2)
|
||||
{
|
||||
let dir = tempdir().unwrap();
|
||||
let file = dir.path().join("case.mq.md");
|
||||
let original = source.replace("## @exec main\n\n", "## @exec main\n \t\n");
|
||||
fs::write(&file, &original).unwrap();
|
||||
let project = ProjectInput::load(&file, &runner).unwrap();
|
||||
assert_eq!(project.analysis.as_ref().unwrap().schema_version, major);
|
||||
let mut diff = Vec::new();
|
||||
let dry_run = fix_project(&project, &runner, true, &mut diff).unwrap();
|
||||
assert!(!dry_run.changed && dry_run.diagnostic.is_none() && !diff.is_empty());
|
||||
assert_eq!(fs::read(&file).unwrap(), original.as_bytes());
|
||||
let candidates = Candidates::from([(project.entry.clone(), different_body)]);
|
||||
for dry_run in [true, false] {
|
||||
let refused =
|
||||
apply_candidates(&project, &runner, &candidates, dry_run, &mut Vec::new())
|
||||
.unwrap();
|
||||
assert!(!refused.changed);
|
||||
let diagnostic = refused.diagnostic.unwrap();
|
||||
assert_eq!(diagnostic.id, "MQD-SAFETY-001");
|
||||
assert!(
|
||||
diagnostic.message.contains("Analysis 中"),
|
||||
"{}",
|
||||
diagnostic.message
|
||||
);
|
||||
assert_eq!(fs::read(&file).unwrap(), original.as_bytes());
|
||||
}
|
||||
let applied = fix_project(&project, &runner, false, &mut Vec::new()).unwrap();
|
||||
assert!(applied.changed && applied.diagnostic.is_none());
|
||||
assert_eq!(fs::read(&file).unwrap(), source.as_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
use comrak::{
|
||||
nodes::{ListType, Node, NodeValue, Sourcepos, TableAlignment},
|
||||
parse_document, Arena, Options,
|
||||
};
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::{error::Result, model::SourceSnapshot};
|
||||
|
||||
pub fn profile_options() -> Options<'static> {
|
||||
let mut options = Options::default();
|
||||
options.extension.table = true;
|
||||
options.extension.strikethrough = true;
|
||||
options.extension.tasklist = true;
|
||||
options.extension.math_dollars = true;
|
||||
options.extension.math_dollars_block = true;
|
||||
options.extension.front_matter_delimiter = Some("---".to_string());
|
||||
options
|
||||
}
|
||||
|
||||
pub fn fallback_ast(source: &SourceSnapshot) -> Result<Value> {
|
||||
let text = source.text();
|
||||
let (shift, body) = text
|
||||
.strip_prefix('\u{feff}')
|
||||
.map(|body| (3, body))
|
||||
.unwrap_or((0, text));
|
||||
let arena = Arena::new();
|
||||
let root = parse_document(&arena, body, &profile_options());
|
||||
let line_starts = line_starts(body);
|
||||
Ok(convert(&root, &line_starts, shift, body.len()))
|
||||
}
|
||||
|
||||
fn line_starts(source: &str) -> Vec<usize> {
|
||||
let mut starts = vec![0];
|
||||
for (index, byte) in source.bytes().enumerate() {
|
||||
if byte == b'\n' {
|
||||
starts.push(index + 1);
|
||||
}
|
||||
}
|
||||
starts
|
||||
}
|
||||
|
||||
fn span(pos: Sourcepos, starts: &[usize], shift: usize, len: usize) -> SpanValue {
|
||||
let offset = |line: usize, column: usize, inclusive: bool| {
|
||||
if line == 0 {
|
||||
return 0;
|
||||
}
|
||||
starts
|
||||
.get(line - 1)
|
||||
.map(|start| {
|
||||
(start + column.saturating_sub(1) + usize::from(inclusive)).min(len)
|
||||
})
|
||||
.unwrap_or(len)
|
||||
};
|
||||
let start = offset(pos.start.line, pos.start.column, false);
|
||||
let end = offset(pos.end.line, pos.end.column, true).max(start);
|
||||
SpanValue(start + shift, end + shift)
|
||||
}
|
||||
|
||||
struct SpanValue(usize, usize);
|
||||
|
||||
fn convert(node: &Node<'_>, starts: &[usize], shift: usize, len: usize) -> Value {
|
||||
let data = node.data();
|
||||
let SpanValue(start, end) = span(data.sourcepos, starts, shift, len);
|
||||
let mut object = Map::new();
|
||||
object.insert("span".into(), json!({"start": start, "end": end}));
|
||||
let mut literal = None;
|
||||
match &data.value {
|
||||
NodeValue::Document => {
|
||||
object.insert("kind".into(), json!("document"));
|
||||
}
|
||||
NodeValue::FrontMatter(raw) => {
|
||||
object.insert("kind".into(), json!("front_matter"));
|
||||
literal = Some(raw.clone());
|
||||
}
|
||||
NodeValue::BlockQuote | NodeValue::MultilineBlockQuote(_) => {
|
||||
object.insert("kind".into(), json!("block_quote"));
|
||||
}
|
||||
NodeValue::List(list) => {
|
||||
object.insert("kind".into(), json!("list"));
|
||||
object.insert(
|
||||
"ordered".into(),
|
||||
json!(list.list_type == ListType::Ordered),
|
||||
);
|
||||
if list.list_type == ListType::Ordered {
|
||||
object.insert("start".into(), json!(list.start));
|
||||
}
|
||||
object.insert("tight".into(), json!(list.tight));
|
||||
}
|
||||
NodeValue::Item(_) => {
|
||||
object.insert("kind".into(), json!("item"));
|
||||
}
|
||||
NodeValue::TaskItem(item) => {
|
||||
object.insert("kind".into(), json!("item"));
|
||||
object.insert("task".into(), json!(item.symbol.is_some()));
|
||||
}
|
||||
NodeValue::Heading(heading) => {
|
||||
object.insert("kind".into(), json!("heading"));
|
||||
object.insert("level".into(), json!(heading.level));
|
||||
object.insert("setext".into(), json!(heading.setext));
|
||||
}
|
||||
NodeValue::Paragraph => {
|
||||
object.insert("kind".into(), json!("paragraph"));
|
||||
}
|
||||
NodeValue::Text(text) => {
|
||||
object.insert("kind".into(), json!("text"));
|
||||
literal = Some(text.to_string());
|
||||
}
|
||||
NodeValue::Strong(_) => {
|
||||
object.insert("kind".into(), json!("strong"));
|
||||
}
|
||||
NodeValue::Emph(_) => {
|
||||
object.insert("kind".into(), json!("emph"));
|
||||
}
|
||||
NodeValue::Strikethrough(_) => {
|
||||
object.insert("kind".into(), json!("strikethrough"));
|
||||
}
|
||||
NodeValue::Code(code) => {
|
||||
object.insert("kind".into(), json!("code"));
|
||||
object.insert("ticks".into(), json!(code.num_backticks));
|
||||
literal = Some(code.literal.clone());
|
||||
}
|
||||
NodeValue::CodeBlock(block) => {
|
||||
object.insert("kind".into(), json!("code_block"));
|
||||
object.insert("fenced".into(), json!(block.fenced));
|
||||
object.insert("info".into(), json!(block.info.trim()));
|
||||
literal = Some(block.literal.clone());
|
||||
}
|
||||
NodeValue::Math(math) => {
|
||||
object.insert("kind".into(), json!("math"));
|
||||
object.insert("display".into(), json!(math.display_math));
|
||||
literal = Some(math.literal.clone());
|
||||
}
|
||||
NodeValue::MathBlock(block) => {
|
||||
object.insert("kind".into(), json!("math_block"));
|
||||
literal = Some(block.literal.clone());
|
||||
}
|
||||
NodeValue::Link(link) => {
|
||||
object.insert("kind".into(), json!("link"));
|
||||
object.insert("url".into(), json!(link.url));
|
||||
object.insert("title".into(), json!(link.title));
|
||||
}
|
||||
NodeValue::Image(image) => {
|
||||
object.insert("kind".into(), json!("image"));
|
||||
object.insert("url".into(), json!(image.url));
|
||||
object.insert("title".into(), json!(image.title));
|
||||
}
|
||||
NodeValue::Table(table) => {
|
||||
object.insert("kind".into(), json!("table"));
|
||||
let alignments: Vec<_> = table
|
||||
.alignments
|
||||
.iter()
|
||||
.map(|alignment| match alignment {
|
||||
TableAlignment::Left => "left",
|
||||
TableAlignment::Center => "center",
|
||||
TableAlignment::Right => "right",
|
||||
TableAlignment::None => "none",
|
||||
})
|
||||
.collect();
|
||||
object.insert("alignments".into(), json!(alignments));
|
||||
}
|
||||
NodeValue::TableRow(row) => {
|
||||
object.insert("kind".into(), json!("table_row"));
|
||||
object.insert("header".into(), json!(row.header));
|
||||
}
|
||||
NodeValue::TableCell => {
|
||||
object.insert("kind".into(), json!("table_cell"));
|
||||
}
|
||||
NodeValue::ThematicBreak(_) => {
|
||||
object.insert("kind".into(), json!("thematic_break"));
|
||||
}
|
||||
NodeValue::SoftBreak => {
|
||||
object.insert("kind".into(), json!("soft_break"));
|
||||
}
|
||||
NodeValue::LineBreak => {
|
||||
object.insert("kind".into(), json!("line_break"));
|
||||
}
|
||||
NodeValue::HtmlBlock(block) => {
|
||||
object.insert("kind".into(), json!("html_block"));
|
||||
literal = Some(block.literal.clone());
|
||||
}
|
||||
NodeValue::HtmlInline(raw) => {
|
||||
object.insert("kind".into(), json!("html_inline"));
|
||||
literal = Some(raw.clone());
|
||||
}
|
||||
other => {
|
||||
object.insert("kind".into(), json!("other"));
|
||||
object.insert("tag".into(), json!(format!("{other:?}")));
|
||||
}
|
||||
}
|
||||
if let Some(literal) = literal {
|
||||
object.insert("literal".into(), json!(literal));
|
||||
}
|
||||
let children: Vec<_> = node
|
||||
.children()
|
||||
.map(|child| convert(&child, starts, shift, len))
|
||||
.collect();
|
||||
if !children.is_empty() {
|
||||
object.insert("children".into(), Value::Array(children));
|
||||
}
|
||||
Value::Object(object)
|
||||
}
|
||||
+189
-59
@@ -1,4 +1,5 @@
|
||||
use std::{
|
||||
cmp::Ordering,
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, Output},
|
||||
@@ -6,6 +7,7 @@ use std::{
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
use crate::error::{io, LintError, Result};
|
||||
@@ -13,12 +15,15 @@ use crate::error::{io, LintError, Result};
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MarqdoRunner {
|
||||
binary: PathBuf,
|
||||
version: SemVer,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CheckOutcome {
|
||||
pub success: bool,
|
||||
pub analysis: Option<Value>,
|
||||
pub analysis_bytes: Vec<u8>,
|
||||
pub artifact_digest: Option<String>,
|
||||
pub output: String,
|
||||
pub diagnostics: Vec<CheckDiagnostic>,
|
||||
}
|
||||
@@ -66,71 +71,56 @@ impl MarqdoRunner {
|
||||
.map(Path::to_path_buf)
|
||||
.or_else(|| std::env::var_os("MARQDO_BIN").map(PathBuf::from))
|
||||
.unwrap_or_else(|| PathBuf::from("marqdo"));
|
||||
let runner = Self { binary };
|
||||
runner.ensure_compatible()?;
|
||||
Ok(runner)
|
||||
let output = Command::new(&binary)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.map_err(|error| io(&binary, error))?;
|
||||
if !output.status.success() {
|
||||
return Err(LintError::Core(format!(
|
||||
"无法运行 {} --version:{}",
|
||||
binary.display(),
|
||||
format_output(&output)
|
||||
)));
|
||||
}
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
let text = text.trim();
|
||||
let raw = text.strip_prefix("marqdo ").unwrap_or(text);
|
||||
let version = SemVer::parse(raw).map_err(|error| {
|
||||
LintError::Protocol(format!(
|
||||
"无法解析 Marqdo 版本 {raw:?}:{error};需要 Marqdo >=3.0.0-rc.4,<4.0.0"
|
||||
))
|
||||
})?;
|
||||
let minimum = SemVer::parse("3.0.0-rc.4").expect("static version");
|
||||
let maximum = SemVer::parse("4.0.0").expect("static version");
|
||||
if version < minimum || version >= maximum {
|
||||
return Err(LintError::Protocol(format!(
|
||||
"需要 Marqdo >=3.0.0-rc.4,<4.0.0,实际为 {raw};请升级核心并用当前 CLI 重新生成 Analysis,重装 marqdo-lint Tool"
|
||||
)));
|
||||
}
|
||||
Ok(Self { binary, version })
|
||||
}
|
||||
|
||||
pub fn binary(&self) -> &Path {
|
||||
&self.binary
|
||||
}
|
||||
|
||||
pub fn ensure_compatible(&self) -> Result<()> {
|
||||
let output = self.run(&[std::ffi::OsStr::new("--version")])?;
|
||||
if !output.status.success() {
|
||||
return Err(LintError::Core(format_output(&output)));
|
||||
}
|
||||
let version = String::from_utf8_lossy(&output.stdout);
|
||||
let version = version
|
||||
.trim()
|
||||
.strip_prefix("marqdo ")
|
||||
.unwrap_or(version.trim());
|
||||
let major = version
|
||||
.split('.')
|
||||
.next()
|
||||
.and_then(|part| part.parse::<u64>().ok());
|
||||
if major != Some(3) {
|
||||
return Err(LintError::Protocol(format!(
|
||||
"需要 Marqdo >=3.0.0-beta.1,<4.0.0,实际为 {version}"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
pub fn version(&self) -> &SemVer {
|
||||
&self.version
|
||||
}
|
||||
|
||||
pub fn inspect(&self, file: &Path) -> Result<Value> {
|
||||
let output = Command::new(&self.binary)
|
||||
.arg("inspect")
|
||||
.arg(file)
|
||||
.arg("--ast")
|
||||
.arg("--json")
|
||||
.output()
|
||||
.map_err(|error| io(&self.binary, error))?;
|
||||
if !output.status.success() {
|
||||
return Err(LintError::Core(format_output(&output)));
|
||||
}
|
||||
let value: Value = serde_json::from_slice(&output.stdout)
|
||||
.map_err(|error| LintError::Protocol(format!("inspect AST JSON 无效:{error}")))?;
|
||||
if value.get("command").and_then(Value::as_str) != Some("inspect") {
|
||||
return Err(LintError::Protocol(
|
||||
"inspect 输出缺少 command=inspect".into(),
|
||||
));
|
||||
}
|
||||
value
|
||||
.get("ast")
|
||||
.cloned()
|
||||
.ok_or_else(|| LintError::Protocol("inspect 输出缺少 ast 字段".into()))
|
||||
}
|
||||
|
||||
pub fn check(&self, file: &Path) -> Result<CheckOutcome> {
|
||||
pub fn check(&self, file: &Path, refs: bool) -> Result<CheckOutcome> {
|
||||
let temporary = NamedTempFile::new().map_err(|error| io("Analysis 临时文件", error))?;
|
||||
let output = Command::new(&self.binary)
|
||||
let mut command = Command::new(&self.binary);
|
||||
command
|
||||
.arg("check")
|
||||
.arg(file)
|
||||
.arg("--json")
|
||||
.arg("--emit")
|
||||
.arg(temporary.path())
|
||||
.output()
|
||||
.map_err(|error| io(&self.binary, error))?;
|
||||
.arg(temporary.path());
|
||||
if refs {
|
||||
command.arg("--refs");
|
||||
}
|
||||
let output = command.output().map_err(|error| io(&self.binary, error))?;
|
||||
if !output.status.success() {
|
||||
let diagnostics = check_diagnostics(&output.stdout);
|
||||
let text = if diagnostics.is_empty() {
|
||||
@@ -145,27 +135,30 @@ impl MarqdoRunner {
|
||||
return Ok(CheckOutcome {
|
||||
success: false,
|
||||
analysis: None,
|
||||
analysis_bytes: Vec::new(),
|
||||
artifact_digest: None,
|
||||
output: text,
|
||||
diagnostics,
|
||||
});
|
||||
}
|
||||
let bytes = fs::read(temporary.path()).map_err(|error| io(temporary.path(), error))?;
|
||||
if bytes.is_empty() {
|
||||
return Err(LintError::Protocol(
|
||||
"核心 check 成功但没有写出 Analysis 工件".into(),
|
||||
));
|
||||
}
|
||||
let artifact_digest = format!("sha256:{:x}", Sha256::digest(&bytes));
|
||||
let analysis = serde_json::from_slice(&bytes)
|
||||
.map_err(|error| LintError::Protocol(format!("Analysis JSON 无效:{error}")))?;
|
||||
Ok(CheckOutcome {
|
||||
success: true,
|
||||
analysis: Some(analysis),
|
||||
analysis_bytes: bytes,
|
||||
artifact_digest: Some(artifact_digest),
|
||||
output: String::new(),
|
||||
diagnostics: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn run(&self, args: &[&std::ffi::OsStr]) -> Result<Output> {
|
||||
Command::new(&self.binary)
|
||||
.args(args)
|
||||
.output()
|
||||
.map_err(|error| io(&self.binary, error))
|
||||
}
|
||||
}
|
||||
|
||||
fn format_output(output: &Output) -> String {
|
||||
@@ -191,3 +184,140 @@ fn check_diagnostics(stdout: &[u8]) -> Vec<CheckDiagnostic> {
|
||||
.filter(|report| report.command == "check")
|
||||
.map_or_else(Vec::new, |report| report.diagnostics)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SemVer {
|
||||
major: u64,
|
||||
minor: u64,
|
||||
patch: u64,
|
||||
prerelease: Vec<Identifier>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum Identifier {
|
||||
Numeric(u64),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
impl SemVer {
|
||||
pub fn parse(input: &str) -> std::result::Result<Self, String> {
|
||||
let input = input.trim();
|
||||
let (core, build) = match input.split_once('+') {
|
||||
Some((core, build)) => {
|
||||
if build.is_empty()
|
||||
|| !build
|
||||
.split('.')
|
||||
.all(|part| !part.is_empty() && is_identifier(part))
|
||||
{
|
||||
return Err("build metadata 无效".into());
|
||||
}
|
||||
(core, Some(build))
|
||||
}
|
||||
None => (input, None),
|
||||
};
|
||||
let _ = build;
|
||||
let (core, prerelease) = match core.split_once('-') {
|
||||
Some((core, prerelease)) => (core, Some(prerelease)),
|
||||
None => (core, None),
|
||||
};
|
||||
let mut parts = core.split('.');
|
||||
let major = parse_number(parts.next(), "major")?;
|
||||
let minor = parse_number(parts.next(), "minor")?;
|
||||
let patch = parse_number(parts.next(), "patch")?;
|
||||
if parts.next().is_some() {
|
||||
return Err("版本号段过多".into());
|
||||
}
|
||||
let mut identifiers = Vec::new();
|
||||
if let Some(prerelease) = prerelease {
|
||||
if prerelease.is_empty() {
|
||||
return Err("prerelease 为空".into());
|
||||
}
|
||||
for part in prerelease.split('.') {
|
||||
if part.is_empty() || !is_identifier(part) {
|
||||
return Err(format!("prerelease 标识 {part:?} 无效"));
|
||||
}
|
||||
if part.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
let value = part
|
||||
.parse::<u64>()
|
||||
.map_err(|_| format!("prerelease 数字 {part:?} 溢出"))?;
|
||||
identifiers.push(Identifier::Numeric(value));
|
||||
} else {
|
||||
identifiers.push(Identifier::Text(part.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
major,
|
||||
minor,
|
||||
patch,
|
||||
prerelease: identifiers,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_number(part: Option<&str>, name: &str) -> std::result::Result<u64, String> {
|
||||
let part = part.ok_or_else(|| format!("缺少 {name} 版本段"))?;
|
||||
if part.is_empty() || !part.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return Err(format!("{name} 必须是数字"));
|
||||
}
|
||||
part.parse::<u64>()
|
||||
.map_err(|_| format!("{name} 版本段溢出"))
|
||||
}
|
||||
|
||||
fn is_identifier(value: &str) -> bool {
|
||||
value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
|
||||
}
|
||||
|
||||
impl Ord for SemVer {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
(self.major, self.minor, self.patch)
|
||||
.cmp(&(other.major, other.minor, other.patch))
|
||||
.then_with(|| compare_prerelease(&self.prerelease, &other.prerelease))
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for SemVer {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
fn compare_prerelease(left: &[Identifier], right: &[Identifier]) -> Ordering {
|
||||
match (left.is_empty(), right.is_empty()) {
|
||||
(true, true) => Ordering::Equal,
|
||||
(true, false) => Ordering::Greater,
|
||||
(false, true) => Ordering::Less,
|
||||
(false, false) => {
|
||||
for (left, right) in left.iter().zip(right) {
|
||||
let ordering = match (left, right) {
|
||||
(Identifier::Numeric(left), Identifier::Numeric(right)) => left.cmp(right),
|
||||
(Identifier::Numeric(_), Identifier::Text(_)) => Ordering::Less,
|
||||
(Identifier::Text(_), Identifier::Numeric(_)) => Ordering::Greater,
|
||||
(Identifier::Text(left), Identifier::Text(right)) => left.cmp(right),
|
||||
};
|
||||
if ordering != Ordering::Equal {
|
||||
return ordering;
|
||||
}
|
||||
}
|
||||
left.len().cmp(&right.len())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::SemVer;
|
||||
|
||||
#[test]
|
||||
fn enforces_the_current_prerelease_floor() {
|
||||
assert!(SemVer::parse("3.0.0-rc.4").unwrap() < SemVer::parse("3.0.0").unwrap());
|
||||
assert!(SemVer::parse("3.0.0-rc.3").unwrap() < SemVer::parse("3.0.0-rc.4").unwrap());
|
||||
assert!(SemVer::parse("3.0.0-rc.10").unwrap() > SemVer::parse("3.0.0-rc.4").unwrap());
|
||||
assert!(SemVer::parse("3.1.0-alpha.1").unwrap() > SemVer::parse("3.0.0-rc.4").unwrap());
|
||||
assert!(SemVer::parse("4.0.0").unwrap() > SemVer::parse("3.0.0").unwrap());
|
||||
assert!(SemVer::parse("3.0").is_err());
|
||||
assert!(SemVer::parse("3.0.0-").is_err());
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -1,8 +1,6 @@
|
||||
mod fallback;
|
||||
mod marqdo;
|
||||
mod project;
|
||||
|
||||
pub use fallback::{fallback_ast, profile_options};
|
||||
pub use marqdo::{CheckDiagnostic, CheckOutcome, MarqdoRunner};
|
||||
pub use marqdo::{CheckDiagnostic, CheckOutcome, MarqdoRunner, SemVer};
|
||||
pub(crate) use project::project_root;
|
||||
pub use project::{AnalysisStatus, MarkdownOrigin, ProjectInput, SourceDocument};
|
||||
pub use project::{AnalysisStatus, ProjectInput, SourceDocument};
|
||||
+51
-81
@@ -4,13 +4,14 @@ use std::{
|
||||
};
|
||||
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::{
|
||||
error::{io, LintError, Result},
|
||||
model::{AnalysisModule, ExecutionProjection, MarkdownTree, SourceSnapshot},
|
||||
};
|
||||
|
||||
use super::{fallback_ast, CheckDiagnostic, MarqdoRunner};
|
||||
use super::{CheckDiagnostic, MarqdoRunner};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
@@ -19,18 +20,10 @@ pub enum AnalysisStatus {
|
||||
AnalysisIncomplete,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MarkdownOrigin {
|
||||
MarqdoInspect,
|
||||
ComrakFallback,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SourceDocument {
|
||||
pub source: SourceSnapshot,
|
||||
pub markdown: MarkdownTree,
|
||||
pub markdown_origin: MarkdownOrigin,
|
||||
pub module: Option<AnalysisModule>,
|
||||
}
|
||||
|
||||
@@ -40,55 +33,74 @@ pub struct ProjectInput {
|
||||
pub documents: Vec<SourceDocument>,
|
||||
pub analysis: Option<ExecutionProjection>,
|
||||
pub analysis_status: AnalysisStatus,
|
||||
pub artifact_digest: Option<String>,
|
||||
pub core_output: String,
|
||||
pub core_diagnostics: Vec<CheckDiagnostic>,
|
||||
pub notices: Vec<String>,
|
||||
}
|
||||
|
||||
impl ProjectInput {
|
||||
pub fn load(entry: impl AsRef<Path>, runner: &MarqdoRunner) -> Result<Self> {
|
||||
pub fn load(entry: impl AsRef<Path>, runner: &MarqdoRunner, refs: bool) -> Result<Self> {
|
||||
let entry = fs::canonicalize(entry.as_ref()).map_err(|error| io(entry.as_ref(), error))?;
|
||||
let mut notices = Vec::new();
|
||||
let entry_document = read_document(&entry, runner, &mut notices)?;
|
||||
let check = runner.check(&entry)?;
|
||||
let check = runner.check(&entry, refs)?;
|
||||
if !check.success {
|
||||
let source = SourceSnapshot::load(&entry)?;
|
||||
let markdown = MarkdownTree::empty(&source);
|
||||
return Ok(Self {
|
||||
entry,
|
||||
documents: vec![entry_document],
|
||||
documents: vec![SourceDocument {
|
||||
source,
|
||||
markdown,
|
||||
module: None,
|
||||
}],
|
||||
analysis: None,
|
||||
analysis_status: AnalysisStatus::AnalysisIncomplete,
|
||||
artifact_digest: None,
|
||||
core_output: check.output,
|
||||
core_diagnostics: check.diagnostics,
|
||||
notices,
|
||||
notices: Vec::new(),
|
||||
});
|
||||
}
|
||||
let raw = check
|
||||
.analysis
|
||||
.ok_or_else(|| LintError::Protocol("核心 check 成功但没有生成 Analysis".into()))?;
|
||||
let analysis = ExecutionProjection::from_json(raw).map_err(LintError::Protocol)?;
|
||||
let bytes = check.analysis_bytes;
|
||||
let artifact_digest = check.artifact_digest;
|
||||
let analysis = ExecutionProjection::from_bytes(&bytes).map_err(LintError::Protocol)?;
|
||||
let entry_module = analysis
|
||||
.entry_module()
|
||||
.ok_or_else(|| LintError::Protocol("Analysis 缺少 entry_module_id 对应模块".into()))?;
|
||||
let root_package = entry_module.package_instance_id.clone();
|
||||
let root = project_root(&entry);
|
||||
let entry_module_id = analysis.project.entry_module_id.clone();
|
||||
let mut documents = Vec::new();
|
||||
for module in analysis
|
||||
.modules
|
||||
.iter()
|
||||
.filter(|module| module.package_instance_id.starts_with("root:"))
|
||||
.filter(|module| module.package_instance_id == root_package)
|
||||
{
|
||||
let path = root.join(&module.relative_path);
|
||||
let mut document = read_document(&path, runner, &mut notices)?;
|
||||
if document.source.digest_hex() != module.source_digest {
|
||||
return Err(LintError::Protocol(format!(
|
||||
"模块 {} 的源码摘要与 Analysis 不一致",
|
||||
module.id
|
||||
)));
|
||||
}
|
||||
let path = if module.id == entry_module_id {
|
||||
entry.clone()
|
||||
} else {
|
||||
root.join(&module.relative_path)
|
||||
};
|
||||
let source = module.source_snapshot(path)?;
|
||||
let markdown = MarkdownTree::from_analysis(
|
||||
module.document.clone(),
|
||||
&module.units,
|
||||
&module.functions,
|
||||
&source,
|
||||
)?;
|
||||
for function in &module.functions {
|
||||
function.validate_source_spans(&document.source)?;
|
||||
function.validate_source_spans(&source)?;
|
||||
}
|
||||
document.module = Some(module.clone());
|
||||
documents.push(document);
|
||||
documents.push(SourceDocument {
|
||||
source,
|
||||
markdown,
|
||||
module: Some(module.clone()),
|
||||
});
|
||||
}
|
||||
if documents.is_empty() {
|
||||
documents.push(entry_document);
|
||||
return Err(LintError::Protocol(
|
||||
"Analysis 中没有入口项目根包的模块".into(),
|
||||
));
|
||||
}
|
||||
documents.sort_by(|left, right| left.source.path.cmp(&right.source.path));
|
||||
Ok(Self {
|
||||
@@ -96,59 +108,12 @@ impl ProjectInput {
|
||||
documents,
|
||||
analysis: Some(analysis),
|
||||
analysis_status: AnalysisStatus::Complete,
|
||||
artifact_digest,
|
||||
core_output: String::new(),
|
||||
core_diagnostics: Vec::new(),
|
||||
notices,
|
||||
notices: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn document_only(entry: impl AsRef<Path>, runner: &MarqdoRunner) -> Result<Self> {
|
||||
let entry = fs::canonicalize(entry.as_ref()).map_err(|error| io(entry.as_ref(), error))?;
|
||||
let mut notices = Vec::new();
|
||||
let document = read_document(&entry, runner, &mut notices)?;
|
||||
Ok(Self {
|
||||
entry,
|
||||
documents: vec![document],
|
||||
analysis: None,
|
||||
analysis_status: AnalysisStatus::AnalysisIncomplete,
|
||||
core_output: String::new(),
|
||||
core_diagnostics: Vec::new(),
|
||||
notices,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn read_document(
|
||||
path: &Path,
|
||||
runner: &MarqdoRunner,
|
||||
notices: &mut Vec<String>,
|
||||
) -> Result<SourceDocument> {
|
||||
let source = SourceSnapshot::load(path)?;
|
||||
match runner.inspect(path) {
|
||||
Ok(ast) => {
|
||||
let markdown = MarkdownTree::from_json(ast, &source)?;
|
||||
Ok(SourceDocument {
|
||||
source,
|
||||
markdown,
|
||||
markdown_origin: MarkdownOrigin::MarqdoInspect,
|
||||
module: None,
|
||||
})
|
||||
}
|
||||
Err(LintError::Core(message)) => {
|
||||
let markdown = MarkdownTree::from_json(fallback_ast(&source)?, &source)?;
|
||||
notices.push(format!(
|
||||
"{}:inspect 不可用,已使用严格 comrak 降级;{message}",
|
||||
path.display()
|
||||
));
|
||||
Ok(SourceDocument {
|
||||
source,
|
||||
markdown,
|
||||
markdown_origin: MarkdownOrigin::ComrakFallback,
|
||||
module: None,
|
||||
})
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn project_root(entry: &Path) -> PathBuf {
|
||||
@@ -163,3 +128,8 @@ pub(crate) fn project_root(entry: &Path) -> PathBuf {
|
||||
current = parent;
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn artifact_sha256(bytes: &[u8]) -> String {
|
||||
format!("sha256:{:x}", Sha256::digest(bytes))
|
||||
}
|
||||
+4
-7
@@ -8,8 +8,8 @@ use crate::{
|
||||
alignment::statement_count,
|
||||
input::SourceDocument,
|
||||
model::{
|
||||
effect_sites, statements, AnalysisFunction, Carrier, HeadingMode, MarkdownTree, NodeId,
|
||||
ProseFragment, Span, StatementKind,
|
||||
effect_sites, statements, AnalysisCall, AnalysisFunction, Carrier, HeadingMode,
|
||||
MarkdownTree, NodeId, ProseFragment, Span, StatementKind,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -93,7 +93,7 @@ pub fn measure_document(
|
||||
pub(crate) fn measure_module_function(
|
||||
markdown: &MarkdownTree,
|
||||
function: &AnalysisFunction,
|
||||
calls: &[serde_json::Value],
|
||||
calls: &[AnalysisCall],
|
||||
config: NarrativeConfig,
|
||||
) -> Option<FunctionNarrative> {
|
||||
let mut metrics = measure_function(markdown, function, config)?;
|
||||
@@ -106,10 +106,7 @@ pub fn measure_function(
|
||||
analysis: &AnalysisFunction,
|
||||
config: NarrativeConfig,
|
||||
) -> Option<FunctionNarrative> {
|
||||
let heading = markdown.headings.iter().find(|heading| {
|
||||
heading.function == Some(heading.node)
|
||||
&& markdown.nodes[heading.node].span == analysis.heading_span
|
||||
})?;
|
||||
let heading = markdown.function_segment(&analysis.id)?;
|
||||
let function = heading.node;
|
||||
let mut carriers: Vec<_> = markdown
|
||||
.carriers
|
||||
|
||||
+1727
-118
File diff suppressed because it is too large.
Load diff
+190
-137
@@ -1,18 +1,14 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::error::{LintError, Result};
|
||||
|
||||
use super::{SourceSnapshot, Span};
|
||||
use super::{AnalysisFunction, AnalysisUnit, HeadingMode, SourceSnapshot, Span, UnitKind};
|
||||
|
||||
pub type NodeId = usize;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum HeadingMode {
|
||||
Knowledge,
|
||||
Exec,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CarrierKind {
|
||||
Code,
|
||||
@@ -39,6 +35,7 @@ pub struct MarkdownNode {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HeadingSegment {
|
||||
pub node: NodeId,
|
||||
pub unit_id: String,
|
||||
pub level: u8,
|
||||
pub mode: HeadingMode,
|
||||
pub name: String,
|
||||
@@ -74,6 +71,10 @@ pub struct MarkdownTree {
|
||||
node_functions: Vec<Option<NodeId>>,
|
||||
node_headings: Vec<Option<NodeId>>,
|
||||
node_modes: Vec<HeadingMode>,
|
||||
function_headings: HashMap<String, NodeId>,
|
||||
unit_headings: HashMap<String, NodeId>,
|
||||
unit_functions: HashMap<String, String>,
|
||||
heading_units: HashMap<NodeId, usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -101,20 +102,71 @@ struct RawNode {
|
||||
}
|
||||
|
||||
impl MarkdownTree {
|
||||
pub fn from_json(value: Value, source: &SourceSnapshot) -> Result<Self> {
|
||||
let raw: RawNode = serde_json::from_value(value)
|
||||
.map_err(|error| LintError::Protocol(format!("AST JSON 无效:{error}")))?;
|
||||
Self::from_raw(raw, source)
|
||||
/// Empty container used only for an honest `analysis_incomplete` report
|
||||
/// after `check` failed. It contains no document AST and therefore runs no
|
||||
/// document-dependent rules.
|
||||
pub fn empty(source: &SourceSnapshot) -> Self {
|
||||
let span = Span::new(0, source.bytes.len());
|
||||
Self {
|
||||
nodes: vec![MarkdownNode {
|
||||
kind: "document".into(),
|
||||
span,
|
||||
literal: None,
|
||||
level: None,
|
||||
setext: false,
|
||||
ordered: None,
|
||||
start: None,
|
||||
tight: None,
|
||||
task: None,
|
||||
ticks: None,
|
||||
parent: None,
|
||||
children: Vec::new(),
|
||||
}],
|
||||
root: 0,
|
||||
headings: Vec::new(),
|
||||
carriers: Vec::new(),
|
||||
node_functions: vec![None],
|
||||
node_headings: vec![None],
|
||||
node_modes: vec![HeadingMode::Knowledge],
|
||||
function_headings: HashMap::new(),
|
||||
unit_headings: HashMap::new(),
|
||||
unit_functions: HashMap::new(),
|
||||
heading_units: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn from_raw(raw: RawNode, source: &SourceSnapshot) -> Result<Self> {
|
||||
/// Build the Markdown container and carrier index from the public
|
||||
/// `modules[].document` projection plus the authoritative `units` list.
|
||||
/// No declaration syntax is parsed here: modes, names, section ranges and
|
||||
/// function ownership come only from Analysis.
|
||||
pub fn from_analysis(
|
||||
document: Value,
|
||||
units: &[AnalysisUnit],
|
||||
functions: &[AnalysisFunction],
|
||||
source: &SourceSnapshot,
|
||||
) -> Result<Self> {
|
||||
let raw: RawNode = serde_json::from_value(document).map_err(|error| {
|
||||
LintError::Protocol(format!("modules[].document JSON 无效:{error}"))
|
||||
})?;
|
||||
Self::from_raw(raw, units, functions, source)
|
||||
}
|
||||
|
||||
fn from_raw(
|
||||
raw: RawNode,
|
||||
units: &[AnalysisUnit],
|
||||
functions: &[AnalysisFunction],
|
||||
source: &SourceSnapshot,
|
||||
) -> Result<Self> {
|
||||
if raw.kind != "document" {
|
||||
return Err(LintError::Protocol("AST 根节点不是 document".into()));
|
||||
return Err(LintError::Protocol(
|
||||
"modules[].document 根节点不是 document".into(),
|
||||
));
|
||||
}
|
||||
let mut nodes = Vec::new();
|
||||
let root = flatten(raw, None, &mut nodes);
|
||||
for node in &nodes {
|
||||
node.span.validate(source.bytes.len())?;
|
||||
source.slice(node.span)?;
|
||||
}
|
||||
let count = nodes.len();
|
||||
let mut tree = Self {
|
||||
@@ -125,62 +177,119 @@ impl MarkdownTree {
|
||||
node_functions: vec![None; count],
|
||||
node_headings: vec![None; count],
|
||||
node_modes: vec![HeadingMode::Knowledge; count],
|
||||
function_headings: HashMap::new(),
|
||||
unit_headings: HashMap::new(),
|
||||
unit_functions: HashMap::new(),
|
||||
heading_units: HashMap::new(),
|
||||
};
|
||||
tree.index_headings_and_carriers(source)?;
|
||||
tree.index_units(units, functions)?;
|
||||
tree.index_regions_and_carriers(units, source)?;
|
||||
Ok(tree)
|
||||
}
|
||||
|
||||
fn index_headings_and_carriers(&mut self, source: &SourceSnapshot) -> Result<()> {
|
||||
struct Ancestor {
|
||||
level: u8,
|
||||
mode: HeadingMode,
|
||||
fn index_units(
|
||||
&mut self,
|
||||
units: &[AnalysisUnit],
|
||||
functions: &[AnalysisFunction],
|
||||
) -> Result<()> {
|
||||
let function_unit_to_id: HashMap<&str, &str> = functions
|
||||
.iter()
|
||||
.map(|function| (function.unit_id.as_str(), function.id.as_str()))
|
||||
.collect();
|
||||
let units_by_id: HashMap<&str, &AnalysisUnit> =
|
||||
units.iter().map(|unit| (unit.id.as_str(), unit)).collect();
|
||||
for unit in units.iter().filter(|unit| unit.kind != UnitKind::Root) {
|
||||
let mut cursor = Some(unit);
|
||||
let mut owner = None;
|
||||
while let Some(current) = cursor {
|
||||
if current.kind == UnitKind::Function {
|
||||
owner = function_unit_to_id.get(current.id.as_str()).copied();
|
||||
break;
|
||||
}
|
||||
cursor = current
|
||||
.parent_id
|
||||
.as_deref()
|
||||
.and_then(|id| units_by_id.get(id).copied());
|
||||
}
|
||||
if let Some(owner) = owner {
|
||||
self.unit_functions
|
||||
.insert(unit.id.clone(), owner.to_string());
|
||||
}
|
||||
}
|
||||
let mut stack: Vec<Ancestor> = Vec::new();
|
||||
for (index, unit) in units
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, unit)| unit.kind != UnitKind::Root)
|
||||
{
|
||||
let heading_span = unit.heading_span.ok_or_else(|| {
|
||||
LintError::Protocol(format!("unit {} 缺少 heading_span", unit.id))
|
||||
})?;
|
||||
let node = self.heading_node_at(heading_span).ok_or_else(|| {
|
||||
LintError::Protocol(format!(
|
||||
"unit {} 的 heading_span 无法唯一对应 document heading",
|
||||
unit.id
|
||||
))
|
||||
})?;
|
||||
self.unit_headings.insert(unit.id.clone(), node);
|
||||
self.heading_units.insert(node, index);
|
||||
if unit.kind == UnitKind::Function {
|
||||
let function_id = function_unit_to_id.get(unit.id.as_str()).ok_or_else(|| {
|
||||
LintError::Protocol(format!("function unit {} 缺少 function 记录", unit.id))
|
||||
})?;
|
||||
self.function_headings
|
||||
.insert((*function_id).to_string(), node);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn heading_node_at(&self, span: Span) -> Option<NodeId> {
|
||||
let matches: Vec<_> = self
|
||||
.nodes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, node)| node.kind == "heading" && node.span == span)
|
||||
.map(|(node, _)| node)
|
||||
.collect();
|
||||
(matches.len() == 1).then_some(matches[0])
|
||||
}
|
||||
|
||||
fn index_regions_and_carriers(
|
||||
&mut self,
|
||||
units: &[AnalysisUnit],
|
||||
source: &SourceSnapshot,
|
||||
) -> Result<()> {
|
||||
let mut current_heading = None;
|
||||
let mut current_function = None;
|
||||
let mut current_mode = HeadingMode::Knowledge;
|
||||
let root_children = self.nodes[self.root].children.clone();
|
||||
for child in root_children {
|
||||
if self.nodes[child].kind == "heading" {
|
||||
let level = self.nodes[child].level.unwrap_or(0);
|
||||
while stack.last().is_some_and(|entry| entry.level >= level) {
|
||||
stack.pop();
|
||||
}
|
||||
let inherited = stack
|
||||
.last()
|
||||
.map(|entry| entry.mode)
|
||||
.unwrap_or(HeadingMode::Knowledge);
|
||||
let declared = if self.nodes[child].setext {
|
||||
None
|
||||
} else {
|
||||
heading_declaration(self, child)
|
||||
};
|
||||
current_mode = declared
|
||||
.as_ref()
|
||||
.map(|(mode, _)| *mode)
|
||||
.unwrap_or(inherited);
|
||||
let unit_index = self.heading_units.get(&child).copied().ok_or_else(|| {
|
||||
LintError::Protocol(format!(
|
||||
"document heading 字节 [{}, {}) 没有对应 unit",
|
||||
self.nodes[child].span.start, self.nodes[child].span.end
|
||||
))
|
||||
})?;
|
||||
let unit = &units[unit_index];
|
||||
current_heading = Some(child);
|
||||
match level {
|
||||
1 => current_function = None,
|
||||
2 => {
|
||||
current_function = (current_mode == HeadingMode::Exec).then_some(child)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let name = declared
|
||||
.map(|(_, name)| name)
|
||||
.unwrap_or_else(|| plain_text(self, child));
|
||||
current_mode = unit.mode;
|
||||
current_function = match unit.kind {
|
||||
UnitKind::Function => Some(child),
|
||||
UnitKind::Section => self
|
||||
.unit_functions
|
||||
.get(&unit.id)
|
||||
.and_then(|id| self.function_headings.get(id).copied()),
|
||||
_ => None,
|
||||
};
|
||||
self.headings.push(HeadingSegment {
|
||||
node: child,
|
||||
level,
|
||||
mode: current_mode,
|
||||
name,
|
||||
unit_id: unit.id.clone(),
|
||||
level: unit.level,
|
||||
mode: unit.mode,
|
||||
name: unit.name.clone(),
|
||||
function: current_function,
|
||||
});
|
||||
stack.push(Ancestor {
|
||||
level,
|
||||
mode: current_mode,
|
||||
});
|
||||
self.node_headings[child] = current_heading;
|
||||
self.node_functions[child] = current_function;
|
||||
self.node_modes[child] = current_mode;
|
||||
@@ -253,7 +362,7 @@ impl MarkdownTree {
|
||||
});
|
||||
let mut spans = children;
|
||||
let first = spans.next().unwrap_or(span);
|
||||
let last = spans.last().unwrap_or(first);
|
||||
let last = spans.next_back().unwrap_or(first);
|
||||
Span::new(first.start, last.end)
|
||||
};
|
||||
source.slice(span)?;
|
||||
@@ -296,6 +405,19 @@ impl MarkdownTree {
|
||||
self.headings.iter().find(|heading| heading.node == node)
|
||||
}
|
||||
|
||||
pub fn heading_for_unit(&self, unit_id: &str) -> Option<NodeId> {
|
||||
self.unit_headings.get(unit_id).copied()
|
||||
}
|
||||
|
||||
pub fn function_heading(&self, function_id: &str) -> Option<NodeId> {
|
||||
self.function_headings.get(function_id).copied()
|
||||
}
|
||||
|
||||
pub fn function_segment(&self, function_id: &str) -> Option<&HeadingSegment> {
|
||||
let node = self.function_heading(function_id)?;
|
||||
self.heading(node)
|
||||
}
|
||||
|
||||
pub fn ancestors(&self, mut node: NodeId) -> Vec<NodeId> {
|
||||
let mut result = Vec::new();
|
||||
while let Some(parent) = self.nodes[node].parent {
|
||||
@@ -319,7 +441,9 @@ impl MarkdownTree {
|
||||
}
|
||||
|
||||
pub fn first_carrier_in_item(&self, item: NodeId) -> Option<&Carrier> {
|
||||
self.item_carriers(item).into_iter().min_by_key(|c| c.span.start)
|
||||
self.item_carriers(item)
|
||||
.into_iter()
|
||||
.min_by_key(|c| c.span.start)
|
||||
}
|
||||
|
||||
pub fn is_descendant(&self, node: NodeId, ancestor: NodeId) -> bool {
|
||||
@@ -352,7 +476,10 @@ impl MarkdownTree {
|
||||
|
||||
fn has_carrier_ancestor(&self, node: NodeId) -> bool {
|
||||
self.ancestors(node).into_iter().any(|ancestor| {
|
||||
matches!(self.nodes[ancestor].kind.as_str(), "strong" | "emph" | "code")
|
||||
matches!(
|
||||
self.nodes[ancestor].kind.as_str(),
|
||||
"strong" | "emph" | "code"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -360,7 +487,13 @@ impl MarkdownTree {
|
||||
self.ancestors(node).into_iter().any(|ancestor| {
|
||||
matches!(
|
||||
self.nodes[ancestor].kind.as_str(),
|
||||
"table" | "strikethrough" | "code_block" | "math" | "math_block" | "html_block" | "html_inline"
|
||||
"table"
|
||||
| "strikethrough"
|
||||
| "code_block"
|
||||
| "math"
|
||||
| "math_block"
|
||||
| "html_block"
|
||||
| "html_inline"
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -394,83 +527,3 @@ fn flatten(raw: RawNode, parent: Option<NodeId>, nodes: &mut Vec<MarkdownNode>)
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
fn heading_declaration(tree: &MarkdownTree, heading: NodeId) -> Option<(HeadingMode, String)> {
|
||||
let first = tree.nodes[heading].children.first()?;
|
||||
let first = &tree.nodes[*first];
|
||||
if first.kind != "text" {
|
||||
return None;
|
||||
}
|
||||
let literal = first.literal.as_deref()?;
|
||||
for (prefix, mode) in [
|
||||
("@exec", HeadingMode::Exec),
|
||||
("@knowledge", HeadingMode::Knowledge),
|
||||
] {
|
||||
if let Some(rest) = literal.strip_prefix(prefix) {
|
||||
if rest.is_empty() || rest.starts_with(char::is_whitespace) {
|
||||
let name = rest.trim();
|
||||
if !name.is_empty() {
|
||||
return Some((mode, name.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn plain_text(tree: &MarkdownTree, node: NodeId) -> String {
|
||||
let node = &tree.nodes[node];
|
||||
if let Some(literal) = &node.literal {
|
||||
if node.kind == "text" || node.kind == "code" {
|
||||
return literal.clone();
|
||||
}
|
||||
}
|
||||
node.children
|
||||
.iter()
|
||||
.map(|child| plain_text(tree, *child))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn tree(markdown: &str) -> MarkdownTree {
|
||||
let source = SourceSnapshot::new(PathBuf::from("test.mq.md"), markdown.as_bytes().to_vec()).unwrap();
|
||||
let ast = crate::input::fallback_ast(&source).unwrap();
|
||||
MarkdownTree::from_json(ast, &source).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexes_functions_carriers_and_list_ancestors() {
|
||||
let tree = tree("# @knowledge 示例\n\n## @exec 判断\n\n说明。\n\n`params(x: Int)`\n\n1. `if x > 0`:正数。\n\n **结果 = 1**\n\n2. `else`:其他。\n\n **结果 = 0**\n\n`end`\n\n*return 结果*\n");
|
||||
assert_eq!(tree.headings.len(), 2);
|
||||
assert_eq!(tree.carriers.len(), 7);
|
||||
let if_carrier = tree.carriers.iter().find(|c| c.payload == "if x > 0").unwrap();
|
||||
let item = tree.nearest(if_carrier.node, "item").unwrap();
|
||||
assert_eq!(tree.first_carrier_in_item(item).unwrap().node, if_carrier.node);
|
||||
let list = tree.nearest(item, "list").unwrap();
|
||||
assert_eq!(tree.nodes[list].ordered, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn knowledge_carriers_are_not_executable() {
|
||||
let tree = tree("## @knowledge 说明\n\n**重要** 和 `code`。\n");
|
||||
assert!(tree.carriers.is_empty());
|
||||
assert!(tree.prose_fragments(0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_emphasis_is_a_carrier_not_prose_and_headings_are_excluded() {
|
||||
let tree = tree("## @exec 标题不计量\n\n普通说明 **重要** 继续说明。\n\n### 小节也不计量\n\n*return 0*\n");
|
||||
let function = tree.headings[0].node;
|
||||
let prose: Vec<_> = tree
|
||||
.prose_fragments(function)
|
||||
.into_iter()
|
||||
.map(|fragment| fragment.text)
|
||||
.collect();
|
||||
assert_eq!(prose, vec!["普通说明 ", " 继续说明。"]);
|
||||
assert!(tree.carriers.iter().any(|carrier| carrier.payload == "重要"));
|
||||
}
|
||||
}
|
||||
+7
-3
@@ -4,11 +4,15 @@ mod source;
|
||||
mod span;
|
||||
|
||||
pub use analysis::{
|
||||
semantic_nodes, AnalysisFunction, AnalysisModule, CoreDiagnostic, ExecutionProjection,
|
||||
semantic_nodes, AnalysisAnchor, AnalysisCall, AnalysisDiagnostic, AnalysisFunction,
|
||||
AnalysisImport, AnalysisModule, AnalysisParam, AnalysisProject, AnalysisReference,
|
||||
AnalysisResource, AnalysisSignature, AnalysisUnit, CallReason, CallState, CallTargetKind,
|
||||
CallTargetOwner, ExecutionProjection, ExtensionIdentity, HeadingMode, IdentityKind, ModeOrigin,
|
||||
Producer, ReferenceState, ReferenceTargetKind, ResourceKind, SignatureKind, StdlibIdentity,
|
||||
UnitKind,
|
||||
};
|
||||
pub use markdown::{
|
||||
Carrier, CarrierKind, HeadingMode, HeadingSegment, MarkdownNode, MarkdownTree, NodeId,
|
||||
ProseFragment,
|
||||
Carrier, CarrierKind, HeadingSegment, MarkdownNode, MarkdownTree, NodeId, ProseFragment,
|
||||
};
|
||||
pub use source::SourceSnapshot;
|
||||
pub use span::{LineColumn, Span};
|
||||
|
||||
+20
-5
@@ -1,4 +1,7 @@
|
||||
use std::{fs, path::{Path, PathBuf}};
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
@@ -52,7 +55,10 @@ impl SourceSnapshot {
|
||||
pub fn slice(&self, span: Span) -> Result<&str> {
|
||||
span.validate(self.bytes.len())?;
|
||||
self.text().get(span.start..span.end).ok_or_else(|| {
|
||||
LintError::Protocol(format!("span [{}, {}) 不在 UTF-8 字符边界", span.start, span.end))
|
||||
LintError::Protocol(format!(
|
||||
"span [{}, {}) 不在 UTF-8 字符边界",
|
||||
span.start, span.end
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -93,9 +99,18 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
assert!(source.digest.starts_with("sha256:"));
|
||||
assert_eq!(source.line_column(3).unwrap(), LineColumn { line: 1, column: 1 });
|
||||
assert_eq!(source.line_column(6).unwrap(), LineColumn { line: 1, column: 2 });
|
||||
assert_eq!(source.line_column(11).unwrap(), LineColumn { line: 2, column: 1 });
|
||||
assert_eq!(
|
||||
source.line_column(3).unwrap(),
|
||||
LineColumn { line: 1, column: 1 }
|
||||
);
|
||||
assert_eq!(
|
||||
source.line_column(6).unwrap(),
|
||||
LineColumn { line: 1, column: 2 }
|
||||
);
|
||||
assert_eq!(
|
||||
source.line_column(11).unwrap(),
|
||||
LineColumn { line: 2, column: 1 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+39
-1
@@ -206,6 +206,42 @@ pub const CATALOG: &[RuleSpec] = &[
|
||||
"heading 模式序列及核心控制边界诊断。",
|
||||
Manual
|
||||
),
|
||||
rule!(
|
||||
"MQD-LINK-001",
|
||||
Error,
|
||||
"引用目标缺失、歧义、无效或越界",
|
||||
"读者无法到达所声明的目标,或目标不唯一。",
|
||||
"修正引用地址或目标,歧义时不要任选第一个候选。",
|
||||
"Analysis references[].state 为 missing/ambiguous/invalid/outside_scope。",
|
||||
Manual
|
||||
),
|
||||
rule!(
|
||||
"MQD-LINK-002",
|
||||
Info,
|
||||
"本地引用未在当前范围核验",
|
||||
"普通 Analysis 只验证已加载模块,未加载不等于断链。",
|
||||
"需要核验时显式运行 check --refs 或加载对应模块。",
|
||||
"Analysis references[].state 为 not_loaded。",
|
||||
Manual
|
||||
),
|
||||
rule!(
|
||||
"MQD-LINK-003",
|
||||
Info,
|
||||
"外部引用未联网核验",
|
||||
"Lint 不访问网络,外部 URI 只作信息提示。",
|
||||
"如需确认外部目标,请在文档评审中人工检查。",
|
||||
"Analysis references[].state 为 external。",
|
||||
Manual
|
||||
),
|
||||
rule!(
|
||||
"MQD-CALL-001",
|
||||
Info,
|
||||
"调用目标未静态绑定",
|
||||
"动态调用或无法静态绑定的目标不影响 Analysis 的有效性。",
|
||||
"当调用是公开接口时,补充说明其目标和约束。",
|
||||
"Analysis calls[].state 为 unresolved 及 reason。",
|
||||
Manual
|
||||
),
|
||||
rule!(
|
||||
"MQD-SAFETY-001",
|
||||
Error,
|
||||
@@ -229,9 +265,11 @@ mod tests {
|
||||
#[test]
|
||||
fn catalog_has_stable_unique_ids() {
|
||||
let ids: BTreeSet<_> = CATALOG.iter().map(|rule| rule.id).collect();
|
||||
assert_eq!(CATALOG.len(), 18);
|
||||
assert_eq!(CATALOG.len(), 22);
|
||||
assert_eq!(ids.len(), CATALOG.len());
|
||||
assert!(ids.contains("MQD-BRANCH-001"));
|
||||
assert!(ids.contains("MQD-SAFETY-001"));
|
||||
assert!(ids.contains("MQD-LINK-001"));
|
||||
assert!(ids.contains("MQD-CALL-001"));
|
||||
}
|
||||
}
|
||||
+107
-24
@@ -1,15 +1,14 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
alignment::{node_span, ReadableControlTree},
|
||||
alignment::ReadableControlTree,
|
||||
diagnostics::Diagnostic,
|
||||
input::{CheckDiagnostic, SourceDocument},
|
||||
metrics::narrative_count,
|
||||
model::{
|
||||
effect_sites, statements, AnalysisFunction, Carrier, CarrierKind, HeadingMode,
|
||||
HeadingSegment, MarkdownTree, ProseFragment, Span, StatementKind,
|
||||
effect_sites, statements, AnalysisCall, AnalysisFunction, Carrier, CarrierKind,
|
||||
HeadingMode, HeadingSegment, MarkdownTree, ProseFragment, ReferenceState, Span,
|
||||
StatementKind,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -17,13 +16,105 @@ pub fn check_ast_document(document: &SourceDocument) -> Vec<Diagnostic> {
|
||||
let markdown = &document.markdown;
|
||||
let mut diagnostics = prose_rule(markdown);
|
||||
diagnostics.extend(knowledge_rule(markdown));
|
||||
diagnostics.extend(reference_rules(document));
|
||||
diagnostics.extend(call_rules(document));
|
||||
diagnostics
|
||||
}
|
||||
|
||||
fn reference_rules(document: &SourceDocument) -> Vec<Diagnostic> {
|
||||
let Some(module) = &document.module else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut diagnostics = Vec::new();
|
||||
for reference in &module.references {
|
||||
let function = module
|
||||
.units
|
||||
.iter()
|
||||
.find(|unit| unit.id == reference.source_unit)
|
||||
.and_then(|unit| unit.function.as_deref())
|
||||
.and_then(|function_id| {
|
||||
module
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.id == function_id)
|
||||
.map(|function| function.local_name.as_str())
|
||||
});
|
||||
let diagnostic = match reference.state {
|
||||
ReferenceState::Missing => Some(
|
||||
Diagnostic::new("MQD-LINK-001", reference.span)
|
||||
.with_message(format!("引用目标缺失:{}", reference.url)),
|
||||
),
|
||||
ReferenceState::Ambiguous => Some(
|
||||
Diagnostic::new("MQD-LINK-001", reference.span).with_message(format!(
|
||||
"引用目标有多个候选,不能任选其一:{}({})",
|
||||
reference.url,
|
||||
reference.candidates.join(", ")
|
||||
)),
|
||||
),
|
||||
ReferenceState::Invalid => Some(
|
||||
Diagnostic::new("MQD-LINK-001", reference.span)
|
||||
.with_message(format!("引用地址无效:{}", reference.url)),
|
||||
),
|
||||
ReferenceState::OutsideScope => Some(
|
||||
Diagnostic::new("MQD-LINK-001", reference.span)
|
||||
.with_message(format!("引用目标越出项目范围:{}", reference.url)),
|
||||
),
|
||||
ReferenceState::NotLoaded => Some(
|
||||
Diagnostic::new("MQD-LINK-002", reference.span).with_message(format!(
|
||||
"引用未在当前 Analysis 范围核验(未加载,不等于断链):{}",
|
||||
reference.url
|
||||
)),
|
||||
),
|
||||
ReferenceState::External => Some(
|
||||
Diagnostic::new("MQD-LINK-003", reference.span)
|
||||
.with_message(format!("外部引用不联网核验:{}", reference.url)),
|
||||
),
|
||||
ReferenceState::Resolved => None,
|
||||
};
|
||||
let Some(mut diagnostic) = diagnostic else {
|
||||
continue;
|
||||
};
|
||||
if let Some(function) = function {
|
||||
diagnostic = diagnostic.with_function(function);
|
||||
}
|
||||
diagnostics.push(diagnostic);
|
||||
}
|
||||
diagnostics
|
||||
}
|
||||
|
||||
fn call_rules(document: &SourceDocument) -> Vec<Diagnostic> {
|
||||
let Some(module) = &document.module else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut diagnostics = Vec::new();
|
||||
for call in &module.calls {
|
||||
if call.state != crate::model::CallState::Unresolved {
|
||||
continue;
|
||||
}
|
||||
let function = module
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.id == call.function)
|
||||
.map(|function| function.local_name.as_str());
|
||||
let reason = match call.reason {
|
||||
Some(crate::model::CallReason::Dynamic) => "动态调用",
|
||||
Some(crate::model::CallReason::Unbound) => "静态目标未绑定",
|
||||
None => "未绑定",
|
||||
};
|
||||
let mut diagnostic = Diagnostic::new("MQD-CALL-001", call.span)
|
||||
.with_message(format!("调用目标未静态绑定({reason});这不是错误"));
|
||||
if let Some(function) = function {
|
||||
diagnostic = diagnostic.with_function(function);
|
||||
}
|
||||
diagnostics.push(diagnostic);
|
||||
}
|
||||
diagnostics
|
||||
}
|
||||
|
||||
pub(crate) fn check_supplemental_function(
|
||||
markdown: &MarkdownTree,
|
||||
function: &AnalysisFunction,
|
||||
calls: &[Value],
|
||||
calls: &[AnalysisCall],
|
||||
tree: &ReadableControlTree,
|
||||
) -> Vec<Diagnostic> {
|
||||
let mut diagnostics = effect_rule(markdown, function, calls);
|
||||
@@ -222,13 +313,11 @@ fn knowledge_rule(markdown: &MarkdownTree) -> Vec<Diagnostic> {
|
||||
fn effect_rule(
|
||||
markdown: &MarkdownTree,
|
||||
analysis: &AnalysisFunction,
|
||||
calls: &[Value],
|
||||
calls: &[AnalysisCall],
|
||||
) -> Vec<Diagnostic> {
|
||||
let carriers = function_carriers(markdown, analysis);
|
||||
let prose = markdown
|
||||
.headings
|
||||
.iter()
|
||||
.find(|heading| markdown.nodes[heading.node].span == analysis.heading_span)
|
||||
.function_segment(&analysis.id)
|
||||
.map(|heading| markdown.prose_fragments(heading.node))
|
||||
.unwrap_or_default();
|
||||
let anchors: BTreeSet<_> = effect_sites(analysis, calls)
|
||||
@@ -243,13 +332,10 @@ fn effect_rule(
|
||||
}
|
||||
|
||||
fn parameter_rule(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> Vec<Diagnostic> {
|
||||
if analysis.signature.get("kind").and_then(Value::as_str) != Some("explicit") {
|
||||
if analysis.signature.kind != crate::model::SignatureKind::Explicit {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(params) = analysis.signature.get("params").and_then(Value::as_array) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if params.is_empty() {
|
||||
if analysis.signature.params.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let carriers = function_carriers(markdown, analysis);
|
||||
@@ -263,9 +349,11 @@ fn parameter_rule(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> Vec<D
|
||||
if has_nearby_prose(markdown, &carriers, &prose, signature) {
|
||||
return Vec::new();
|
||||
}
|
||||
params
|
||||
analysis
|
||||
.signature
|
||||
.params
|
||||
.iter()
|
||||
.filter_map(|param| node_span(param))
|
||||
.map(|param| param.span)
|
||||
.map(|span| {
|
||||
Diagnostic::new("MQD-PARAM-001", span)
|
||||
.with_related(signature.span)
|
||||
@@ -290,7 +378,7 @@ fn style_rule(
|
||||
Some((statement.span, kind))
|
||||
})
|
||||
.collect();
|
||||
if analysis.signature.get("kind").and_then(Value::as_str) == Some("explicit") {
|
||||
if analysis.signature.kind == crate::model::SignatureKind::Explicit {
|
||||
if let Some(signature) = carriers.first() {
|
||||
expected.insert(signature.span, CarrierKind::Code);
|
||||
}
|
||||
@@ -329,12 +417,7 @@ fn function_carriers<'a>(
|
||||
markdown: &'a MarkdownTree,
|
||||
analysis: &AnalysisFunction,
|
||||
) -> Vec<&'a Carrier> {
|
||||
let Some(function) = markdown
|
||||
.headings
|
||||
.iter()
|
||||
.find(|heading| markdown.nodes[heading.node].span == analysis.heading_span)
|
||||
.map(|heading| heading.node)
|
||||
else {
|
||||
let Some(function) = markdown.function_heading(&analysis.id) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut carriers: Vec<_> = markdown
|
||||
|
||||
Reference in new issue
Block a user