Skip to main content

rumdl_lib/
rule.rs

1//!
2//! This module defines the Rule trait and related types for implementing linting rules in rumdl.
3
4use dyn_clone::DynClone;
5use serde::{Deserialize, Serialize};
6use std::ops::Range;
7use thiserror::Error;
8
9use crate::lint_context::LintContext;
10
11// Macro to implement box_clone for Rule implementors
12#[macro_export]
13macro_rules! impl_rule_clone {
14    ($ty:ty) => {
15        impl $ty {
16            fn box_clone(&self) -> Box<dyn Rule> {
17                Box::new(self.clone())
18            }
19        }
20    };
21}
22
23#[derive(Debug, Error)]
24pub enum LintError {
25    #[error("Invalid input: {0}")]
26    InvalidInput(String),
27    #[error("Fix failed: {0}")]
28    FixFailed(String),
29    #[error("IO error: {0}")]
30    IoError(#[from] std::io::Error),
31    #[error("Parsing error: {0}")]
32    ParsingError(String),
33}
34
35pub type LintResult = Result<Vec<LintWarning>, LintError>;
36
37#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
38pub struct LintWarning {
39    pub message: String,
40    pub line: usize, // 1-indexed start line
41    /// 1-indexed start column, measured in **characters** (not bytes).
42    /// When deriving a column from a byte offset (regex match, `str::find`,
43    /// parser byte offset), convert with `range_utils::byte_to_char_count` or a
44    /// character-based range helper. A raw byte offset mis-positions the
45    /// highlight on lines containing multi-byte UTF-8.
46    pub column: usize,
47    pub end_line: usize, // 1-indexed end line
48    /// 1-indexed end column, measured in **characters** (see `column`). Use
49    /// `str::chars().count()`, not `str::len()`, when computing a span width.
50    pub end_column: usize,
51    pub severity: Severity,
52    pub fix: Option<Fix>,
53    pub rule_name: Option<String>,
54}
55
56/// One atomic fix attached to a `LintWarning`.
57///
58/// `range`/`replacement` describe the primary edit. `additional_edits`
59/// carries any *paired* edits that must apply together with the primary one
60/// for the result to be a valid document — for example, MD054's conversion
61/// of an inline link to a reference style produces the in-place link rewrite
62/// **and** a reference-definition append at end-of-file; applying only one
63/// half would leave a dangling reference.
64///
65/// All fix consumers (the LSP code-action layer, CLI counters, the
66/// `apply_warning_fixes` helper) treat the primary edit and the
67/// `additional_edits` as a single unit. The field is empty by default so
68/// rules that only need a single-location fix can keep using
69/// `Fix::new(range, replacement)`; only rules that need multi-location
70/// atomicity populate it via `Fix::with_additional_edits(...)`.
71///
72/// `additional_edits` is intentionally a flat `Vec<Fix>` — nesting beyond
73/// one level isn't needed today and would complicate the apply contract.
74/// Apply order is "primary first, then additional in their declared order"
75/// when offsets are non-overlapping; consumers that batch multiple fixes
76/// across warnings still sort by `range.start` descending so earlier offsets
77/// remain valid as later edits mutate the buffer.
78#[derive(Debug, PartialEq, Clone, Default, Serialize, Deserialize)]
79pub struct Fix {
80    pub range: Range<usize>,
81    pub replacement: String,
82    /// Edits applied atomically with the primary `range`/`replacement` pair.
83    /// Empty for the common single-edit case. See struct docs for semantics.
84    #[serde(default, skip_serializing_if = "Vec::is_empty")]
85    pub additional_edits: Vec<Fix>,
86}
87
88impl Fix {
89    /// Construct a single-edit fix. Use this for the overwhelming common case
90    /// where a fix is one in-place replacement.
91    pub fn new(range: Range<usize>, replacement: String) -> Self {
92        Self {
93            range,
94            replacement,
95            additional_edits: Vec::new(),
96        }
97    }
98
99    /// Construct a multi-edit fix bundle. The primary edit is applied first,
100    /// followed by every entry in `additional_edits` as part of the same
101    /// atomic operation.
102    pub fn with_additional_edits(range: Range<usize>, replacement: String, additional_edits: Vec<Fix>) -> Self {
103        Self {
104            range,
105            replacement,
106            additional_edits,
107        }
108    }
109}
110
111#[derive(Debug, PartialEq, Clone, Copy, Serialize, schemars::JsonSchema)]
112#[serde(rename_all = "lowercase")]
113pub enum Severity {
114    Error,
115    Warning,
116    Info,
117}
118
119impl<'de> serde::Deserialize<'de> for Severity {
120    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
121    where
122        D: serde::Deserializer<'de>,
123    {
124        let s = String::deserialize(deserializer)?;
125        match s.to_lowercase().as_str() {
126            "error" => Ok(Severity::Error),
127            "warning" => Ok(Severity::Warning),
128            "info" => Ok(Severity::Info),
129            _ => Err(serde::de::Error::custom(format!(
130                "Invalid severity: '{s}'. Valid values: error, warning, info"
131            ))),
132        }
133    }
134}
135
136/// Type of rule for selective processing
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub enum RuleCategory {
139    Heading,
140    List,
141    CodeBlock,
142    Link,
143    Image,
144    Html,
145    Emphasis,
146    Whitespace,
147    Blockquote,
148    Table,
149    FrontMatter,
150    Other,
151}
152
153/// Capability of a rule to fix issues
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub enum FixCapability {
156    /// Rule can automatically fix all violations it detects
157    FullyFixable,
158    /// Rule can fix some violations based on context
159    ConditionallyFixable,
160    /// Rule cannot fix violations (by design)
161    Unfixable,
162}
163
164/// Declares what cross-file data a rule needs
165///
166/// Most rules only need single-file context and should use `None` (the default).
167/// Rules that need to validate references across files (like MD051) should use `Workspace`.
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
169pub enum CrossFileScope {
170    /// Single-file only - no cross-file analysis needed (default for 99% of rules)
171    #[default]
172    None,
173    /// Needs workspace-wide index for cross-file validation
174    Workspace,
175}
176
177pub trait Rule: DynClone + Send + Sync {
178    fn name(&self) -> &'static str;
179    fn description(&self) -> &'static str;
180    fn check(&self, ctx: &LintContext) -> LintResult;
181    fn fix(&self, ctx: &LintContext) -> Result<String, LintError>;
182
183    /// Check if this rule should quickly skip processing based on content
184    fn should_skip(&self, _ctx: &LintContext) -> bool {
185        false
186    }
187
188    /// Get the category of this rule for selective processing
189    fn category(&self) -> RuleCategory {
190        RuleCategory::Other // Default implementation returns Other
191    }
192
193    fn as_any(&self) -> &dyn std::any::Any;
194
195    // DocumentStructure has been merged into LintContext - this method is no longer used
196    // fn as_maybe_document_structure(&self) -> Option<&dyn MaybeDocumentStructure> {
197    //     None
198    // }
199
200    /// Returns the rule name and default config table if the rule has config.
201    /// If a rule implements this, it MUST be defined on the `impl Rule for ...` block,
202    /// not just the inherent impl.
203    fn default_config_section(&self) -> Option<(String, toml::Value)> {
204        None
205    }
206
207    /// Returns config key aliases for this rule
208    /// This allows rules to accept alternative config key names for backwards compatibility
209    fn config_aliases(&self) -> Option<std::collections::HashMap<String, String>> {
210        None
211    }
212
213    /// Returns the list of config keys whose deserializer accepts more than one TOML
214    /// type (e.g. either a scalar or a list). The schema is built from a serialized
215    /// default that can only encode one variant, so the validator would reject the
216    /// alternative form. The registry replaces the schema entry for each listed key
217    /// with a polymorphic sentinel so type checking is skipped while the key name
218    /// is still validated. Keep `default_config_section()` returning clean defaults
219    /// — the sentinel is a schema concern and must not leak into user-facing output
220    /// like `rumdl config --defaults`.
221    fn polymorphic_config_keys(&self) -> &'static [&'static str] {
222        &[]
223    }
224
225    /// Declares the fix capability of this rule
226    fn fix_capability(&self) -> FixCapability {
227        FixCapability::FullyFixable // Safe default for backward compatibility
228    }
229
230    /// Declares cross-file analysis requirements for this rule
231    ///
232    /// Returns `CrossFileScope::None` by default, meaning the rule only needs
233    /// single-file context. Rules that need workspace-wide data should override
234    /// this to return `CrossFileScope::Workspace`.
235    fn cross_file_scope(&self) -> CrossFileScope {
236        CrossFileScope::None
237    }
238
239    /// Contribute data to the workspace index during linting
240    ///
241    /// Called during the single-file linting phase for rules that return
242    /// `CrossFileScope::Workspace`. Rules should extract headings, links,
243    /// and other data needed for cross-file validation.
244    ///
245    /// This is called as a side effect of linting, so LintContext is already
246    /// created - no duplicate parsing required.
247    fn contribute_to_index(&self, _ctx: &LintContext, _file_index: &mut crate::workspace_index::FileIndex) {
248        // Default: no contribution
249    }
250
251    /// Perform cross-file validation after all files have been linted
252    ///
253    /// Called once per file after the entire workspace has been indexed.
254    /// Rules receive the file_index (from contribute_to_index) and the full
255    /// workspace_index for cross-file lookups.
256    ///
257    /// Note: This receives the FileIndex instead of LintContext to avoid re-parsing
258    /// each file. The FileIndex was already populated during contribute_to_index.
259    ///
260    /// Rules can use workspace_index methods for cross-file validation:
261    /// - `get_file(path)` - to look up headings in target files (for MD051)
262    /// - `files()` - to iterate all indexed files
263    ///
264    /// Returns additional warnings for cross-file issues. These are appended
265    /// to the single-file warnings.
266    fn cross_file_check(
267        &self,
268        _file_path: &std::path::Path,
269        _file_index: &crate::workspace_index::FileIndex,
270        _workspace_index: &crate::workspace_index::WorkspaceIndex,
271    ) -> LintResult {
272        Ok(Vec::new()) // Default: no cross-file warnings
273    }
274
275    /// Factory: create a rule from config (if present), or use defaults.
276    fn from_config(_config: &crate::config::Config) -> Box<dyn Rule>
277    where
278        Self: Sized,
279    {
280        panic!(
281            "from_config not implemented for rule: {}",
282            std::any::type_name::<Self>()
283        );
284    }
285}
286
287// Implement the cloning logic for the Rule trait object
288dyn_clone::clone_trait_object!(Rule);
289
290/// Extension trait to add downcasting capabilities to Rule
291pub trait RuleExt {
292    fn downcast_ref<T: 'static>(&self) -> Option<&T>;
293}
294
295impl<R: Rule + 'static> RuleExt for Box<R> {
296    fn downcast_ref<T: 'static>(&self) -> Option<&T> {
297        if std::any::TypeId::of::<R>() == std::any::TypeId::of::<T>() {
298            unsafe { Some(&*std::ptr::from_ref(self.as_ref()).cast::<T>()) }
299        } else {
300            None
301        }
302    }
303}
304
305// Inline config parsing functions are in inline_config.rs.
306// Use InlineConfig::from_content() for the full inline configuration system,
307// or inline_config::parse_disable_comment/parse_enable_comment for low-level parsing.
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312
313    #[test]
314    fn test_severity_serialization() {
315        let warning = LintWarning {
316            message: "Test warning".to_string(),
317            line: 1,
318            column: 1,
319            end_line: 1,
320            end_column: 10,
321            severity: Severity::Warning,
322            fix: None,
323            rule_name: Some("MD001".to_string()),
324        };
325
326        let serialized = serde_json::to_string(&warning).unwrap();
327        assert!(serialized.contains("\"severity\":\"warning\""));
328
329        let error = LintWarning {
330            severity: Severity::Error,
331            ..warning
332        };
333
334        let serialized = serde_json::to_string(&error).unwrap();
335        assert!(serialized.contains("\"severity\":\"error\""));
336    }
337
338    #[test]
339    fn test_fix_serialization() {
340        let fix = Fix::new(0..10, "fixed text".to_string());
341
342        let warning = LintWarning {
343            message: "Test warning".to_string(),
344            line: 1,
345            column: 1,
346            end_line: 1,
347            end_column: 10,
348            severity: Severity::Warning,
349            fix: Some(fix),
350            rule_name: Some("MD001".to_string()),
351        };
352
353        let serialized = serde_json::to_string(&warning).unwrap();
354        assert!(serialized.contains("\"fix\""));
355        assert!(serialized.contains("\"replacement\":\"fixed text\""));
356    }
357
358    #[test]
359    fn test_rule_category_equality() {
360        assert_eq!(RuleCategory::Heading, RuleCategory::Heading);
361        assert_ne!(RuleCategory::Heading, RuleCategory::List);
362
363        // Test all categories are distinct
364        let categories = [
365            RuleCategory::Heading,
366            RuleCategory::List,
367            RuleCategory::CodeBlock,
368            RuleCategory::Link,
369            RuleCategory::Image,
370            RuleCategory::Html,
371            RuleCategory::Emphasis,
372            RuleCategory::Whitespace,
373            RuleCategory::Blockquote,
374            RuleCategory::Table,
375            RuleCategory::FrontMatter,
376            RuleCategory::Other,
377        ];
378
379        for (i, cat1) in categories.iter().enumerate() {
380            for (j, cat2) in categories.iter().enumerate() {
381                if i == j {
382                    assert_eq!(cat1, cat2);
383                } else {
384                    assert_ne!(cat1, cat2);
385                }
386            }
387        }
388    }
389
390    #[test]
391    fn test_lint_error_conversions() {
392        use std::io;
393
394        // Test From<io::Error>
395        let io_error = io::Error::new(io::ErrorKind::NotFound, "file not found");
396        let lint_error: LintError = io_error.into();
397        match lint_error {
398            LintError::IoError(_) => {}
399            _ => panic!("Expected IoError variant"),
400        }
401
402        // Test Display trait
403        let invalid_input = LintError::InvalidInput("bad input".to_string());
404        assert_eq!(invalid_input.to_string(), "Invalid input: bad input");
405
406        let fix_failed = LintError::FixFailed("couldn't fix".to_string());
407        assert_eq!(fix_failed.to_string(), "Fix failed: couldn't fix");
408
409        let parsing_error = LintError::ParsingError("parse error".to_string());
410        assert_eq!(parsing_error.to_string(), "Parsing error: parse error");
411    }
412}