Skip to main content

mdwright_lint/
rule_set.rs

1//! A set of rules to run against a document.
2//!
3//! `RuleSet` is a registry, not a bit-mask: it owns `Box<dyn
4//! LintRule>` values keyed by name. The CLI builds one from
5//! `RuleSet::stdlib_defaults()` and applies `+rule` / `-rule`
6//! adjustments; library callers add their own rules in any
7//! combination they like (see the crate-level extensibility
8//! example).
9//!
10//! Names must be unique inside a set. `add` returns an error rather
11//! than silently dropping or overriding — duplicate registration is
12//! almost always a bug.
13
14use std::fmt;
15
16use mdwright_document::Document;
17
18use crate::LintOptions;
19use crate::diagnostic::Diagnostic;
20use crate::rule::LintRule;
21use crate::stdlib;
22use crate::suppression::SuppressionMap;
23
24/// An ordered, name-unique collection of [`LintRule`]s.
25#[derive(Default)]
26pub struct RuleSet {
27    rules: Vec<Box<dyn LintRule>>,
28}
29
30impl RuleSet {
31    /// An empty set; add rules with [`Self::add`].
32    #[must_use]
33    pub fn new() -> Self {
34        Self { rules: Vec::new() }
35    }
36
37    /// The stdlib's curated default-on rules. Equivalent to
38    /// [`crate::stdlib::defaults`].
39    #[must_use]
40    pub fn stdlib_defaults() -> Self {
41        stdlib::defaults()
42    }
43
44    /// Every stdlib rule, including the default-off ones.
45    /// Equivalent to [`crate::stdlib::all`].
46    #[must_use]
47    pub fn stdlib_all() -> Self {
48        stdlib::all()
49    }
50
51    /// Insert a rule. Names must be unique within the set.
52    ///
53    /// # Errors
54    ///
55    /// Returns [`DuplicateRuleName`] if a rule with the same
56    /// `name()` is already present.
57    pub fn add(&mut self, rule: Box<dyn LintRule>) -> Result<&mut Self, DuplicateRuleName> {
58        if self.contains(rule.name()) {
59            return Err(DuplicateRuleName {
60                name: rule.name().to_owned(),
61            });
62        }
63        self.rules.push(rule);
64        Ok(self)
65    }
66
67    /// Remove the rule with the given `name`. Returns `true` if a
68    /// rule was removed, `false` if no rule had that name.
69    pub fn remove(&mut self, name: &str) -> bool {
70        let before = self.rules.len();
71        self.rules.retain(|r| r.name() != name);
72        self.rules.len() != before
73    }
74
75    #[must_use]
76    pub fn contains(&self, name: &str) -> bool {
77        self.rules.iter().any(|r| r.name() == name)
78    }
79
80    pub fn iter(&self) -> impl Iterator<Item = &dyn LintRule> {
81        self.rules.iter().map(|b| &**b)
82    }
83
84    /// Look up a rule by its `name`.
85    #[must_use]
86    pub fn by_name(&self, name: &str) -> Option<&dyn LintRule> {
87        self.rules.iter().find(|r| r.name() == name).map(|b| &**b)
88    }
89
90    /// Iterate over the names of every rule in the set.
91    pub fn names(&self) -> impl Iterator<Item = &str> {
92        self.rules.iter().map(|r| r.name())
93    }
94
95    /// Run every rule in the set over `doc`.
96    #[must_use]
97    pub fn check(&self, doc: &Document) -> Vec<Diagnostic> {
98        self.check_with(doc, LintOptions::default())
99    }
100
101    /// Run every rule in the set over `doc` under `opts`.
102    #[must_use]
103    pub fn check_with(&self, doc: &Document, opts: LintOptions) -> Vec<Diagnostic> {
104        let mut out = Vec::new();
105        for rule in self.iter() {
106            let before = out.len();
107            rule.check(doc, &mut out);
108            let name_owned = rule.name().to_owned();
109            let advisory = rule.is_advisory();
110            for d in out.get_mut(before..).into_iter().flatten() {
111                d.rule = std::borrow::Cow::Owned(name_owned.clone());
112                d.advisory = advisory;
113            }
114        }
115
116        if opts.respect_suppressions {
117            let user_names: Vec<String> = self.iter().map(|r| r.name().to_owned()).collect();
118            let mut known: Vec<&str> = stdlib::names().collect();
119            for n in &user_names {
120                let s: &str = n.as_str();
121                if !known.contains(&s) {
122                    known.push(s);
123                }
124            }
125            let (map, unknown) = SuppressionMap::build(doc.source(), doc.line_index(), doc.suppressions(), &known);
126            out.retain(|d| !map.suppresses(&d.rule, &d.span));
127            out.extend(unknown);
128        }
129
130        out.sort_by(|a, b| {
131            a.line
132                .cmp(&b.line)
133                .then(a.column.cmp(&b.column))
134                .then_with(|| a.rule.cmp(&b.rule))
135        });
136        out
137    }
138
139    #[must_use]
140    pub fn len(&self) -> usize {
141        self.rules.len()
142    }
143
144    #[must_use]
145    pub fn is_empty(&self) -> bool {
146        self.rules.is_empty()
147    }
148}
149
150/// Consumes the set and yields its rules in insertion order.
151///
152/// Required by the CLI's `--rules` selector, which partitions the
153/// available pool of rules into the user-requested subset without
154/// cloning trait objects (`LintRule` is not `Clone`).
155impl IntoIterator for RuleSet {
156    type Item = Box<dyn LintRule>;
157    type IntoIter = std::vec::IntoIter<Box<dyn LintRule>>;
158
159    fn into_iter(self) -> Self::IntoIter {
160        self.rules.into_iter()
161    }
162}
163
164impl fmt::Debug for RuleSet {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        f.debug_struct("RuleSet")
167            .field("rules", &self.rules.iter().map(|r| r.name()).collect::<Vec<_>>())
168            .finish()
169    }
170}
171
172/// Error returned by [`RuleSet::add`] when a name collides with an
173/// already-registered rule.
174#[derive(Debug, Clone)]
175pub struct DuplicateRuleName {
176    pub name: String,
177}
178
179impl fmt::Display for DuplicateRuleName {
180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181        write!(f, "rule already registered: {}", self.name)
182    }
183}
184
185impl std::error::Error for DuplicateRuleName {}
186
187#[cfg(test)]
188mod tests {
189    use super::{DuplicateRuleName, RuleSet};
190    use crate::diagnostic::Diagnostic;
191    use crate::rule::LintRule;
192    use mdwright_document::Document;
193
194    struct Noop(&'static str);
195    impl LintRule for Noop {
196        fn name(&self) -> &str {
197            self.0
198        }
199        fn description(&self) -> &str {
200            "noop"
201        }
202        fn check(&self, _doc: &Document, _out: &mut Vec<Diagnostic>) {}
203    }
204
205    #[test]
206    fn add_and_contains() -> anyhow::Result<()> {
207        let mut rs = RuleSet::new();
208        rs.add(Box::new(Noop("a"))).map_err(|e| anyhow::anyhow!("{e}"))?;
209        assert!(rs.contains("a"));
210        assert!(!rs.contains("b"));
211        Ok(())
212    }
213
214    #[test]
215    fn duplicate_add_errors() -> anyhow::Result<()> {
216        let mut rs = RuleSet::new();
217        rs.add(Box::new(Noop("a"))).map_err(|e| anyhow::anyhow!("{e}"))?;
218        let err = rs.add(Box::new(Noop("a")));
219        assert!(matches!(err, Err(DuplicateRuleName { ref name }) if name == "a"));
220        Ok(())
221    }
222
223    #[test]
224    fn remove_works() -> anyhow::Result<()> {
225        let mut rs = RuleSet::new();
226        rs.add(Box::new(Noop("a"))).map_err(|e| anyhow::anyhow!("{e}"))?;
227        assert!(rs.remove("a"));
228        assert!(!rs.remove("a"));
229        assert!(!rs.contains("a"));
230        Ok(())
231    }
232
233    #[test]
234    fn by_name_finds_or_returns_none() -> anyhow::Result<()> {
235        let mut rs = RuleSet::new();
236        rs.add(Box::new(Noop("a"))).map_err(|e| anyhow::anyhow!("{e}"))?;
237        rs.add(Box::new(Noop("b"))).map_err(|e| anyhow::anyhow!("{e}"))?;
238        assert_eq!(rs.by_name("a").map(LintRule::name), Some("a"));
239        assert_eq!(rs.by_name("b").map(LintRule::name), Some("b"));
240        assert!(rs.by_name("c").is_none());
241        Ok(())
242    }
243
244    #[test]
245    fn names_iterates_in_insertion_order() -> anyhow::Result<()> {
246        let mut rs = RuleSet::new();
247        rs.add(Box::new(Noop("alpha"))).map_err(|e| anyhow::anyhow!("{e}"))?;
248        rs.add(Box::new(Noop("beta"))).map_err(|e| anyhow::anyhow!("{e}"))?;
249        rs.add(Box::new(Noop("gamma"))).map_err(|e| anyhow::anyhow!("{e}"))?;
250        let collected: Vec<&str> = rs.names().collect();
251        assert_eq!(collected, vec!["alpha", "beta", "gamma"]);
252        Ok(())
253    }
254
255    #[test]
256    fn into_iter_yields_owned_boxes_in_insertion_order() -> anyhow::Result<()> {
257        let mut rs = RuleSet::new();
258        rs.add(Box::new(Noop("first"))).map_err(|e| anyhow::anyhow!("{e}"))?;
259        rs.add(Box::new(Noop("second"))).map_err(|e| anyhow::anyhow!("{e}"))?;
260        let names: Vec<String> = rs.into_iter().map(|r| r.name().to_owned()).collect();
261        assert_eq!(names, vec!["first".to_owned(), "second".to_owned()]);
262        Ok(())
263    }
264}