mdwright_lint/
rule_set.rs1use 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#[derive(Default)]
26pub struct RuleSet {
27 rules: Vec<Box<dyn LintRule>>,
28}
29
30impl RuleSet {
31 #[must_use]
33 pub fn new() -> Self {
34 Self { rules: Vec::new() }
35 }
36
37 #[must_use]
40 pub fn stdlib_defaults() -> Self {
41 stdlib::defaults()
42 }
43
44 #[must_use]
47 pub fn stdlib_all() -> Self {
48 stdlib::all()
49 }
50
51 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 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 #[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 pub fn names(&self) -> impl Iterator<Item = &str> {
92 self.rules.iter().map(|r| r.name())
93 }
94
95 #[must_use]
97 pub fn check(&self, doc: &Document) -> Vec<Diagnostic> {
98 self.check_with(doc, LintOptions::default())
99 }
100
101 #[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
150impl 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#[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}