diff --git a/schemas/marqdo-lint-v1.schema.json b/schemas/marqdo-lint-v1.schema.json new file mode 100644 index 0000000..514095b --- /dev/null +++ b/schemas/marqdo-lint-v1.schema.json @@ -0,0 +1,92 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://cflmy.cn/marqdo-lint/marqdo-lint-v1.schema.json", + "title": "Marqdo Lint v1", + "oneOf": [ + {"$ref": "#/$defs/document"}, + {"$ref": "#/$defs/run"} + ], + "$defs": { + "span": { + "type": "object", + "required": ["start", "end"], + "properties": { + "start": {"type": "integer", "minimum": 0}, + "end": {"type": "integer", "minimum": 0} + }, + "additionalProperties": false + }, + "diagnostic": { + "type": "object", + "required": ["id", "severity", "span", "related_spans", "message", "reason", "suggestion", "fix_safety"], + "properties": { + "id": {"type": "string", "pattern": "^MQD-[A-Z]+-[0-9]{3}$"}, + "severity": {"enum": ["info", "warning", "error"]}, + "span": {"$ref": "#/$defs/span"}, + "related_spans": {"type": "array", "items": {"$ref": "#/$defs/span"}}, + "message": {"type": "string"}, + "reason": {"type": "string"}, + "suggestion": {"type": "string"}, + "fix_safety": {"enum": ["manual", "safe_only", "not_applicable"]}, + "function": {"type": "string"} + }, + "additionalProperties": false + }, + "metrics": { + "type": "object", + "required": ["narrative_ratio", "measurement_version", "functions"], + "properties": { + "narrative_ratio": {"type": ["number", "null"], "minimum": 0, "maximum": 1}, + "measurement_version": {"const": 1}, + "functions": {"type": "array", "items": {"type": "object"}} + }, + "additionalProperties": false + }, + "document": { + "type": "object", + "required": ["schema", "schema_version", "source", "diagnostics", "analysis_status", "metrics"], + "properties": { + "schema": {"const": "marqdo.lint"}, + "schema_version": {"const": 1}, + "source": { + "type": "object", + "required": ["path", "digest"], + "properties": { + "path": {"type": "string"}, + "digest": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"} + }, + "additionalProperties": false + }, + "diagnostics": {"type": "array", "items": {"$ref": "#/$defs/diagnostic"}}, + "analysis_status": {"enum": ["complete", "analysis_incomplete"]}, + "metrics": {"$ref": "#/$defs/metrics"}, + "notices": {"type": "array", "items": {"type": "string"}}, + "core_output": {"type": "string"} + }, + "additionalProperties": false + }, + "summary": { + "type": "object", + "required": ["files", "info", "warnings", "errors", "analysis_incomplete"], + "properties": { + "files": {"type": "integer", "minimum": 0}, + "info": {"type": "integer", "minimum": 0}, + "warnings": {"type": "integer", "minimum": 0}, + "errors": {"type": "integer", "minimum": 0}, + "analysis_incomplete": {"type": "integer", "minimum": 0} + }, + "additionalProperties": false + }, + "run": { + "type": "object", + "required": ["schema", "schema_version", "reports", "summary"], + "properties": { + "schema": {"const": "marqdo.lint"}, + "schema_version": {"const": 1}, + "reports": {"type": "array", "items": {"$ref": "#/$defs/document"}}, + "summary": {"$ref": "#/$defs/summary"} + }, + "additionalProperties": false + } + } +} diff --git a/scripts/package-tool.sh b/scripts/package-tool.sh new file mode 100755 index 0000000..42321be --- /dev/null +++ b/scripts/package-tool.sh @@ -0,0 +1,15 @@ +#!/bin/sh +set -eu + +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +DEST=${1:-"$ROOT/.cache/tool-bundle"} +export CARGO_HOME=${CARGO_HOME:-"$ROOT/.cache/cargo-home"} +export CARGO_TARGET_DIR=${CARGO_TARGET_DIR:-"$ROOT/.cache/marqdo-lint-release-target"} +export TMPDIR=${TMPDIR:-"$ROOT/.cache/tmp"} + +mkdir -p "$TMPDIR" "$DEST/bin" +cargo build --locked --release --manifest-path "$ROOT/Cargo.toml" +install -m 755 "$CARGO_TARGET_DIR/release/marqdo-lint" "$DEST/bin/marqdo-lint" +cp "$ROOT/tool.json" "$DEST/tool.json" +sha256sum "$DEST/bin/marqdo-lint" +printf 'Tool bundle: %s\n' "$DEST" diff --git a/src/cli/mod.rs b/src/cli/mod.rs new file mode 100644 index 0000000..2ceeaa4 --- /dev/null +++ b/src/cli/mod.rs @@ -0,0 +1,252 @@ +use std::{collections::BTreeSet, fs, path::PathBuf}; + +use clap::{Parser, Subcommand, ValueEnum}; +use walkdir::WalkDir; + +use crate::{ + config::{LintConfig, Profile}, + diagnostics::{DocumentReport, FailOn, LintRun}, + engine::analyze_document, + error::{io, LintError, Result}, + input::{MarqdoRunner, ProjectInput}, + rules, +}; + +#[derive(Debug, Parser)] +#[command(name = "marqdo-lint", version, about = "检查 Marqdo 可执行文档的阅读结构与说明")] +pub struct Cli { + #[command(subcommand)] + command: Option, + #[arg(value_name = "PATH", default_value = ".")] + paths: Vec, + #[arg(long, value_enum, default_value = "human", global = true)] + format: OutputFormat, + #[arg(long, value_enum)] + profile: Option, + #[arg(long, value_name = "FILE")] + config: Option, + #[arg(long, value_enum, default_value = "warning")] + fail_on: FailOnArg, + #[arg(long, value_enum, value_name = "MODE")] + fix: Option, +} + +#[derive(Debug, Subcommand)] +enum Command { + Explain { + #[arg(value_name = "RULE_ID")] + rule: String, + }, + Rules, +} + +#[derive(Debug, Clone, Copy, ValueEnum)] +enum OutputFormat { + Human, + Json, +} + +#[derive(Debug, Clone, Copy, ValueEnum)] +enum ProfileArg { + Recommended, + StrictDoc, + Minimal, + Migration, +} + +impl From for Profile { + fn from(value: ProfileArg) -> Self { + match value { + ProfileArg::Recommended => Self::Recommended, + ProfileArg::StrictDoc => Self::StrictDoc, + ProfileArg::Minimal => Self::Minimal, + ProfileArg::Migration => Self::Migration, + } + } +} + +#[derive(Debug, Clone, Copy, ValueEnum)] +enum FailOnArg { + Never, + Info, + Warning, + Error, +} + +impl From for FailOn { + fn from(value: FailOnArg) -> Self { + match value { + FailOnArg::Never => Self::Never, + FailOnArg::Info => Self::Info, + FailOnArg::Warning => Self::Warning, + FailOnArg::Error => Self::Error, + } + } +} + +#[derive(Debug, Clone, Copy, ValueEnum)] +enum FixMode { + Safe, +} + +pub fn run() -> Result { + let cli = Cli::parse(); + if let Some(command) = cli.command { + return match command { + Command::Explain { rule } => explain(&rule, cli.format), + Command::Rules => list_rules(cli.format), + }; + } + if cli.fix.is_some() { + return Err(LintError::Config( + "当前构建尚未启用写回;请使用人工建议".into(), + )); + } + let config = LintConfig::discover(cli.config.as_deref())?; + let effective = config.resolve(cli.profile.map(Into::into))?; + let entries = discover_entries(&cli.paths)?; + let runner = MarqdoRunner::discover(None)?; + let mut run = LintRun::default(); + let mut inspected = BTreeSet::new(); + for entry in entries { + if inspected.contains(&entry) { + continue; + } + let project = ProjectInput::load(&entry, &runner)?; + for (index, document) in project.documents.iter().enumerate() { + if !inspected.insert(document.source.path.clone()) { + continue; + } + let path = logical_path(&project, index); + let analysis = analyze_document(document, &effective); + run.reports.push(DocumentReport::new( + document, + project.analysis_status, + path, + analysis, + &effective, + project.notices.clone(), + if document.source.path == project.entry { + project.core_output.clone() + } else { + String::new() + }, + )?); + } + } + run.reports + .sort_by(|left, right| left.source.path.cmp(&right.source.path)); + match cli.format { + OutputFormat::Human => print!("{}", run.render_human()), + OutputFormat::Json => println!("{}", run.render_json()?), + } + Ok(run.exit_code(cli.fail_on.into())) +} + +fn explain(id: &str, format: OutputFormat) -> Result { + let rule = rules::find(id) + .ok_or_else(|| LintError::Config(format!("未知 Rule ID:{id}")))?; + match format { + OutputFormat::Human => println!( + "{}\n级别:{:?}\n{}\n损失:{}\n建议:{}\n依据:{}\n修复:{:?}", + rule.id, + rule.default_severity, + rule.summary, + rule.reason, + rule.suggestion, + rule.evidence, + rule.fix_safety + ), + OutputFormat::Json => println!( + "{}", + serde_json::to_string_pretty(rule) + .map_err(|error| LintError::Protocol(error.to_string()))? + ), + } + Ok(0) +} + +fn list_rules(format: OutputFormat) -> Result { + match format { + OutputFormat::Human => { + for rule in rules::CATALOG { + println!("{} {:?} {}", rule.id, rule.default_severity, rule.summary); + } + } + OutputFormat::Json => println!( + "{}", + serde_json::to_string_pretty(rules::CATALOG) + .map_err(|error| LintError::Protocol(error.to_string()))? + ), + } + Ok(0) +} + +fn discover_entries(paths: &[PathBuf]) -> Result> { + let mut entries = BTreeSet::new(); + for path in paths { + if path.is_file() { + entries.insert(path.clone()); + continue; + } + if !path.is_dir() { + return Err(LintError::Config(format!( + "输入路径不存在或不是普通文件/目录:{}", + path.display() + ))); + } + let index = path.join("index.mq.md"); + if index.is_file() { + entries.insert(index); + continue; + } + for entry in WalkDir::new(path) + .follow_links(false) + .into_iter() + .filter_entry(|entry| { + !matches!( + entry.file_name().to_str(), + Some(".git" | ".cache" | "target") + ) + }) + { + let entry = entry.map_err(|error| LintError::Config(error.to_string()))?; + if entry.file_type().is_file() + && entry + .path() + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.ends_with(".mq.md")) + { + entries.insert(entry.path().to_path_buf()); + } + } + } + if entries.is_empty() { + return Err(LintError::Config("没有找到 .mq.md 输入".into())); + } + let mut entries = entries.into_iter() + .map(|path| fs::canonicalize(&path).map_err(|error| io(path, error))) + .collect::>>()?; + // Load conventional entry points before modules that they may already cover. + entries.sort_by_key(|path| (path.file_name().is_none_or(|name| name != "index.mq.md"), path.clone())); + entries.dedup(); + Ok(entries) +} + +fn logical_path(project: &ProjectInput, index: usize) -> String { + let document = &project.documents[index]; + let cwd = std::env::current_dir().ok(); + cwd.and_then(|cwd| { + document + .source + .path + .strip_prefix(cwd) + .ok() + .map(|path| path.to_string_lossy().into_owned()) + }) + .or_else(|| { + document.module.as_ref().map(|module| module.relative_path.clone()) + }) + .unwrap_or_else(|| document.source.path.to_string_lossy().into_owned()) +} diff --git a/src/config/mod.rs b/src/config/mod.rs new file mode 100644 index 0000000..88807f9 --- /dev/null +++ b/src/config/mod.rs @@ -0,0 +1,289 @@ +use std::{collections::BTreeMap, fs, path::Path}; + +use serde::{Deserialize, Serialize}; + +use crate::{ + diagnostics::Diagnostic, + error::{io, LintError, Result}, + metrics::NarrativeConfig, + model::Span, + rules::{self, Severity}, +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Profile { + 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 { + Off, + Info, + Warning, + Error, +} + +impl RuleLevel { + fn severity(self) -> Option { + match self { + Self::Off => None, + Self::Info => Some(Severity::Info), + Self::Warning => Some(Severity::Warning), + Self::Error => Some(Severity::Error), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Suppression { + pub path: String, + pub rule: String, + pub reason: String, + pub function: Option, + pub span: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +#[serde(deny_unknown_fields)] +pub struct FixConfig { + pub mode: String, + pub require_semantic_equivalence: bool, +} + +impl Default for FixConfig { + fn default() -> Self { + Self { + mode: "safe-only".into(), + require_semantic_equivalence: true, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +#[serde(deny_unknown_fields)] +pub struct LintConfig { + pub schema_version: u32, + pub profile: Profile, + pub min_narrative_ratio: f64, + pub short_function_max_statements: usize, + pub rules: BTreeMap, + #[serde(rename = "suppress", alias = "suppressions")] + pub suppressions: Vec, + pub fix: FixConfig, +} + +impl Default for LintConfig { + fn default() -> Self { + Self { + schema_version: 1, + profile: Profile::Recommended, + min_narrative_ratio: 0.50, + short_function_max_statements: 4, + rules: BTreeMap::new(), + suppressions: Vec::new(), + fix: FixConfig::default(), + } + } +} + +#[derive(Debug, Clone)] +pub struct EffectiveConfig { + pub profile: Profile, + pub narrative: NarrativeConfig, + pub levels: BTreeMap, + pub suppressions: Vec, + pub fix: FixConfig, +} + +impl EffectiveConfig { + pub fn apply(&self, path: &str, diagnostics: &mut Vec) { + diagnostics.retain_mut(|diagnostic| { + if let Some(level) = self.levels.get(&diagnostic.id).copied() { + let Some(severity) = level.severity() else { + return false; + }; + diagnostic.severity = severity; + } + !self.is_suppressed(path, diagnostic) + }); + } + + pub fn is_suppressed(&self, path: &str, diagnostic: &Diagnostic) -> bool { + self.suppressions.iter().any(|suppression| { + normalize_path(&suppression.path) == normalize_path(path) + && suppression.rule == diagnostic.id + && suppression + .function + .as_ref() + .is_none_or(|function| Some(function) == diagnostic.function.as_ref()) + && suppression + .span + .is_none_or(|span| span == diagnostic.span) + }) + } +} + +impl LintConfig { + pub fn load(path: &Path) -> Result { + let text = fs::read_to_string(path).map_err(|error| io(path, error))?; + let config: Self = toml::from_str(&text) + .map_err(|error| LintError::Config(format!("{}:{error}", path.display())))?; + config.validate()?; + Ok(config) + } + + pub fn discover(explicit: Option<&Path>) -> Result { + if let Some(path) = explicit { + return Self::load(path); + } + let path = Path::new("marqdo-lint.toml"); + if path.is_file() { + Self::load(path) + } else { + Ok(Self::default()) + } + } + + pub fn resolve(&self, profile_override: Option) -> Result { + self.validate()?; + let profile = profile_override.unwrap_or(self.profile); + let mut levels = BTreeMap::new(); + match profile { + Profile::Recommended => {} + Profile::StrictDoc => { + for id in [ + "MQD-DOC-002", + "MQD-DOC-004", + "MQD-BRANCH-004", + "MQD-LOOP-002", + "MQD-PROSE-002", + "MQD-PARAM-001", + ] { + levels.insert(id.into(), RuleLevel::Warning); + } + } + Profile::Minimal => { + for id in [ + "MQD-DOC-001", + "MQD-DOC-002", + "MQD-DOC-003", + "MQD-DOC-004", + "MQD-BRANCH-004", + "MQD-LOOP-002", + "MQD-PROSE-002", + "MQD-PARAM-001", + "MQD-STYLE-001", + ] { + levels.insert(id.into(), RuleLevel::Off); + } + } + Profile::Migration => { + levels.insert("MQD-STYLE-001".into(), RuleLevel::Off); + levels.insert("MQD-PROSE-001".into(), RuleLevel::Off); + levels.insert("MQD-DOC-003".into(), RuleLevel::Info); + } + } + for (id, level) in &self.rules { + levels.insert(id.clone(), *level); + } + Ok(EffectiveConfig { + profile, + narrative: NarrativeConfig { + threshold: self.min_narrative_ratio, + short_function_threshold: self.short_function_max_statements, + }, + levels, + suppressions: self.suppressions.clone(), + fix: self.fix.clone(), + }) + } + + fn validate(&self) -> Result<()> { + if self.schema_version != 1 { + return Err(LintError::Config(format!( + "只支持 schema_version=1,实际为 {}", + self.schema_version + ))); + } + if !self.min_narrative_ratio.is_finite() + || !(0.0..=1.0).contains(&self.min_narrative_ratio) + { + return Err(LintError::Config( + "min_narrative_ratio 必须位于 0.0..=1.0".into(), + )); + } + if self.short_function_max_statements == 0 { + return Err(LintError::Config( + "short_function_max_statements 必须大于零".into(), + )); + } + for id in self.rules.keys() { + if rules::find(id).is_none() { + return Err(LintError::Config(format!("未知 Rule ID:{id}"))); + } + } + for suppression in &self.suppressions { + if suppression.path.trim().is_empty() || suppression.reason.trim().is_empty() { + return Err(LintError::Config( + "每条抑制必须具有非空 path 和 reason".into(), + )); + } + if rules::find(&suppression.rule).is_none() { + return Err(LintError::Config(format!( + "抑制使用未知 Rule ID:{}", + suppression.rule + ))); + } + } + if self.fix.mode != "safe-only" || !self.fix.require_semantic_equivalence { + return Err(LintError::Config( + "修复仅支持 safe-only 且必须要求语义等价".into(), + )); + } + Ok(()) + } +} + +fn normalize_path(path: &str) -> String { + path.replace('\\', "/") + .trim_start_matches("./") + .to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn validates_rule_ids_thresholds_and_suppression_reasons() { + 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; + assert!(config.validate().is_err()); + let mut config = LintConfig::default(); + config.suppressions.push(Suppression { + path: "index.mq.md".into(), + rule: "MQD-DOC-001".into(), + reason: " ".into(), + function: None, + span: None, + }); + assert!(config.validate().is_err()); + } +} diff --git a/src/diagnostics/mod.rs b/src/diagnostics/mod.rs index d88a531..713ade0 100644 --- a/src/diagnostics/mod.rs +++ b/src/diagnostics/mod.rs @@ -1,3 +1,7 @@ +mod report; + +pub use report::{DocumentReport, FailOn, LintRun, MetricsReport, RunReport, Summary}; + use serde::{Deserialize, Serialize}; use crate::{ diff --git a/src/diagnostics/report.rs b/src/diagnostics/report.rs new file mode 100644 index 0000000..9c46124 --- /dev/null +++ b/src/diagnostics/report.rs @@ -0,0 +1,235 @@ +use serde::Serialize; + +use crate::{ + config::EffectiveConfig, + diagnostics::Diagnostic, + engine::DocumentAnalysis, + error::Result, + input::{AnalysisStatus, MarkdownOrigin, SourceDocument}, + metrics::{FunctionNarrative, MEASUREMENT_VERSION}, + model::LineColumn, + rules::Severity, +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FailOn { + Never, + Info, + Warning, + Error, +} + +#[derive(Debug, Serialize)] +pub struct SourceReport { + pub path: String, + pub digest: String, +} + +#[derive(Debug, Serialize)] +pub struct MetricsReport { + pub narrative_ratio: Option, + pub measurement_version: u8, + pub functions: Vec, +} + +#[derive(Debug, Serialize)] +pub struct DocumentReport { + pub schema: &'static str, + pub schema_version: u8, + pub source: SourceReport, + pub diagnostics: Vec, + pub analysis_status: AnalysisStatus, + pub metrics: MetricsReport, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub notices: Vec, + #[serde(skip_serializing_if = "String::is_empty")] + pub core_output: String, + #[serde(skip)] + locations: Vec, +} + +impl DocumentReport { + pub fn new( + document: &SourceDocument, + mut analysis_status: AnalysisStatus, + path: String, + mut analysis: DocumentAnalysis, + config: &EffectiveConfig, + mut notices: Vec, + core_output: String, + ) -> Result { + if document.module.is_none() + || document.markdown_origin != MarkdownOrigin::MarqdoInspect + || !analysis.alignment_issues.is_empty() + { + analysis_status = AnalysisStatus::AnalysisIncomplete; + } + notices.append(&mut analysis.alignment_issues); + config.apply(&path, &mut analysis.diagnostics); + let locations = analysis + .diagnostics + .iter() + .map(|diagnostic| document.source.line_column(diagnostic.span.start)) + .collect::>>()?; + let narrative_ratio = (analysis.metrics.len() == 1) + .then(|| analysis.metrics[0].ratio) + .flatten(); + Ok(Self { + schema: "marqdo.lint", + schema_version: 1, + source: SourceReport { + path, + digest: document.source.digest.clone(), + }, + diagnostics: analysis.diagnostics, + analysis_status, + metrics: MetricsReport { + narrative_ratio, + measurement_version: MEASUREMENT_VERSION, + functions: analysis.metrics, + }, + notices, + core_output, + locations, + }) + } + + pub fn render_human(&self) -> String { + let mut output = String::new(); + for notice in &self.notices { + output.push_str(&format!("notice: {notice}\n")); + } + if !self.core_output.is_empty() { + output.push_str(&self.core_output); + output.push('\n'); + } + for (index, diagnostic) in self.diagnostics.iter().enumerate() { + let location = self.locations[index]; + output.push_str(&format!( + "{}:{}:{} {} {}\n {}\n 损失:{}\n 建议:{}\n 修复:{}\n", + self.source.path, + location.line, + location.column, + severity_name(diagnostic.severity), + diagnostic.id, + diagnostic.message, + diagnostic.reason, + diagnostic.suggestion, + match diagnostic.fix_safety { + crate::rules::FixSafety::Manual => "manual", + crate::rules::FixSafety::SafeOnly => "safe_only", + crate::rules::FixSafety::NotApplicable => "not_applicable", + } + )); + } + if self.diagnostics.is_empty() + && self.analysis_status == AnalysisStatus::Complete + && self.core_output.is_empty() + { + output.push_str(&format!("{}:未检测到 Lint 违规\n", self.source.path)); + } + output + } +} + +#[derive(Debug, Default, Serialize)] +pub struct Summary { + pub files: usize, + pub info: usize, + pub warnings: usize, + pub errors: usize, + pub analysis_incomplete: usize, +} + +#[derive(Debug, Serialize)] +pub struct RunReport<'a> { + pub schema: &'static str, + pub schema_version: u8, + pub reports: &'a [DocumentReport], + pub summary: Summary, +} + +#[derive(Debug, Default)] +pub struct LintRun { + pub reports: Vec, +} + +impl LintRun { + pub fn summary(&self) -> Summary { + let mut summary = Summary { + files: self.reports.len(), + ..Summary::default() + }; + for report in &self.reports { + if report.analysis_status == AnalysisStatus::AnalysisIncomplete { + summary.analysis_incomplete += 1; + } + for diagnostic in &report.diagnostics { + match diagnostic.severity { + Severity::Info => summary.info += 1, + Severity::Warning => summary.warnings += 1, + Severity::Error => summary.errors += 1, + } + } + } + summary + } + + pub fn render_human(&self) -> String { + let mut output = self + .reports + .iter() + .map(DocumentReport::render_human) + .collect::(); + let summary = self.summary(); + output.push_str(&format!( + "检查 {} 个文件:{} info,{} warning,{} error,{} 个分析不完整\n", + summary.files, + summary.info, + summary.warnings, + summary.errors, + summary.analysis_incomplete + )); + output + } + + pub fn render_json(&self) -> Result { + if self.reports.len() == 1 { + return serde_json::to_string_pretty(&self.reports[0]) + .map_err(|error| crate::error::LintError::Protocol(error.to_string())); + } + serde_json::to_string_pretty(&RunReport { + schema: "marqdo.lint", + schema_version: 1, + reports: &self.reports, + summary: self.summary(), + }) + .map_err(|error| crate::error::LintError::Protocol(error.to_string())) + } + + pub fn exit_code(&self, fail_on: FailOn) -> i32 { + if self.reports.iter().any(|report| report.analysis_status == AnalysisStatus::AnalysisIncomplete) { + return 2; + } + let failed = self.reports.iter().any(|report| { + report.diagnostics.iter().any(|diagnostic| { + match (fail_on, diagnostic.severity) { + (FailOn::Never, _) => false, + (FailOn::Info, _) => true, + (FailOn::Warning, Severity::Warning | Severity::Error) => true, + (FailOn::Error, Severity::Error) => true, + _ => false, + } + }) + }); + i32::from(failed) + } +} + +fn severity_name(severity: Severity) -> &'static str { + match severity { + Severity::Info => "info", + Severity::Warning => "warning", + Severity::Error => "error", + } +} diff --git a/src/engine.rs b/src/engine.rs new file mode 100644 index 0000000..7e38e98 --- /dev/null +++ b/src/engine.rs @@ -0,0 +1,61 @@ +use crate::{ + alignment::align_function, + config::EffectiveConfig, + diagnostics::Diagnostic, + input::{MarkdownOrigin, SourceDocument}, + metrics::{measure_document, FunctionNarrative}, + rules::{ + check_aligned, check_ast_document, check_documentation, check_entry_without_analysis, + check_semantic_document, + }, +}; + +#[derive(Debug, Clone)] +pub struct DocumentAnalysis { + pub diagnostics: Vec, + pub metrics: Vec, + pub alignment_issues: Vec, +} + +pub fn analyze_document(document: &SourceDocument, config: &EffectiveConfig) -> DocumentAnalysis { + let mut alignment_issues = Vec::new(); + let module = document.module.as_ref() + .filter(|_| document.markdown_origin == MarkdownOrigin::MarqdoInspect); + let mut diagnostics = if let Some(module) = module { + let mut diagnostics = Vec::new(); + for function in &module.functions { + let tree = align_function(&document.markdown, function); + if tree.complete { + diagnostics.extend(check_aligned(&document.markdown, function, &tree)); + } else { + alignment_issues.extend(tree.issues.iter().map(|issue| { + format!("{}:{}", function.local_name, issue) + })); + } + } + diagnostics.extend(check_documentation(document, config.narrative)); + diagnostics.extend(check_semantic_document(document)); + diagnostics + } else { + let mut diagnostics = check_ast_document(document); + diagnostics.extend(check_entry_without_analysis(document)); + diagnostics + }; + diagnostics.sort_by(|left, right| { + (left.span.start, left.span.end, &left.id).cmp(&( + right.span.start, + right.span.end, + &right.id, + )) + }); + let metrics = if module.is_some() { + measure_document(document, config.narrative) + } else { + Vec::new() + }; + DocumentAnalysis { + diagnostics, + metrics, + alignment_issues, + } +} diff --git a/src/lib.rs b/src/lib.rs index f48fae0..1884c36 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,8 @@ pub mod alignment; +pub mod cli; +pub mod config; pub mod diagnostics; +pub mod engine; pub mod error; pub mod input; pub mod metrics; diff --git a/src/main.rs b/src/main.rs index 65109c2..3629d4c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,9 @@ -fn main() { - println!("marqdo-lint {}", marqdo_lint::VERSION); +fn main() -> std::process::ExitCode { + match marqdo_lint::cli::run() { + Ok(code) => std::process::ExitCode::from(code as u8), + Err(error) => { + eprintln!("error: {error}"); + std::process::ExitCode::from(2) + } + } } diff --git a/src/rules/control.rs b/src/rules/control.rs index eb320f3..ef8412b 100644 --- a/src/rules/control.rs +++ b/src/rules/control.rs @@ -30,18 +30,26 @@ pub fn check_function(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> V if !tree.complete { return Vec::new(); } + check_aligned(markdown, analysis, &tree) +} + +pub(crate) fn check_aligned( + markdown: &MarkdownTree, + analysis: &AnalysisFunction, + tree: &ReadableControlTree, +) -> Vec { let mut diagnostics = Vec::new(); for (index, control) in tree.controls.iter().enumerate() { match control.kind { ControlKind::Branch => { - branch_rules(markdown, analysis, &tree, control, &mut diagnostics) + branch_rules(markdown, analysis, tree, control, &mut diagnostics) } ControlKind::Loop => { - loop_rules(markdown, analysis, &tree, control, &mut diagnostics) + loop_rules(markdown, analysis, tree, control, &mut diagnostics) } } - nesting_rule(markdown, &tree, index, &mut diagnostics); - end_rule(markdown, &tree, control, &mut diagnostics); + nesting_rule(markdown, tree, index, &mut diagnostics); + end_rule(markdown, tree, control, &mut diagnostics); } diagnostics.sort_by(|left, right| { (left.span.start, left.span.end, &left.id).cmp(&( diff --git a/src/rules/mod.rs b/src/rules/mod.rs index 263e699..0bf7a26 100644 --- a/src/rules/mod.rs +++ b/src/rules/mod.rs @@ -1,8 +1,13 @@ mod control; mod documentation; +mod supplemental; +pub(crate) use control::check_aligned; pub use control::{check_document, check_function}; pub use documentation::{check_documentation, check_function_documentation}; +pub use supplemental::{ + check_ast_document, check_entry_without_analysis, check_semantic_document, +}; use serde::{Deserialize, Serialize}; @@ -22,7 +27,7 @@ pub enum FixSafety { NotApplicable, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct RuleSpec { pub id: &'static str, pub default_severity: Severity, diff --git a/src/rules/supplemental.rs b/src/rules/supplemental.rs new file mode 100644 index 0000000..4f7d296 --- /dev/null +++ b/src/rules/supplemental.rs @@ -0,0 +1,284 @@ +use std::collections::BTreeMap; + +use serde_json::Value; + +use crate::{ + alignment::{align_function, node_span, ControlKind}, + diagnostics::Diagnostic, + input::SourceDocument, + metrics::narrative_count, + model::{ + semantic_nodes, AnalysisFunction, Carrier, CarrierKind, HeadingMode, MarkdownTree, NodeId, + ProseFragment, + }, +}; + +pub fn check_ast_document(document: &SourceDocument) -> Vec { + let markdown = &document.markdown; + let mut diagnostics = prose_rule(markdown); + diagnostics.extend(knowledge_rule(markdown)); + diagnostics +} + +pub fn check_semantic_document(document: &SourceDocument) -> Vec { + let mut diagnostics = check_ast_document(document); + let Some(module) = &document.module else { + return diagnostics; + }; + for function in &module.functions { + diagnostics.extend(effect_rule(&document.markdown, function)); + diagnostics.extend(parameter_rule(&document.markdown, function)); + diagnostics.extend(style_rule(&document.markdown, function)); + } + diagnostics +} + +pub fn check_entry_without_analysis(document: &SourceDocument) -> Vec { + let markdown = &document.markdown; + let mut diagnostics = Vec::new(); + for heading in markdown + .headings + .iter() + .filter(|heading| heading.function == Some(heading.node)) + { + let carriers: Vec<_> = markdown + .carriers + .iter() + .filter(|carrier| carrier.function == Some(heading.node)) + .collect(); + let has_entry = markdown.prose_fragments(heading.node).iter().any(|fragment| { + narrative_count(&fragment.text) > 0 + && carriers + .first() + .is_none_or(|carrier| fragment.span.end <= carrier.span.start) + }); + if !has_entry { + diagnostics.push( + Diagnostic::new("MQD-DOC-001", markdown.nodes[heading.node].span) + .with_function(&heading.name), + ); + } + } + diagnostics +} + +fn prose_rule(markdown: &MarkdownTree) -> Vec { + let mut diagnostics = Vec::new(); + for carrier in &markdown.carriers { + let Some(function) = carrier.function else { + continue; + }; + let Some(paragraph) = markdown.nearest(carrier.node, "paragraph") else { + continue; + }; + let paragraph_span = markdown.nodes[paragraph].span; + let prose = markdown.prose_fragments(function); + let before = prose.iter().any(|fragment| { + paragraph_span.contains(fragment.span) + && fragment.span.end <= carrier.span.start + && narrative_count(&fragment.text) > 0 + }); + let after = prose.iter().any(|fragment| { + paragraph_span.contains(fragment.span) + && fragment.span.start >= carrier.span.end + && narrative_count(&fragment.text) > 0 + }); + if before && after { + let function_name = markdown + .heading(function) + .map(|heading| heading.name.as_str()) + .unwrap_or_default(); + diagnostics.push( + Diagnostic::new("MQD-PROSE-001", carrier.span) + .with_related(paragraph_span) + .with_function(function_name), + ); + } + } + diagnostics +} + +fn knowledge_rule(markdown: &MarkdownTree) -> Vec { + markdown + .headings + .iter() + .filter(|heading| { + heading.level > 2 + && heading.function.is_some() + && heading.mode == HeadingMode::Knowledge + }) + .map(|heading| { + let function = heading.function.and_then(|function| markdown.heading(function)); + let mut diagnostic = Diagnostic::new( + "MQD-KNOW-001", + markdown.nodes[heading.node].span, + ); + if let Some(function) = function { + diagnostic = diagnostic.with_function(&function.name); + } + diagnostic + }) + .collect() +} + +fn effect_rule(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> Vec { + let carriers = function_carriers(markdown, analysis); + let prose = markdown + .headings + .iter() + .find(|heading| markdown.nodes[heading.node].span == analysis.heading_span) + .map(|heading| markdown.prose_fragments(heading.node)) + .unwrap_or_default(); + semantic_nodes(&analysis.body) + .filter(|node| { + node.get("kind").and_then(Value::as_str) == Some("assign") + && node.get("target").is_some_and(Value::is_object) + }) + .filter_map(|node| node_span(node)) + .filter_map(|span| { + let carrier = carriers.iter().find(|carrier| carrier.span == span)?; + if has_nearby_prose(markdown, &carriers, &prose, carrier) { + return None; + } + Some( + Diagnostic::new("MQD-PROSE-002", span) + .with_function(&analysis.local_name), + ) + }) + .collect() +} + +fn parameter_rule(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> Vec { + if analysis.signature.get("kind").and_then(Value::as_str) != Some("explicit") { + return Vec::new(); + } + let Some(params) = analysis.signature.get("params").and_then(Value::as_array) else { + return Vec::new(); + }; + if params.is_empty() { + return Vec::new(); + } + let carriers = function_carriers(markdown, analysis); + let Some(signature) = carriers.first() else { + return Vec::new(); + }; + let Some(function) = signature.function else { + return Vec::new(); + }; + let prose = markdown.prose_fragments(function); + if has_nearby_prose(markdown, &carriers, &prose, signature) { + return Vec::new(); + } + params + .iter() + .filter_map(|param| node_span(param)) + .map(|span| { + Diagnostic::new("MQD-PARAM-001", span) + .with_related(signature.span) + .with_function(&analysis.local_name) + }) + .collect() +} + +fn style_rule(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> Vec { + let carriers = function_carriers(markdown, analysis); + let mut expected: BTreeMap = BTreeMap::new(); + if analysis.signature.get("kind").and_then(Value::as_str) == Some("explicit") { + if let Some(signature) = carriers.first() { + expected.insert(signature.node, CarrierKind::Code); + } + } + for node in semantic_nodes(&analysis.body) { + let Some(span) = node_span(node) else { + continue; + }; + let kind = match node.get("kind").and_then(Value::as_str) { + Some("assign") => CarrierKind::Strong, + Some("return") => CarrierKind::Emph, + _ => continue, + }; + if let Some(carrier) = carriers.iter().find(|carrier| carrier.span == span) { + expected.insert(carrier.node, kind); + } + } + let tree = align_function(markdown, analysis); + if tree.complete { + for control in &tree.controls { + expected.insert(control.opener.node, CarrierKind::Code); + if control.kind == ControlKind::Branch { + if let Some(carrier) = &control.else_carrier { + expected.insert(carrier.node, CarrierKind::Code); + } + } + if let Some(carrier) = &control.end { + expected.insert(carrier.node, CarrierKind::Code); + } + } + } + carriers + .iter() + .filter_map(|carrier| { + let expected_kind = expected.get(&carrier.node)?; + if carrier.kind == *expected_kind { + return None; + } + Some( + Diagnostic::new("MQD-STYLE-001", carrier.span) + .with_function(&analysis.local_name), + ) + }) + .collect() +} + +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 { + return Vec::new(); + }; + let mut carriers: Vec<_> = markdown + .carriers + .iter() + .filter(|carrier| carrier.function == Some(function)) + .collect(); + carriers.sort_by_key(|carrier| carrier.span.start); + carriers +} + +fn has_nearby_prose( + markdown: &MarkdownTree, + carriers: &[&Carrier], + prose: &[ProseFragment], + anchor: &Carrier, +) -> bool { + let Some(index) = carriers.iter().position(|carrier| carrier.node == anchor.node) else { + return false; + }; + let before_start = index + .checked_sub(1) + .map(|previous| carriers[previous].span.end) + .unwrap_or_else(|| { + anchor + .function + .map(|function| markdown.nodes[function].span.end) + .unwrap_or(0) + }); + let after_end = carriers + .get(index + 1) + .map(|next| next.span.start) + .unwrap_or(usize::MAX); + prose.iter().any(|fragment| { + fragment.heading == anchor.heading + && narrative_count(&fragment.text) > 0 + && ((fragment.span.start >= before_start + && fragment.span.end <= anchor.span.start) + || (fragment.span.start >= anchor.span.end + && fragment.span.end <= after_end)) + }) +} diff --git a/tests/cli.rs b/tests/cli.rs new file mode 100644 index 0000000..c97040f --- /dev/null +++ b/tests/cli.rs @@ -0,0 +1,122 @@ +use std::{fs, path::PathBuf, process::Command}; + +use serde_json::Value; + +fn lint() -> Command { + Command::new(env!("CARGO_BIN_EXE_marqdo-lint")) +} + +fn fixtures() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures") +} + +#[test] +fn rule_commands_do_not_require_the_core() { + let output = lint() + .env("MARQDO_BIN", "no-such-core") + .args(["rules", "--format", "json"]) + .output() + .unwrap(); + assert!(output.status.success()); + let rules: Vec = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(rules.len(), 18); + + let output = lint() + .env("MARQDO_BIN", "no-such-core") + .args(["explain", "MQD-BRANCH-001", "--format", "json"]) + .output() + .unwrap(); + assert!(output.status.success()); + let rule: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(rule["fix_safety"], "manual"); + assert!(rule["evidence"].is_string()); +} + +#[test] +fn reports_and_exit_codes_distinguish_style_from_unavailable_analysis() { + if std::env::var_os("MARQDO_BIN").is_none() { + return; + } + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("index.mq.md"); + fs::write(&source, "## @exec small\n\n*return 1*\n").unwrap(); + let report = |args: &[&str]| { + let output = lint() + .current_dir(temp.path()) + .args(["index.mq.md", "--format", "json"]) + .args(args) + .output() + .unwrap(); + assert!(output.stderr.is_empty(), "{:?}", output); + (output.status.code().unwrap(), serde_json::from_slice::(&output.stdout).unwrap()) + }; + let (code, result) = report(&[]); + assert_eq!(code, 1, "{result}"); + assert_eq!(result["analysis_status"], "complete"); + assert_eq!(result["diagnostics"][0]["id"], "MQD-DOC-001"); + assert!(result["diagnostics"].as_array().unwrap().iter().any(|diagnostic| { + diagnostic["id"] == "MQD-DOC-003" && diagnostic["severity"] == "info" + })); + assert_eq!(report(&["--fail-on", "error"]).0, 0); + + fs::write(temp.path().join("marqdo-lint.toml"), r#" +[[suppress]] +path = "index.mq.md" +rule = "MQD-DOC-001" +reason = "Fixture for a deliberately short helper" +"#).unwrap(); + assert_eq!(report(&[]).0, 0); + + fs::copy(fixtures().join("golden/invalid-control.mq.md"), source).unwrap(); + let (code, result) = report(&["--fail-on", "never"]); + assert_eq!(code, 2, "{result}"); + assert_eq!(result["analysis_status"], "analysis_incomplete"); + assert!(result["metrics"]["narrative_ratio"].is_null()); + assert!(result["core_output"].as_str().unwrap().contains("sem.unclosed_control")); +} + +#[test] +fn multi_module_run_reports_each_source_once() { + if std::env::var_os("MARQDO_BIN").is_none() { + return; + } + let output = lint() + .current_dir(fixtures().join("multi")) + .args(["index.mq.md", "geometry.mq.md", ".", "--format", "json", "--fail-on", "never"]) + .output() + .unwrap(); + assert!(output.status.success(), "{:?}", output); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["summary"]["files"], 2); + assert_eq!(report["reports"][0]["source"]["path"], "geometry.mq.md"); + assert_eq!(report["reports"][1]["source"]["path"], "index.mq.md"); +} + +#[cfg(unix)] +#[test] +fn t30_frozen_core_installs_and_dispatches_lint() { + let Some(core) = std::env::var_os("MARQDO_BIN") else { + return; + }; + let temp = tempfile::tempdir().unwrap(); + let bundle = temp.path().join("bundle"); + fs::create_dir_all(bundle.join("bin")).unwrap(); + fs::copy(env!("CARGO_BIN_EXE_marqdo-lint"), bundle.join("bin/marqdo-lint")).unwrap(); + let manifest = bundle.join("tool.json"); + fs::write(&manifest, include_bytes!("../tool.json")).unwrap(); + let marqdo = || { + let mut command = Command::new(&core); + command.env("MARQDO_TOOL_HOME", temp.path().join("registry")) + .env_remove("MARQDO_BIN"); + command + }; + let install = marqdo().args(["tool", "install"]).arg(manifest).output().unwrap(); + assert!(install.status.success(), "{:?}", install); + let output = marqdo() + .current_dir(fixtures().join("golden")) + .args(["lint", "branches.mq.md", "--format", "json", "--fail-on", "never"]) + .output().unwrap(); + assert!(output.status.success(), "{:?}", output); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["analysis_status"], "complete"); +} diff --git a/tests/fixtures/rejecting-core.sh b/tests/fixtures/rejecting-core.sh new file mode 100755 index 0000000..2f0d98a --- /dev/null +++ b/tests/fixtures/rejecting-core.sh @@ -0,0 +1,6 @@ +#!/bin/sh +case "$1" in + --version) echo 'marqdo 3.0.0-rc.1'; exit 0 ;; + inspect) exit 2 ;; + check) echo 'invalid document'; exit 1 ;; +esac diff --git a/tests/input_pipeline.rs b/tests/input_pipeline.rs index ef50756..f37b2bb 100644 --- a/tests/input_pipeline.rs +++ b/tests/input_pipeline.rs @@ -62,20 +62,10 @@ fn failed_check_is_analysis_incomplete_not_clean() { assert!(project.core_output.contains("sem.unclosed_control")); } +#[cfg(unix)] #[test] fn inspect_failure_uses_document_only_fallback() { - use std::{fs, os::unix::fs::PermissionsExt}; - - let directory = tempfile::tempdir().unwrap(); - let binary = directory.path().join("marqdo"); - fs::write( - &binary, - "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then echo 'marqdo 3.0.0-rc.1'; exit 0; fi\nif [ \"$1\" = \"inspect\" ]; then exit 2; fi\nif [ \"$1\" = \"check\" ]; then echo 'invalid document'; exit 1; fi\n", - ) - .unwrap(); - let mut permissions = fs::metadata(&binary).unwrap().permissions(); - permissions.set_mode(0o755); - fs::set_permissions(&binary, permissions).unwrap(); + let binary = fixture("../rejecting-core.sh"); let runner = MarqdoRunner::discover(Some(&binary)).unwrap(); let project = ProjectInput::load(fixture("branches.mq.md"), &runner).unwrap(); assert_eq!(project.analysis_status, AnalysisStatus::AnalysisIncomplete); diff --git a/tool.json b/tool.json new file mode 100644 index 0000000..23cb920 --- /dev/null +++ b/tool.json @@ -0,0 +1,12 @@ +{ + "schema": "marqdo.cli-tool", + "schema_version": 1, + "name": "cflmy.marqdo-lint", + "version": "0.1.0", + "command": "lint", + "entrypoint": "bin/marqdo-lint", + "compatibility": { + "marqdo": ">=3.0.0-beta.1,<4.0.0", + "analysis": [2] + } +}