mdbook_lint_core/
rule.rs

1use crate::{Document, error::Result, violation::Violation};
2use comrak::{Arena, nodes::AstNode};
3
4/// Rule stability levels
5#[derive(Debug, Clone, PartialEq)]
6pub enum RuleStability {
7    /// Rule is stable and recommended for production use
8    Stable,
9    /// Rule is experimental and may change
10    Experimental,
11    /// Rule is deprecated and may be removed in future versions
12    Deprecated,
13    /// Rule number reserved but never implemented
14    Reserved,
15}
16
17/// Rule categories for grouping and filtering
18#[derive(Debug, Clone, PartialEq)]
19pub enum RuleCategory {
20    /// Document structure and heading organization
21    Structure,
22    /// Whitespace, line length, and formatting consistency
23    Formatting,
24    /// Links, images, and content validation
25    Content,
26    /// Link-specific validation
27    Links,
28    /// Accessibility and usability rules
29    Accessibility,
30    /// mdBook-specific functionality and conventions
31    MdBook,
32}
33
34/// Metadata about a rule's status, category, and properties
35#[derive(Debug, Clone)]
36pub struct RuleMetadata {
37    /// Whether the rule is deprecated
38    pub deprecated: bool,
39    /// Reason for deprecation (if applicable)
40    pub deprecated_reason: Option<&'static str>,
41    /// Suggested replacement rule (if applicable)
42    pub replacement: Option<&'static str>,
43    /// Rule category for grouping
44    pub category: RuleCategory,
45    /// Version when rule was introduced
46    pub introduced_in: Option<&'static str>,
47    /// Stability level of the rule
48    pub stability: RuleStability,
49    /// Rules that this rule overrides (for context-specific rules)
50    pub overrides: Option<&'static str>,
51}
52
53impl RuleMetadata {
54    /// Create metadata for a stable, active rule
55    pub fn stable(category: RuleCategory) -> Self {
56        Self {
57            deprecated: false,
58            deprecated_reason: None,
59            replacement: None,
60            category,
61            introduced_in: None,
62            stability: RuleStability::Stable,
63            overrides: None,
64        }
65    }
66
67    /// Create metadata for a deprecated rule
68    pub fn deprecated(
69        category: RuleCategory,
70        reason: &'static str,
71        replacement: Option<&'static str>,
72    ) -> Self {
73        Self {
74            deprecated: true,
75            deprecated_reason: Some(reason),
76            replacement,
77            category,
78            introduced_in: None,
79            stability: RuleStability::Deprecated,
80            overrides: None,
81        }
82    }
83
84    /// Create metadata for an experimental rule
85    pub fn experimental(category: RuleCategory) -> Self {
86        Self {
87            deprecated: false,
88            deprecated_reason: None,
89            replacement: None,
90            category,
91            introduced_in: None,
92            stability: RuleStability::Experimental,
93            overrides: None,
94        }
95    }
96
97    /// Create metadata for a reserved rule number (never implemented)
98    pub fn reserved(reason: &'static str) -> Self {
99        Self {
100            deprecated: false,
101            deprecated_reason: Some(reason),
102            replacement: None,
103            category: RuleCategory::Structure,
104            introduced_in: None,
105            stability: RuleStability::Reserved,
106            overrides: None,
107        }
108    }
109
110    /// Set the version when this rule was introduced
111    pub fn introduced_in(mut self, version: &'static str) -> Self {
112        self.introduced_in = Some(version);
113        self
114    }
115
116    /// Set which rule this rule overrides
117    pub fn overrides(mut self, rule_id: &'static str) -> Self {
118        self.overrides = Some(rule_id);
119        self
120    }
121}
122
123/// Trait that all linting rules must implement
124pub trait Rule: Send + Sync {
125    /// Unique identifier for the rule (e.g., "MD001")
126    fn id(&self) -> &'static str;
127
128    /// Human-readable name for the rule (e.g., "heading-increment")
129    fn name(&self) -> &'static str;
130
131    /// Description of what the rule checks
132    fn description(&self) -> &'static str;
133
134    /// Metadata about this rule's status and properties
135    fn metadata(&self) -> RuleMetadata;
136
137    /// Check a document for violations of this rule with optional pre-parsed AST
138    fn check_with_ast<'a>(
139        &self,
140        document: &Document,
141        ast: Option<&'a AstNode<'a>>,
142    ) -> Result<Vec<Violation>>;
143
144    /// Check a document for violations of this rule (backward compatibility)
145    fn check(&self, document: &Document) -> Result<Vec<Violation>> {
146        self.check_with_ast(document, None)
147    }
148
149    /// Whether this rule can automatically fix violations
150    fn can_fix(&self) -> bool {
151        false
152    }
153
154    /// Attempt to fix a violation (if supported)
155    fn fix(&self, _content: &str, _violation: &Violation) -> Option<String> {
156        None
157    }
158
159    /// Create a violation for this rule
160    fn create_violation(
161        &self,
162        message: String,
163        line: usize,
164        column: usize,
165        severity: crate::violation::Severity,
166    ) -> Violation {
167        Violation {
168            rule_id: self.id().to_string(),
169            rule_name: self.name().to_string(),
170            message,
171            line,
172            column,
173            severity,
174        }
175    }
176}
177
178/// Helper trait for AST-based rules
179///
180/// # When to Use AstRule vs Rule
181///
182/// **Use `AstRule` when your rule needs to:**
183/// - Analyze document structure (headings, lists, links, code blocks)
184/// - Navigate parent-child relationships in the markdown tree
185/// - Access precise position information from comrak's sourcepos
186/// - Understand markdown semantics beyond simple text patterns
187///
188/// **Use `Rule` directly when your rule:**
189/// - Only needs line-by-line text analysis
190/// - Checks simple text patterns (trailing spaces, line length)
191/// - Doesn't need to understand markdown structure
192///
193/// # Implementation Examples
194///
195/// **AstRule Examples:**
196/// - `MD001` (heading-increment): Needs to traverse heading hierarchy
197/// - `MDBOOK002` (link-validation): Needs to find and validate link nodes
198/// - `MD031` (blanks-around-fences): Needs to identify fenced code blocks
199///
200/// **Rule Examples:**
201/// - `MD013` (line-length): Simple line-by-line character counting
202/// - `MD009` (no-trailing-spaces): Pattern matching on line endings
203///
204/// # Basic Implementation Pattern
205///
206/// ```rust
207/// use mdbook_lint_core::rule::{AstRule, RuleMetadata, RuleCategory};
208/// use mdbook_lint_core::{Document, Violation, Result};
209/// use comrak::nodes::{AstNode, NodeValue};
210///
211/// pub struct MyRule;
212///
213/// impl AstRule for MyRule {
214///     fn id(&self) -> &'static str { "MY001" }
215///     fn name(&self) -> &'static str { "my-rule" }
216///     fn description(&self) -> &'static str { "Description of what this rule checks" }
217///
218///     fn metadata(&self) -> RuleMetadata {
219///         RuleMetadata::stable(RuleCategory::Structure)
220///     }
221///
222///     fn check_ast<'a>(&self, document: &Document, ast: &'a AstNode<'a>) -> Result<Vec<Violation>> {
223///         let mut violations = Vec::new();
224///
225///         // Find nodes of interest
226///         for node in ast.descendants() {
227///             if let NodeValue::Heading(heading) = &node.data.borrow().value {
228///                 // Get position information
229///                 if let Some((line, column)) = document.node_position(node) {
230///                     // Check some condition
231///                     if heading.level > 3 {
232///                         violations.push(self.create_violation(
233///                             "Heading too deep".to_string(),
234///                             line,
235///                             column,
236///                             mdbook_lint_core::violation::Severity::Warning,
237///                         ));
238///                     }
239///                 }
240///             }
241///         }
242///
243///         Ok(violations)
244///     }
245/// }
246/// ```
247///
248/// # Key Methods Available
249///
250/// **From Document:**
251/// - `document.node_position(node)` - Get (line, column) for any AST node
252/// - `document.node_text(node)` - Extract text content from a node
253/// - `document.headings(ast)` - Get all heading nodes
254/// - `document.code_blocks(ast)` - Get all code block nodes
255///
256/// **From AstNode:**
257/// - `node.descendants()` - Iterate all child nodes recursively
258/// - `node.children()` - Get direct children only
259/// - `node.parent()` - Get parent node (if any)
260/// - `node.data.borrow().value` - Access the NodeValue enum
261///
262/// **Creating Violations:**
263/// - `self.create_violation(message, line, column, severity)` - Standard violation creation
264pub trait AstRule: Send + Sync {
265    /// Unique identifier for the rule (e.g., "MD001")
266    fn id(&self) -> &'static str;
267
268    /// Human-readable name for the rule (e.g., "heading-increment")
269    fn name(&self) -> &'static str;
270
271    /// Description of what the rule checks
272    fn description(&self) -> &'static str;
273
274    /// Metadata about this rule's status and properties
275    fn metadata(&self) -> RuleMetadata;
276
277    /// Check a document using its AST
278    fn check_ast<'a>(&self, document: &Document, ast: &'a AstNode<'a>) -> Result<Vec<Violation>>;
279
280    /// Whether this rule can automatically fix violations
281    fn can_fix(&self) -> bool {
282        false
283    }
284
285    /// Attempt to fix a violation (if supported)
286    fn fix(&self, _content: &str, _violation: &Violation) -> Option<String> {
287        None
288    }
289
290    /// Create a violation for this rule
291    fn create_violation(
292        &self,
293        message: String,
294        line: usize,
295        column: usize,
296        severity: crate::violation::Severity,
297    ) -> Violation {
298        Violation {
299            rule_id: self.id().to_string(),
300            rule_name: self.name().to_string(),
301            message,
302            line,
303            column,
304            severity,
305        }
306    }
307}
308
309// Blanket implementation so AstRule types automatically implement Rule
310impl<T: AstRule> Rule for T {
311    fn id(&self) -> &'static str {
312        T::id(self)
313    }
314
315    fn name(&self) -> &'static str {
316        T::name(self)
317    }
318
319    fn description(&self) -> &'static str {
320        T::description(self)
321    }
322
323    fn metadata(&self) -> RuleMetadata {
324        T::metadata(self)
325    }
326
327    fn check_with_ast<'a>(
328        &self,
329        document: &Document,
330        ast: Option<&'a AstNode<'a>>,
331    ) -> Result<Vec<Violation>> {
332        if let Some(ast) = ast {
333            self.check_ast(document, ast)
334        } else {
335            let arena = Arena::new();
336            let ast = document.parse_ast(&arena);
337            self.check_ast(document, ast)
338        }
339    }
340
341    fn check(&self, document: &Document) -> Result<Vec<Violation>> {
342        self.check_with_ast(document, None)
343    }
344
345    fn can_fix(&self) -> bool {
346        T::can_fix(self)
347    }
348
349    fn fix(&self, content: &str, violation: &Violation) -> Option<String> {
350        T::fix(self, content, violation)
351    }
352
353    fn create_violation(
354        &self,
355        message: String,
356        line: usize,
357        column: usize,
358        severity: crate::violation::Severity,
359    ) -> Violation {
360        T::create_violation(self, message, line, column, severity)
361    }
362}