Skip to main content

rumdl_lib/rules/
md087_unused_disable_comment.rs

1//! Rule MD087: Inline disable comments should suppress something.
2//!
3//! A `<!-- rumdl-disable-line MD013 -->` written to silence a finding stays behind
4//! after the line is rewritten or the rule stops reporting it. Nothing else
5//! notices: a comment that suppresses nothing costs no findings, so it survives
6//! every run and quietly widens the set of rules that cannot report on that line
7//! again.
8//!
9//! The rule judges a comment by what the run around it actually suppressed, so it
10//! reports only what the current configuration makes unnecessary. A comment a
11//! wider one already covers is reported too: with the rule off for the whole file,
12//! a `disable-line` naming it silences nothing of its own, and the wider comment
13//! keeps the line quiet once the narrower one is gone. Three kinds of comment are
14//! deliberately left alone:
15//!
16//! - one naming a rule this run does not carry, since a rule configuration turned
17//!   off produced nothing and its comment cannot be judged by that silence
18//! - one naming no rule at all, which disables every rule at once, including ones
19//!   a given run may not carry
20//! - `<!-- prettier-ignore -->`, which belongs to another formatter
21//!
22//! Detection only. Removing a comment is a content decision: the author may be
23//! about to restore the line that needed it, and `rumdl fmt` must not delete
24//! authored comments on its own.
25
26use crate::inline_config::{DisableSite, collect_disable_sites, normalize_rule_name};
27use crate::lint_context::LintContext;
28use crate::rule::{FixCapability, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity, SuppressionReport};
29
30#[derive(Debug, Clone, Default)]
31pub struct MD087UnusedDisableComment;
32
33impl MD087UnusedDisableComment {
34    pub fn new() -> Self {
35        Self
36    }
37
38    /// The rules a comment names that suppressed nothing, in the order written.
39    ///
40    /// A comment naming no rule returns nothing: it disables every rule, so the
41    /// findings of one run cannot show that it silenced nothing.
42    fn unused_rules(&self, site: &DisableSite, report: &SuppressionReport) -> Vec<String> {
43        let mut unused: Vec<String> = Vec::new();
44
45        for written in &site.rules {
46            // The same canonicalization the inline config applies, so a comment is
47            // judged against the rule it really disables. An unrecognized name
48            // canonicalizes to nothing the run carries and drops out below.
49            let canonical = normalize_rule_name(written);
50            // This rule's own findings are raised after the report is assembled,
51            // so a comment silencing them cannot appear in it.
52            if canonical == self.name() || !report.judged_rules.contains(&canonical) {
53                continue;
54            }
55            let used = report
56                .suppressed
57                .iter()
58                .any(|warning| warning.rule_name == canonical && site.scope.carries(warning.layer, warning.line));
59            if !used && !unused.contains(written) {
60                unused.push(written.clone());
61            }
62        }
63
64        unused
65    }
66
67    fn warning(&self, ctx: &LintContext, site: &DisableSite, unused: &[String]) -> LintWarning {
68        let line_offset = ctx.line_info(site.line).map_or(0, |info| info.byte_offset);
69        let (line, column) = ctx.offset_to_line_col(line_offset + site.span.start);
70        let (_, end_column) = ctx.offset_to_line_col(line_offset + site.span.end);
71        let names = unused.join(", ");
72        // A configure-file comment configures rules rather than disabling a span,
73        // so it is named for what the entry does instead of what the comment is.
74        let message = if site.kind == "configure-file" {
75            format!("Unused configure-file disable: {names}")
76        } else {
77            format!("Unused {} comment: {names}", site.kind)
78        };
79        LintWarning {
80            rule_name: Some(self.name().to_string()),
81            severity: Severity::Warning,
82            line,
83            column,
84            end_line: line,
85            end_column,
86            message,
87            fix: None,
88        }
89    }
90}
91
92impl Rule for MD087UnusedDisableComment {
93    fn name(&self) -> &'static str {
94        "MD087"
95    }
96
97    fn description(&self) -> &'static str {
98        "Inline disable comments should suppress something"
99    }
100
101    fn category(&self) -> RuleCategory {
102        RuleCategory::Other
103    }
104
105    fn should_skip(&self, ctx: &LintContext) -> bool {
106        !ctx.content.contains("<!--")
107    }
108
109    fn check(&self, _ctx: &LintContext) -> LintResult {
110        // A comment is judged by what the rest of the run suppressed, which is
111        // only known once every other rule has finished. That arrives through
112        // check_suppressions.
113        Ok(Vec::new())
114    }
115
116    fn observes_suppressions(&self) -> bool {
117        true
118    }
119
120    fn check_suppressions(&self, ctx: &LintContext, report: &SuppressionReport) -> LintResult {
121        let mut warnings = Vec::new();
122        for site in collect_disable_sites(ctx.content) {
123            let unused = self.unused_rules(&site, report);
124            if unused.is_empty() {
125                continue;
126            }
127            warnings.push(self.warning(ctx, &site, &unused));
128        }
129        Ok(warnings)
130    }
131
132    fn fix_capability(&self) -> FixCapability {
133        FixCapability::Unfixable
134    }
135
136    fn fix(&self, ctx: &LintContext) -> Result<String, LintError> {
137        Ok(ctx.content.to_string())
138    }
139
140    fn as_any(&self) -> &dyn std::any::Any {
141        self
142    }
143
144    fn from_config(_config: &crate::config::Config) -> Box<dyn Rule>
145    where
146        Self: Sized,
147    {
148        Box::new(Self)
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155    use crate::config::MarkdownFlavor;
156    use crate::inline_config::DisableLayer;
157    use crate::rule::SuppressedWarning;
158    use std::collections::HashSet;
159
160    fn report(suppressed: &[(&str, DisableLayer, usize)], judged: &[&str]) -> SuppressionReport {
161        SuppressionReport {
162            suppressed: suppressed
163                .iter()
164                .map(|&(rule_name, layer, line)| SuppressedWarning {
165                    rule_name: rule_name.to_string(),
166                    line,
167                    layer,
168                })
169                .collect(),
170            judged_rules: judged.iter().map(|name| (*name).to_string()).collect::<HashSet<_>>(),
171        }
172    }
173
174    fn check(content: &str, suppressed: &[(&str, DisableLayer, usize)], judged: &[&str]) -> Vec<LintWarning> {
175        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
176        MD087UnusedDisableComment::new()
177            .check_suppressions(&ctx, &report(suppressed, judged))
178            .unwrap()
179    }
180
181    #[test]
182    fn reports_a_disable_line_comment_that_suppressed_nothing() {
183        let content = "# Title\n\nA short line <!-- rumdl-disable-line MD013 -->\n";
184        let warnings = check(content, &[], &["MD013"]);
185        assert_eq!(warnings.len(), 1, "got: {warnings:?}");
186        assert_eq!(warnings[0].message, "Unused disable-line comment: MD013");
187        assert_eq!((warnings[0].line, warnings[0].column), (3, 14));
188        assert_eq!(warnings[0].end_column, 47, "the warning spans the comment");
189        assert!(
190            warnings[0].fix.is_none(),
191            "removing an authored comment is not automatic"
192        );
193    }
194
195    #[test]
196    fn keeps_quiet_when_the_comment_suppressed_a_finding() {
197        let content = "# Title\n\nA short line <!-- rumdl-disable-line MD013 -->\n";
198        let warnings = check(content, &[("MD013", DisableLayer::Line, 3)], &["MD013"]);
199        assert!(warnings.is_empty(), "got: {warnings:?}");
200    }
201
202    #[test]
203    fn a_disable_line_comment_is_judged_on_its_own_line_only() {
204        let content = "<!-- rumdl-disable-line MD013 -->\nA long line\n";
205        let warnings = check(content, &[("MD013", DisableLayer::Line, 2)], &["MD013"]);
206        assert_eq!(warnings.len(), 1, "a finding on line 2 is not this comment's doing");
207        assert_eq!(warnings[0].line, 1);
208    }
209
210    #[test]
211    fn a_disable_next_line_comment_is_judged_on_the_following_line() {
212        let content = "<!-- rumdl-disable-next-line MD013 -->\nA long line\n";
213        assert!(
214            check(content, &[("MD013", DisableLayer::Line, 2)], &["MD013"]).is_empty(),
215            "the suppression on line 2 is what the comment is for"
216        );
217        let warnings = check(content, &[("MD013", DisableLayer::Line, 1)], &["MD013"]);
218        assert_eq!(warnings.len(), 1, "a finding on line 1 is not this comment's doing");
219        assert_eq!(warnings[0].message, "Unused disable-next-line comment: MD013");
220    }
221
222    #[test]
223    fn a_block_disable_reaches_the_end_of_the_document() {
224        let content = "<!-- rumdl-disable MD013 -->\n\ntext\n\n<!-- rumdl-enable MD013 -->\n\nmore\n";
225        assert!(
226            check(content, &[("MD013", DisableLayer::Block, 7)], &["MD013"]).is_empty(),
227            "a scope wider than the truth may only under-report"
228        );
229        let warnings = check(content, &[], &["MD013"]);
230        assert_eq!(warnings.len(), 1, "got: {warnings:?}");
231        assert_eq!(warnings[0].message, "Unused disable comment: MD013");
232    }
233
234    #[test]
235    fn a_disable_file_comment_covers_a_finding_above_it() {
236        let content = "A long line\n\n<!-- rumdl-disable-file MD013 -->\n";
237        assert!(
238            check(content, &[("MD013", DisableLayer::File, 1)], &["MD013"]).is_empty(),
239            "disable-file applies to the whole document, including lines above it"
240        );
241    }
242
243    #[test]
244    fn a_comment_a_wider_one_already_covers_is_reported() {
245        let content = "<!-- rumdl-disable-file MD013 -->\n\nA long line <!-- rumdl-disable-line MD013 -->\n";
246        let warnings = check(content, &[("MD013", DisableLayer::File, 3)], &["MD013"]);
247        assert_eq!(warnings.len(), 1, "got: {warnings:?}");
248        assert_eq!(warnings[0].message, "Unused disable-line comment: MD013");
249        assert_eq!(warnings[0].line, 3, "the file-wide comment is the one doing the work");
250    }
251
252    #[test]
253    fn the_wider_comment_is_the_one_reported_when_the_narrow_one_does_the_work() {
254        // The converse of the case above: the block disable is closed before the
255        // finding, so the line comment is what keeps it quiet.
256        let content = "<!-- rumdl-disable MD013 -->\n<!-- rumdl-enable MD013 -->\nA long line <!-- rumdl-disable-line MD013 -->\n";
257        let warnings = check(content, &[("MD013", DisableLayer::Line, 3)], &["MD013"]);
258        assert_eq!(warnings.len(), 1, "got: {warnings:?}");
259        assert_eq!(warnings[0].message, "Unused disable comment: MD013");
260        assert_eq!(warnings[0].line, 1);
261    }
262
263    #[test]
264    fn only_the_unused_names_of_a_multi_rule_comment_are_reported() {
265        let content = "text <!-- rumdl-disable-line MD013 MD033 MD009 -->\n";
266        let warnings = check(
267            content,
268            &[("MD033", DisableLayer::Line, 1)],
269            &["MD009", "MD013", "MD033"],
270        );
271        assert_eq!(warnings.len(), 1, "got: {warnings:?}");
272        assert_eq!(warnings[0].message, "Unused disable-line comment: MD013, MD009");
273    }
274
275    #[test]
276    fn a_rule_the_run_does_not_carry_is_not_judged() {
277        let content = "text <!-- rumdl-disable-line MD013 -->\n";
278        assert!(
279            check(content, &[], &["MD009"]).is_empty(),
280            "MD013 produced nothing because it did not run"
281        );
282    }
283
284    #[test]
285    fn an_unknown_rule_name_is_not_judged() {
286        let content = "text <!-- rumdl-disable-line MD999 -->\n";
287        assert!(
288            check(content, &[], &["MD013"]).is_empty(),
289            "MD999 is not a rule the run carries"
290        );
291    }
292
293    #[test]
294    fn a_comment_naming_no_rule_is_never_reported() {
295        let content = "text <!-- rumdl-disable-line -->\n<!-- rumdl-disable -->\n";
296        assert!(
297            check(content, &[], &["MD013"]).is_empty(),
298            "a bare comment disables rules this run may not carry"
299        );
300    }
301
302    #[test]
303    fn prettier_ignore_belongs_to_another_formatter() {
304        let content = "<!-- prettier-ignore -->\n| a | b |\n";
305        assert!(
306            check(content, &[], &["MD013"]).is_empty(),
307            "not rumdl's comment to judge"
308        );
309    }
310
311    #[test]
312    fn a_comment_inside_a_code_block_configures_nothing() {
313        let content = "# Title\n\n```markdown\n<!-- rumdl-disable-line MD013 -->\n```\n";
314        assert!(
315            check(content, &[], &["MD013"]).is_empty(),
316            "a fenced example documents a comment rather than writing one"
317        );
318    }
319
320    #[test]
321    fn an_alias_is_reported_as_the_author_wrote_it() {
322        let content = "text <!-- rumdl-disable-line line-length -->\n";
323        let warnings = check(content, &[], &["MD013"]);
324        assert_eq!(warnings.len(), 1, "got: {warnings:?}");
325        assert_eq!(warnings[0].message, "Unused disable-line comment: line-length");
326    }
327
328    #[test]
329    fn a_markdownlint_comment_is_judged_the_same_way() {
330        let content = "text <!-- markdownlint-disable-line MD013 -->\n";
331        let warnings = check(content, &[], &["MD013"]);
332        assert_eq!(warnings.len(), 1, "got: {warnings:?}");
333        assert_eq!(warnings[0].message, "Unused disable-line comment: MD013");
334    }
335
336    #[test]
337    fn a_configure_file_entry_turning_a_rule_off_is_judged_like_a_disable() {
338        let content = "<!-- rumdl-configure-file { \"MD013\": false } -->\n\ntext\n";
339        let warnings = check(content, &[], &["MD013"]);
340        assert_eq!(warnings.len(), 1, "got: {warnings:?}");
341        assert_eq!(warnings[0].message, "Unused configure-file disable: MD013");
342        assert!(
343            check(content, &[("MD013", DisableLayer::File, 3)], &["MD013"]).is_empty(),
344            "the entry turned the rule off for the whole file"
345        );
346    }
347
348    #[test]
349    fn a_configure_file_entry_carrying_options_is_not_a_disable() {
350        let content = "<!-- rumdl-configure-file { \"MD013\": { \"line_length\": 200 } } -->\n\ntext\n";
351        assert!(
352            check(content, &[], &["MD013"]).is_empty(),
353            "configuring a rule is not suppressing it"
354        );
355    }
356
357    #[test]
358    fn this_rule_never_judges_a_comment_silencing_itself() {
359        let content = "text <!-- rumdl-disable-line MD087 -->\n";
360        assert!(
361            check(content, &[], &["MD013", "MD087"]).is_empty(),
362            "MD087 findings are raised after the report is assembled"
363        );
364    }
365
366    #[test]
367    fn the_column_is_measured_in_characters() {
368        let content = "héllo wörld <!-- rumdl-disable-line MD013 -->\n";
369        let warnings = check(content, &[], &["MD013"]);
370        assert_eq!(warnings.len(), 1, "got: {warnings:?}");
371        assert_eq!(warnings[0].column, 13, "two multi-byte characters precede the comment");
372    }
373
374    #[test]
375    fn check_reports_nothing_on_its_own() {
376        let content = "text <!-- rumdl-disable-line MD013 -->\n";
377        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
378        assert!(
379            MD087UnusedDisableComment::new().check(&ctx).unwrap().is_empty(),
380            "the verdict needs the run's suppressions"
381        );
382    }
383}