feat: ship configurable lint CLI and Tool v1 bundle

This commit is contained in:
cflmy committed 2026-11-23 18:55:58 +08:00
1 parent f26f6099f2
commit 94c36270fa
16 files changed
+1403 -19

No files matched your search

+252
View File
@@ -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<Command>,
#[arg(value_name = "PATH", default_value = ".")]
paths: Vec<PathBuf>,
#[arg(long, value_enum, default_value = "human", global = true)]
format: OutputFormat,
#[arg(long, value_enum)]
profile: Option<ProfileArg>,
#[arg(long, value_name = "FILE")]
config: Option<PathBuf>,
#[arg(long, value_enum, default_value = "warning")]
fail_on: FailOnArg,
#[arg(long, value_enum, value_name = "MODE")]
fix: Option<FixMode>,
}
#[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<ProfileArg> 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<FailOnArg> 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<i32> {
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<i32> {
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<i32> {
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<Vec<PathBuf>> {
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::<Result<Vec<_>>>()?;
// 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())
}
+289
View File
@@ -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<Severity> {
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<String>,
pub span: Option<Span>,
}
#[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<String, RuleLevel>,
#[serde(rename = "suppress", alias = "suppressions")]
pub suppressions: Vec<Suppression>,
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<String, RuleLevel>,
pub suppressions: Vec<Suppression>,
pub fix: FixConfig,
}
impl EffectiveConfig {
pub fn apply(&self, path: &str, diagnostics: &mut Vec<Diagnostic>) {
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<Self> {
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<Self> {
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<Profile>) -> Result<EffectiveConfig> {
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());
}
}
+4
View File
@@ -1,3 +1,7 @@
mod report;
pub use report::{DocumentReport, FailOn, LintRun, MetricsReport, RunReport, Summary};
use serde::{Deserialize, Serialize};
use crate::{
+235
View File
@@ -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<f64>,
pub measurement_version: u8,
pub functions: Vec<FunctionNarrative>,
}
#[derive(Debug, Serialize)]
pub struct DocumentReport {
pub schema: &'static str,
pub schema_version: u8,
pub source: SourceReport,
pub diagnostics: Vec<Diagnostic>,
pub analysis_status: AnalysisStatus,
pub metrics: MetricsReport,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub notices: Vec<String>,
#[serde(skip_serializing_if = "String::is_empty")]
pub core_output: String,
#[serde(skip)]
locations: Vec<LineColumn>,
}
impl DocumentReport {
pub fn new(
document: &SourceDocument,
mut analysis_status: AnalysisStatus,
path: String,
mut analysis: DocumentAnalysis,
config: &EffectiveConfig,
mut notices: Vec<String>,
core_output: String,
) -> Result<Self> {
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::<Result<Vec<_>>>()?;
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<DocumentReport>,
}
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::<String>();
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<String> {
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",
}
}
+61
View File
@@ -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<Diagnostic>,
pub metrics: Vec<FunctionNarrative>,
pub alignment_issues: Vec<String>,
}
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,
}
}
+3
View File
@@ -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;
+8 -2
View File
@@ -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)
}
}
}
+12 -4
View File
@@ -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<Diagnostic> {
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(&(
+6 -1
View File
@@ -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,
+284
View File
@@ -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<Diagnostic> {
let markdown = &document.markdown;
let mut diagnostics = prose_rule(markdown);
diagnostics.extend(knowledge_rule(markdown));
diagnostics
}
pub fn check_semantic_document(document: &SourceDocument) -> Vec<Diagnostic> {
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<Diagnostic> {
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<Diagnostic> {
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<Diagnostic> {
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<Diagnostic> {
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<Diagnostic> {
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<Diagnostic> {
let carriers = function_carriers(markdown, analysis);
let mut expected: BTreeMap<NodeId, CarrierKind> = 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))
})
}