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    /// Byte range in the text supplied to the producing API. Public document
81    /// linting includes any leading BOM; raw `Rule::check` ranges address the
82    /// rule's `LintContext::content`.
83    pub range: Range<usize>,
84    pub replacement: String,
85    /// Edits applied atomically with the primary `range`/`replacement` pair.
86    /// Empty for the common single-edit case. See struct docs for semantics.
87    #[serde(default, skip_serializing_if = "Vec::is_empty")]
88    pub additional_edits: Vec<Fix>,
89}
90
91impl Fix {
92    /// Construct a single-edit fix. Use this for the overwhelming common case
93    /// where a fix is one in-place replacement.
94    pub fn new(range: Range<usize>, replacement: String) -> Self {
95        Self {
96            range,
97            replacement,
98            additional_edits: Vec::new(),
99        }
100    }
101
102    /// Construct a multi-edit fix bundle. The primary edit is applied first,
103    /// followed by every entry in `additional_edits` as part of the same
104    /// atomic operation.
105    pub fn with_additional_edits(range: Range<usize>, replacement: String, additional_edits: Vec<Fix>) -> Self {
106        Self {
107            range,
108            replacement,
109            additional_edits,
110        }
111    }
112}
113
114#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, Serialize, schemars::JsonSchema)]
115#[serde(rename_all = "lowercase")]
116pub enum Severity {
117    Error,
118    Warning,
119    Info,
120}
121
122impl<'de> serde::Deserialize<'de> for Severity {
123    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
124    where
125        D: serde::Deserializer<'de>,
126    {
127        let s = String::deserialize(deserializer)?;
128        match s.to_lowercase().as_str() {
129            "error" => Ok(Severity::Error),
130            "warning" => Ok(Severity::Warning),
131            "info" => Ok(Severity::Info),
132            _ => Err(serde::de::Error::custom(format!(
133                "Invalid severity: '{s}'. Valid values: error, warning, info"
134            ))),
135        }
136    }
137}
138
139/// Type of rule for selective processing
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum RuleCategory {
142    Heading,
143    List,
144    CodeBlock,
145    Link,
146    Image,
147    Html,
148    Emphasis,
149    Whitespace,
150    Blockquote,
151    Table,
152    FrontMatter,
153    Other,
154}
155
156/// Capability of a rule to fix issues
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum FixCapability {
159    /// Rule can automatically fix all violations it detects
160    FullyFixable,
161    /// Rule can fix some violations based on context
162    ConditionallyFixable,
163    /// Rule cannot fix violations (by design)
164    Unfixable,
165}
166
167/// Declares what cross-file data a rule needs
168///
169/// Most rules only need single-file context and should use `None` (the default).
170/// Rules that need to validate references across files (like MD051) should use `Workspace`.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
172pub enum CrossFileScope {
173    /// Single-file only - no cross-file analysis needed (default for 99% of rules)
174    #[default]
175    None,
176    /// Needs workspace-wide index for cross-file validation
177    Workspace,
178}
179
180/// A warning an inline disable comment kept out of a document's results.
181#[derive(Debug, Clone, PartialEq, Eq)]
182pub struct SuppressedWarning {
183    /// Canonical id of the rule that raised the warning, e.g. `MD013`
184    pub rule_name: String,
185    /// 1-indexed line of the warning's range the rule was found disabled on
186    pub line: usize,
187    /// The kind of directive that disabled the rule there
188    pub layer: crate::inline_config::DisableLayer,
189}
190
191/// What a run's inline disable comments actually suppressed.
192///
193/// Assembled once per document, after every single-file rule has run, so a rule
194/// reading it sees the complete picture.
195#[derive(Debug, Clone, Default)]
196pub struct SuppressionReport {
197    /// Every warning an inline disable comment removed, in the order raised
198    pub suppressed: Vec<SuppressedWarning>,
199    /// Canonical ids of the rules whose findings this report accounts for.
200    ///
201    /// A rule outside this set produced nothing the report can see, so nothing
202    /// can be concluded about a comment naming it.
203    pub judged_rules: std::collections::HashSet<String>,
204}
205
206pub trait Rule: DynClone + Send + Sync {
207    fn name(&self) -> &'static str;
208    fn description(&self) -> &'static str;
209    fn check(&self, ctx: &LintContext) -> LintResult;
210    fn fix(&self, ctx: &LintContext) -> Result<String, LintError>;
211
212    /// Return the native fix when computing findings already produces it.
213    /// The result belongs only to this configured instance and exact context;
214    /// callers discard it with the findings after any source rewrite.
215    #[doc(hidden)]
216    fn check_with_prepared_fix(&self, ctx: &LintContext) -> Result<(Vec<LintWarning>, Option<String>), LintError> {
217        self.check(ctx).map(|warnings| (warnings, None))
218    }
219
220    /// Apply this rule's native fixer using its already-computed findings.
221    /// Callers must supply raw diagnostics from this configured instance and
222    /// this exact immutable context. No findings survive a source rewrite.
223    /// Custom rules keep their normal fixer unless they explicitly opt in.
224    #[doc(hidden)]
225    fn fix_with_diagnostics(&self, ctx: &LintContext, _warnings: &[LintWarning]) -> Result<String, LintError> {
226        self.fix(ctx)
227    }
228
229    /// Whether CLI fixing is exactly the application of this rule's diagnostic
230    /// edits, filtered by inline disables. The engine can then consume the
231    /// already-computed edits without checking the same source a second time.
232    ///
233    /// Opt in only when `fix()` performs no additional transformations. The
234    /// default preserves custom fix implementations and third-party rules.
235    /// When opting in, `should_skip(ctx)` must imply that applying the raw
236    /// check diagnostics would leave the source unchanged as well.
237    #[doc(hidden)]
238    fn fixes_from_diagnostics(&self) -> bool {
239        false
240    }
241
242    /// Built-in-only certificate for proving that a source revision needs no fix.
243    /// External rules retain their existing check and fix behavior by default.
244    #[doc(hidden)]
245    fn native_format_policy(&self) -> Option<crate::format_proof::NativeFormatPolicy> {
246        None
247    }
248
249    /// Check if this rule should quickly skip processing based on content.
250    fn should_skip(&self, _ctx: &LintContext) -> bool {
251        false
252    }
253
254    /// Get the category of this rule for selective processing
255    fn category(&self) -> RuleCategory {
256        RuleCategory::Other // Default implementation returns Other
257    }
258
259    /// Whether the content-category prefilter may skip this rule.
260    ///
261    /// The prefilter reads the document's shape alone: a `Link` rule is skipped
262    /// for a document holding no links. A rule whose configuration widens what
263    /// it reads answers `false` for that configuration, so that `should_skip`
264    /// and `check` decide instead. MD051 and MD057 read frontmatter values on
265    /// request, and a document can carry those with no link syntax at all.
266    fn skippable_by_category(&self) -> bool {
267        true
268    }
269
270    /// Return this concrete rule instance for type-based queries.
271    fn as_any(&self) -> &dyn std::any::Any;
272
273    // DocumentStructure has been merged into LintContext - this method is no longer used
274    // fn as_maybe_document_structure(&self) -> Option<&dyn MaybeDocumentStructure> {
275    //     None
276    // }
277
278    /// Returns the rule name and default config table if the rule has config.
279    /// If a rule implements this, it MUST be defined on the `impl Rule for ...` block,
280    /// not just the inherent impl.
281    ///
282    /// This is user-facing: it backs `rumdl config`, `rumdl config --defaults` and
283    /// `rumdl explain`, so every value here must be a real default the user could write
284    /// back into a config file. A key whose default cannot be written down (an unset
285    /// `Option`) is therefore absent. Config *validation* reads [`Rule::config_schema`]
286    /// instead, which keeps such keys.
287    fn default_config_section(&self) -> Option<(String, toml::Value)> {
288        None
289    }
290
291    /// Returns the rule name and every config key the rule accepts, for validation.
292    ///
293    /// A key with no representable default (an unset `Option`, or a deserializer that
294    /// accepts several TOML types) carries a sentinel value: the key name is recognized
295    /// while its type check is skipped. Sentinels contain a NUL byte and must never
296    /// reach user-facing output, which is why this is separate from
297    /// [`Rule::default_config_section`].
298    ///
299    /// Defaults to the user-facing table, which is correct for a rule whose every key
300    /// has a representable default.
301    fn config_schema(&self) -> Option<(String, toml::Value)> {
302        self.default_config_section()
303    }
304
305    /// Returns config key aliases for this rule
306    /// This allows rules to accept alternative config key names for backwards compatibility
307    fn config_aliases(&self) -> Option<std::collections::HashMap<String, String>> {
308        None
309    }
310
311    /// Returns the list of config keys whose deserializer accepts more than one TOML
312    /// type (e.g. either a scalar or a list). The schema is built from a serialized
313    /// default that can only encode one variant, so the validator would reject the
314    /// alternative form. The registry replaces the schema entry for each listed key
315    /// with a polymorphic sentinel so type checking is skipped while the key name
316    /// is still validated. The registry rewrites [`Rule::config_schema`], so
317    /// `default_config_section()` keeps returning the clean user-facing default.
318    fn polymorphic_config_keys(&self) -> &'static [&'static str] {
319        &[]
320    }
321
322    /// Declares the fix capability of this rule
323    fn fix_capability(&self) -> FixCapability {
324        FixCapability::FullyFixable // Safe default for backward compatibility
325    }
326
327    /// Declares cross-file analysis requirements for this rule
328    ///
329    /// Returns `CrossFileScope::None` by default, meaning the rule only needs
330    /// single-file context. Rules that need workspace-wide data should override
331    /// this to return `CrossFileScope::Workspace`.
332    fn cross_file_scope(&self) -> CrossFileScope {
333        CrossFileScope::None
334    }
335
336    /// Contribute data to the workspace index during linting
337    ///
338    /// Called during the single-file linting phase for rules that return
339    /// `CrossFileScope::Workspace`. Rules should extract headings, links,
340    /// and other data needed for cross-file validation.
341    ///
342    /// This is called as a side effect of linting, so LintContext is already
343    /// created - no duplicate parsing required.
344    fn contribute_to_index(&self, _ctx: &LintContext, _file_index: &mut crate::workspace_index::FileIndex) {
345        // Default: no contribution
346    }
347
348    /// Perform cross-file validation after all files have been linted
349    ///
350    /// Called once per file after the entire workspace has been indexed.
351    /// Rules receive the file_index (from contribute_to_index) and the full
352    /// workspace_index for cross-file lookups.
353    ///
354    /// Note: This receives the FileIndex instead of LintContext to avoid re-parsing
355    /// each file. The FileIndex was already populated during contribute_to_index.
356    ///
357    /// Rules can use workspace_index methods for cross-file validation:
358    /// - `get_file(path)` - to look up headings in target files (for MD051)
359    /// - `files()` - to iterate all indexed files
360    ///
361    /// Returns additional warnings for cross-file issues. These are appended
362    /// to the single-file warnings.
363    fn cross_file_check(
364        &self,
365        _file_path: &std::path::Path,
366        _file_index: &crate::workspace_index::FileIndex,
367        _workspace_index: &crate::workspace_index::WorkspaceIndex,
368    ) -> LintResult {
369        Ok(Vec::new()) // Default: no cross-file warnings
370    }
371
372    /// Whether this rule reports on the inline comments that suppressed warnings
373    ///
374    /// Recording every suppression costs work on each file, so the linting driver
375    /// does it only when a rule asks for it. A rule answering `true` receives the
376    /// result through `check_suppressions`.
377    fn observes_suppressions(&self) -> bool {
378        false
379    }
380
381    /// Report on a document's inline disable comments
382    ///
383    /// Called once per document after every single-file rule has run, for rules
384    /// that return `true` from `observes_suppressions`. The report says which
385    /// warnings the comments removed and which rules the run can account for.
386    ///
387    /// Returns warnings that join the single-file warnings.
388    fn check_suppressions(&self, _ctx: &LintContext, _report: &SuppressionReport) -> LintResult {
389        Ok(Vec::new()) // Default: nothing to report
390    }
391
392    /// Factory: create a rule from config (if present), or use defaults.
393    fn from_config(_config: &crate::config::Config) -> Box<dyn Rule>
394    where
395        Self: Sized,
396    {
397        panic!(
398            "from_config not implemented for rule: {}",
399            std::any::type_name::<Self>()
400        );
401    }
402}
403
404// Implement the cloning logic for the Rule trait object
405dyn_clone::clone_trait_object!(Rule);
406
407/// Extension trait to add downcasting capabilities to Rule
408pub trait RuleExt {
409    fn downcast_ref<T: 'static>(&self) -> Option<&T>;
410}
411
412impl<R: Rule + 'static> RuleExt for Box<R> {
413    fn downcast_ref<T: 'static>(&self) -> Option<&T> {
414        if std::any::TypeId::of::<R>() == std::any::TypeId::of::<T>() {
415            unsafe { Some(&*std::ptr::from_ref(self.as_ref()).cast::<T>()) }
416        } else {
417            None
418        }
419    }
420}
421
422// Inline config parsing functions are in inline_config.rs.
423// Use InlineConfig::from_content() for the full inline configuration system,
424// or inline_config::parse_disable_comment/parse_enable_comment for low-level parsing.
425
426#[cfg(test)]
427mod tests {
428    use super::*;
429
430    #[test]
431    fn test_severity_serialization() {
432        let warning = LintWarning {
433            message: "Test warning".to_string(),
434            line: 1,
435            column: 1,
436            end_line: 1,
437            end_column: 10,
438            severity: Severity::Warning,
439            fix: None,
440            rule_name: Some("MD001".to_string()),
441        };
442
443        let serialized = serde_json::to_string(&warning).unwrap();
444        assert!(serialized.contains("\"severity\":\"warning\""));
445
446        let error = LintWarning {
447            severity: Severity::Error,
448            ..warning
449        };
450
451        let serialized = serde_json::to_string(&error).unwrap();
452        assert!(serialized.contains("\"severity\":\"error\""));
453    }
454
455    #[test]
456    fn test_fix_serialization() {
457        let fix = Fix::new(0..10, "fixed text".to_string());
458
459        let warning = LintWarning {
460            message: "Test warning".to_string(),
461            line: 1,
462            column: 1,
463            end_line: 1,
464            end_column: 10,
465            severity: Severity::Warning,
466            fix: Some(fix),
467            rule_name: Some("MD001".to_string()),
468        };
469
470        let serialized = serde_json::to_string(&warning).unwrap();
471        assert!(serialized.contains("\"fix\""));
472        assert!(serialized.contains("\"replacement\":\"fixed text\""));
473    }
474
475    #[test]
476    fn test_rule_category_equality() {
477        assert_eq!(RuleCategory::Heading, RuleCategory::Heading);
478        assert_ne!(RuleCategory::Heading, RuleCategory::List);
479
480        // Test all categories are distinct
481        let categories = [
482            RuleCategory::Heading,
483            RuleCategory::List,
484            RuleCategory::CodeBlock,
485            RuleCategory::Link,
486            RuleCategory::Image,
487            RuleCategory::Html,
488            RuleCategory::Emphasis,
489            RuleCategory::Whitespace,
490            RuleCategory::Blockquote,
491            RuleCategory::Table,
492            RuleCategory::FrontMatter,
493            RuleCategory::Other,
494        ];
495
496        for (i, cat1) in categories.iter().enumerate() {
497            for (j, cat2) in categories.iter().enumerate() {
498                if i == j {
499                    assert_eq!(cat1, cat2);
500                } else {
501                    assert_ne!(cat1, cat2);
502                }
503            }
504        }
505    }
506
507    #[test]
508    fn test_lint_error_conversions() {
509        use std::io;
510
511        // Test From<io::Error>
512        let io_error = io::Error::new(io::ErrorKind::NotFound, "file not found");
513        let lint_error: LintError = io_error.into();
514        match lint_error {
515            LintError::IoError(_) => {}
516            _ => panic!("Expected IoError variant"),
517        }
518
519        // Test Display trait
520        let invalid_input = LintError::InvalidInput("bad input".to_string());
521        assert_eq!(invalid_input.to_string(), "Invalid input: bad input");
522
523        let fix_failed = LintError::FixFailed("couldn't fix".to_string());
524        assert_eq!(fix_failed.to_string(), "Fix failed: couldn't fix");
525
526        let parsing_error = LintError::ParsingError("parse error".to_string());
527        assert_eq!(parsing_error.to_string(), "Parsing error: parse error");
528    }
529}