Skip to main content

rumdl_lib/rules/
mod.rs

1pub mod code_fence_utils;
2pub mod emphasis_style;
3pub mod front_matter_utils;
4pub mod heading_utils;
5pub mod strong_style;
6
7mod md001_heading_increment;
8mod md003_heading_style;
9pub mod md004_unordered_list_style;
10mod md005_list_indent;
11pub mod md007_ul_indent;
12mod md009_trailing_spaces;
13pub mod md010_no_hard_tabs;
14mod md011_no_reversed_links;
15pub mod md013_line_length;
16mod md014_commands_show_output;
17mod md024_no_duplicate_heading;
18mod md025_single_title;
19mod md026_no_trailing_punctuation;
20mod md027_multiple_spaces_blockquote;
21mod md028_no_blanks_blockquote;
22mod md029_ordered_list_prefix;
23pub mod md030_list_marker_space;
24mod md031_blanks_around_fences;
25mod md032_blanks_around_lists;
26mod md033_no_inline_html;
27mod md034_no_bare_urls;
28mod md035_hr_style;
29pub mod md036_no_emphasis_only_first;
30mod md037_spaces_around_emphasis;
31mod md038_no_space_in_code;
32mod md039_no_space_in_links;
33pub mod md040_fenced_code_language;
34mod md041_first_line_heading;
35mod md042_no_empty_links;
36mod md043_required_headings;
37mod md044_proper_names;
38mod md045_no_alt_text;
39mod md046_code_block_style;
40mod md047_single_trailing_newline;
41mod md048_code_fence_style;
42mod md049_emphasis_style;
43mod md050_strong_style;
44pub mod md051_link_fragments;
45mod md052_reference_links_images;
46mod md053_link_image_reference_definitions;
47mod md054_link_image_style;
48mod md055_table_pipe_style;
49mod md056_table_column_count;
50mod md058_blanks_around_tables;
51mod md059_link_text;
52mod md060_table_format;
53mod md061_forbidden_terms;
54mod md062_link_destination_whitespace;
55mod md063_heading_capitalization;
56mod md064_no_multiple_consecutive_spaces;
57mod md065_blanks_around_horizontal_rules;
58mod md066_footnote_validation;
59mod md067_footnote_definition_order;
60mod md068_empty_footnote_definition;
61mod md069_no_duplicate_list_markers;
62mod md070_nested_code_fence;
63mod md071_blank_line_after_frontmatter;
64mod md072_frontmatter_key_sort;
65mod md073_toc_validation;
66mod md074_mkdocs_nav;
67mod md075_orphaned_table_rows;
68mod md076_list_item_spacing;
69mod md077_list_continuation_indent;
70mod md078_missing_chunk_labels;
71mod md079_chunk_label_spaces;
72mod md080_heading_anchor_collision;
73mod md081_no_excessive_emphasis;
74mod md082_no_empty_sections;
75mod md083_mojibake;
76mod md084_invisible_characters;
77mod md085_paragraph_continuation_indent;
78
79pub use code_fence_utils::CodeFenceStyle;
80pub use md001_heading_increment::MD001HeadingIncrement;
81pub use md003_heading_style::MD003HeadingStyle;
82pub use md004_unordered_list_style::MD004UnorderedListStyle;
83pub use md004_unordered_list_style::UnorderedListStyle;
84pub use md005_list_indent::MD005ListIndent;
85pub use md007_ul_indent::MD007ULIndent;
86pub use md009_trailing_spaces::MD009TrailingSpaces;
87pub use md010_no_hard_tabs::{MD010Config, MD010NoHardTabs};
88pub use md011_no_reversed_links::MD011NoReversedLinks;
89pub use md013_line_length::MD013Config;
90pub use md013_line_length::MD013LineLength;
91pub use md014_commands_show_output::MD014CommandsShowOutput;
92pub use md024_no_duplicate_heading::MD024NoDuplicateHeading;
93pub use md025_single_title::MD025SingleTitle;
94pub use md026_no_trailing_punctuation::MD026NoTrailingPunctuation;
95pub use md027_multiple_spaces_blockquote::MD027MultipleSpacesBlockquote;
96pub use md028_no_blanks_blockquote::MD028NoBlanksBlockquote;
97pub use md029_ordered_list_prefix::{ListStyle, MD029OrderedListPrefix};
98pub use md030_list_marker_space::MD030ListMarkerSpace;
99pub use md031_blanks_around_fences::MD031BlanksAroundFences;
100pub use md032_blanks_around_lists::MD032BlanksAroundLists;
101pub use md033_no_inline_html::MD033NoInlineHtml;
102pub use md034_no_bare_urls::MD034NoBareUrls;
103pub use md035_hr_style::MD035HRStyle;
104pub use md036_no_emphasis_only_first::MD036NoEmphasisAsHeading;
105pub use md037_spaces_around_emphasis::MD037NoSpaceInEmphasis;
106pub use md038_no_space_in_code::MD038NoSpaceInCode;
107pub use md039_no_space_in_links::MD039NoSpaceInLinks;
108pub use md040_fenced_code_language::MD040FencedCodeLanguage;
109pub use md041_first_line_heading::MD041FirstLineHeading;
110pub use md042_no_empty_links::MD042NoEmptyLinks;
111pub use md043_required_headings::MD043RequiredHeadings;
112pub use md044_proper_names::MD044ProperNames;
113pub use md045_no_alt_text::MD045NoAltText;
114pub use md046_code_block_style::{CodeBlockStyle, MD046CodeBlockStyle};
115pub use md047_single_trailing_newline::MD047SingleTrailingNewline;
116pub use md048_code_fence_style::MD048CodeFenceStyle;
117pub use md049_emphasis_style::MD049EmphasisStyle;
118pub use md050_strong_style::MD050StrongStyle;
119pub use md051_link_fragments::MD051LinkFragments;
120pub use md052_reference_links_images::MD052ReferenceLinkImages;
121pub use md053_link_image_reference_definitions::MD053LinkImageReferenceDefinitions;
122pub use md054_link_image_style::MD054LinkImageStyle;
123pub use md055_table_pipe_style::MD055TablePipeStyle;
124pub use md056_table_column_count::MD056TableColumnCount;
125pub use md058_blanks_around_tables::MD058BlanksAroundTables;
126pub use md059_link_text::MD059LinkText;
127pub use md060_table_format::ColumnAlign;
128pub use md060_table_format::MD060Config;
129pub use md060_table_format::MD060TableFormat;
130pub use md061_forbidden_terms::MD061ForbiddenTerms;
131pub use md062_link_destination_whitespace::MD062LinkDestinationWhitespace;
132pub use md063_heading_capitalization::MD063HeadingCapitalization;
133pub use md064_no_multiple_consecutive_spaces::MD064NoMultipleConsecutiveSpaces;
134pub use md065_blanks_around_horizontal_rules::MD065BlanksAroundHorizontalRules;
135pub use md066_footnote_validation::MD066FootnoteValidation;
136pub use md067_footnote_definition_order::MD067FootnoteDefinitionOrder;
137pub use md068_empty_footnote_definition::MD068EmptyFootnoteDefinition;
138pub use md069_no_duplicate_list_markers::MD069NoDuplicateListMarkers;
139pub use md070_nested_code_fence::MD070NestedCodeFence;
140pub use md071_blank_line_after_frontmatter::MD071BlankLineAfterFrontmatter;
141pub use md072_frontmatter_key_sort::MD072FrontmatterKeySort;
142pub use md073_toc_validation::MD073TocValidation;
143pub use md074_mkdocs_nav::MD074MkDocsNav;
144pub use md075_orphaned_table_rows::MD075OrphanedTableRows;
145pub use md076_list_item_spacing::{ListItemSpacingStyle, MD076ListItemSpacing};
146pub use md077_list_continuation_indent::{ContinuationStyle, MD077ListContinuationIndent};
147pub use md078_missing_chunk_labels::MD078MissingChunkLabels;
148pub use md079_chunk_label_spaces::MD079ChunkLabelSpaces;
149pub use md080_heading_anchor_collision::MD080HeadingAnchorCollision;
150pub use md081_no_excessive_emphasis::MD081NoExcessiveEmphasis;
151pub use md082_no_empty_sections::MD082NoEmptySections;
152pub use md083_mojibake::MD083DetectMojibake;
153pub use md084_invisible_characters::MD084InvisibleCharacters;
154pub use md085_paragraph_continuation_indent::MD085ParagraphContinuationIndent;
155
156mod md012_no_multiple_blanks;
157pub use md012_no_multiple_blanks::MD012NoMultipleBlanks;
158
159mod md018_no_missing_space_atx;
160pub use md018_no_missing_space_atx::MD018NoMissingSpaceAtx;
161
162mod md019_no_multiple_space_atx;
163pub use md019_no_multiple_space_atx::MD019NoMultipleSpaceAtx;
164
165mod md020_no_missing_space_closed_atx;
166mod md021_no_multiple_space_closed_atx;
167pub use md020_no_missing_space_closed_atx::MD020NoMissingSpaceClosedAtx;
168pub use md021_no_multiple_space_closed_atx::MD021NoMultipleSpaceClosedAtx;
169
170pub(crate) mod md022_blanks_around_headings;
171pub use md022_blanks_around_headings::MD022BlanksAroundHeadings;
172
173mod md023_heading_start_left;
174pub use md023_heading_start_left::MD023HeadingStartLeft;
175
176mod md057_existing_relative_links;
177
178pub use md057_existing_relative_links::{AbsoluteLinksOption, MD057Config, MD057ExistingRelativeLinks};
179
180use crate::rule::Rule;
181
182/// Type alias for rule constructor functions
183type RuleCtor = fn(&crate::config::Config) -> Box<dyn Rule>;
184
185/// Entry in the rule registry, with metadata about the rule
186struct RuleEntry {
187    name: &'static str,
188    ctor: RuleCtor,
189    /// Whether this rule requires explicit opt-in via extend-enable or enable=["ALL"]
190    opt_in: bool,
191}
192
193/// Registry of all available rules with their constructor functions
194/// This enables automatic inline config support - the engine can recreate
195/// any rule with a merged config without per-rule changes.
196///
197/// Rules marked `opt_in: true` are excluded from the default rule set and must
198/// be explicitly enabled via `extend-enable` or `enable = ["ALL"]`.
199const RULES: &[RuleEntry] = &[
200    RuleEntry {
201        name: "MD001",
202        ctor: MD001HeadingIncrement::from_config,
203        opt_in: false,
204    },
205    RuleEntry {
206        name: "MD003",
207        ctor: MD003HeadingStyle::from_config,
208        opt_in: false,
209    },
210    RuleEntry {
211        name: "MD004",
212        ctor: MD004UnorderedListStyle::from_config,
213        opt_in: false,
214    },
215    RuleEntry {
216        name: "MD005",
217        ctor: MD005ListIndent::from_config,
218        opt_in: false,
219    },
220    RuleEntry {
221        name: "MD007",
222        ctor: MD007ULIndent::from_config,
223        opt_in: false,
224    },
225    RuleEntry {
226        name: "MD009",
227        ctor: MD009TrailingSpaces::from_config,
228        opt_in: false,
229    },
230    RuleEntry {
231        name: "MD010",
232        ctor: MD010NoHardTabs::from_config,
233        opt_in: false,
234    },
235    RuleEntry {
236        name: "MD011",
237        ctor: MD011NoReversedLinks::from_config,
238        opt_in: false,
239    },
240    RuleEntry {
241        name: "MD012",
242        ctor: MD012NoMultipleBlanks::from_config,
243        opt_in: false,
244    },
245    RuleEntry {
246        name: "MD013",
247        ctor: MD013LineLength::from_config,
248        opt_in: false,
249    },
250    RuleEntry {
251        name: "MD014",
252        ctor: MD014CommandsShowOutput::from_config,
253        opt_in: false,
254    },
255    RuleEntry {
256        name: "MD018",
257        ctor: MD018NoMissingSpaceAtx::from_config,
258        opt_in: false,
259    },
260    RuleEntry {
261        name: "MD019",
262        ctor: MD019NoMultipleSpaceAtx::from_config,
263        opt_in: false,
264    },
265    RuleEntry {
266        name: "MD020",
267        ctor: MD020NoMissingSpaceClosedAtx::from_config,
268        opt_in: false,
269    },
270    RuleEntry {
271        name: "MD021",
272        ctor: MD021NoMultipleSpaceClosedAtx::from_config,
273        opt_in: false,
274    },
275    RuleEntry {
276        name: "MD022",
277        ctor: MD022BlanksAroundHeadings::from_config,
278        opt_in: false,
279    },
280    RuleEntry {
281        name: "MD023",
282        ctor: MD023HeadingStartLeft::from_config,
283        opt_in: false,
284    },
285    RuleEntry {
286        name: "MD024",
287        ctor: MD024NoDuplicateHeading::from_config,
288        opt_in: false,
289    },
290    RuleEntry {
291        name: "MD025",
292        ctor: MD025SingleTitle::from_config,
293        opt_in: false,
294    },
295    RuleEntry {
296        name: "MD026",
297        ctor: MD026NoTrailingPunctuation::from_config,
298        opt_in: false,
299    },
300    RuleEntry {
301        name: "MD027",
302        ctor: MD027MultipleSpacesBlockquote::from_config,
303        opt_in: false,
304    },
305    RuleEntry {
306        name: "MD028",
307        ctor: MD028NoBlanksBlockquote::from_config,
308        opt_in: false,
309    },
310    RuleEntry {
311        name: "MD029",
312        ctor: MD029OrderedListPrefix::from_config,
313        opt_in: false,
314    },
315    RuleEntry {
316        name: "MD030",
317        ctor: MD030ListMarkerSpace::from_config,
318        opt_in: false,
319    },
320    RuleEntry {
321        name: "MD031",
322        ctor: MD031BlanksAroundFences::from_config,
323        opt_in: false,
324    },
325    RuleEntry {
326        name: "MD032",
327        ctor: MD032BlanksAroundLists::from_config,
328        opt_in: false,
329    },
330    RuleEntry {
331        name: "MD033",
332        ctor: MD033NoInlineHtml::from_config,
333        opt_in: false,
334    },
335    RuleEntry {
336        name: "MD034",
337        ctor: MD034NoBareUrls::from_config,
338        opt_in: false,
339    },
340    RuleEntry {
341        name: "MD035",
342        ctor: MD035HRStyle::from_config,
343        opt_in: false,
344    },
345    RuleEntry {
346        name: "MD036",
347        ctor: MD036NoEmphasisAsHeading::from_config,
348        opt_in: false,
349    },
350    RuleEntry {
351        name: "MD037",
352        ctor: MD037NoSpaceInEmphasis::from_config,
353        opt_in: false,
354    },
355    RuleEntry {
356        name: "MD038",
357        ctor: MD038NoSpaceInCode::from_config,
358        opt_in: false,
359    },
360    RuleEntry {
361        name: "MD039",
362        ctor: MD039NoSpaceInLinks::from_config,
363        opt_in: false,
364    },
365    RuleEntry {
366        name: "MD040",
367        ctor: MD040FencedCodeLanguage::from_config,
368        opt_in: false,
369    },
370    RuleEntry {
371        name: "MD041",
372        ctor: MD041FirstLineHeading::from_config,
373        opt_in: false,
374    },
375    RuleEntry {
376        name: "MD042",
377        ctor: MD042NoEmptyLinks::from_config,
378        opt_in: false,
379    },
380    RuleEntry {
381        name: "MD043",
382        ctor: MD043RequiredHeadings::from_config,
383        opt_in: false,
384    },
385    RuleEntry {
386        name: "MD044",
387        ctor: MD044ProperNames::from_config,
388        opt_in: false,
389    },
390    RuleEntry {
391        name: "MD045",
392        ctor: MD045NoAltText::from_config,
393        opt_in: false,
394    },
395    RuleEntry {
396        name: "MD046",
397        ctor: MD046CodeBlockStyle::from_config,
398        opt_in: false,
399    },
400    RuleEntry {
401        name: "MD047",
402        ctor: MD047SingleTrailingNewline::from_config,
403        opt_in: false,
404    },
405    RuleEntry {
406        name: "MD048",
407        ctor: MD048CodeFenceStyle::from_config,
408        opt_in: false,
409    },
410    RuleEntry {
411        name: "MD049",
412        ctor: MD049EmphasisStyle::from_config,
413        opt_in: false,
414    },
415    RuleEntry {
416        name: "MD050",
417        ctor: MD050StrongStyle::from_config,
418        opt_in: false,
419    },
420    RuleEntry {
421        name: "MD051",
422        ctor: MD051LinkFragments::from_config,
423        opt_in: false,
424    },
425    RuleEntry {
426        name: "MD052",
427        ctor: MD052ReferenceLinkImages::from_config,
428        opt_in: false,
429    },
430    RuleEntry {
431        name: "MD053",
432        ctor: MD053LinkImageReferenceDefinitions::from_config,
433        opt_in: false,
434    },
435    RuleEntry {
436        name: "MD054",
437        ctor: MD054LinkImageStyle::from_config,
438        opt_in: false,
439    },
440    RuleEntry {
441        name: "MD055",
442        ctor: MD055TablePipeStyle::from_config,
443        opt_in: false,
444    },
445    RuleEntry {
446        name: "MD056",
447        ctor: MD056TableColumnCount::from_config,
448        opt_in: false,
449    },
450    RuleEntry {
451        name: "MD057",
452        ctor: MD057ExistingRelativeLinks::from_config,
453        opt_in: false,
454    },
455    RuleEntry {
456        name: "MD058",
457        ctor: MD058BlanksAroundTables::from_config,
458        opt_in: false,
459    },
460    RuleEntry {
461        name: "MD059",
462        ctor: MD059LinkText::from_config,
463        opt_in: false,
464    },
465    RuleEntry {
466        name: "MD060",
467        ctor: MD060TableFormat::from_config,
468        opt_in: true,
469    },
470    RuleEntry {
471        name: "MD061",
472        ctor: MD061ForbiddenTerms::from_config,
473        opt_in: false,
474    },
475    RuleEntry {
476        name: "MD062",
477        ctor: MD062LinkDestinationWhitespace::from_config,
478        opt_in: false,
479    },
480    RuleEntry {
481        name: "MD063",
482        ctor: MD063HeadingCapitalization::from_config,
483        opt_in: true,
484    },
485    RuleEntry {
486        name: "MD064",
487        ctor: MD064NoMultipleConsecutiveSpaces::from_config,
488        opt_in: false,
489    },
490    RuleEntry {
491        name: "MD065",
492        ctor: MD065BlanksAroundHorizontalRules::from_config,
493        opt_in: false,
494    },
495    RuleEntry {
496        name: "MD066",
497        ctor: MD066FootnoteValidation::from_config,
498        opt_in: false,
499    },
500    RuleEntry {
501        name: "MD067",
502        ctor: MD067FootnoteDefinitionOrder::from_config,
503        opt_in: false,
504    },
505    RuleEntry {
506        name: "MD068",
507        ctor: MD068EmptyFootnoteDefinition::from_config,
508        opt_in: false,
509    },
510    RuleEntry {
511        name: "MD069",
512        ctor: MD069NoDuplicateListMarkers::from_config,
513        opt_in: false,
514    },
515    RuleEntry {
516        name: "MD070",
517        ctor: MD070NestedCodeFence::from_config,
518        opt_in: true,
519    },
520    RuleEntry {
521        name: "MD071",
522        ctor: MD071BlankLineAfterFrontmatter::from_config,
523        opt_in: false,
524    },
525    RuleEntry {
526        name: "MD072",
527        ctor: MD072FrontmatterKeySort::from_config,
528        opt_in: true,
529    },
530    RuleEntry {
531        name: "MD073",
532        ctor: MD073TocValidation::from_config,
533        opt_in: true,
534    },
535    RuleEntry {
536        name: "MD074",
537        ctor: MD074MkDocsNav::from_config,
538        opt_in: true,
539    },
540    RuleEntry {
541        name: "MD075",
542        ctor: MD075OrphanedTableRows::from_config,
543        opt_in: false,
544    },
545    RuleEntry {
546        name: "MD076",
547        ctor: MD076ListItemSpacing::from_config,
548        opt_in: false,
549    },
550    RuleEntry {
551        name: "MD077",
552        ctor: MD077ListContinuationIndent::from_config,
553        opt_in: false,
554    },
555    RuleEntry {
556        name: "MD078",
557        ctor: MD078MissingChunkLabels::from_config,
558        opt_in: false,
559    },
560    RuleEntry {
561        name: "MD079",
562        ctor: MD079ChunkLabelSpaces::from_config,
563        opt_in: false,
564    },
565    RuleEntry {
566        name: "MD080",
567        ctor: MD080HeadingAnchorCollision::from_config,
568        opt_in: true,
569    },
570    RuleEntry {
571        name: "MD081",
572        ctor: MD081NoExcessiveEmphasis::from_config,
573        opt_in: false,
574    },
575    RuleEntry {
576        name: "MD082",
577        ctor: MD082NoEmptySections::from_config,
578        opt_in: true,
579    },
580    RuleEntry {
581        name: "MD083",
582        ctor: MD083DetectMojibake::from_config,
583        opt_in: true,
584    },
585    RuleEntry {
586        name: "MD084",
587        ctor: MD084InvisibleCharacters::from_config,
588        opt_in: true,
589    },
590    RuleEntry {
591        name: "MD085",
592        ctor: MD085ParagraphContinuationIndent::from_config,
593        opt_in: true,
594    },
595];
596
597/// Returns all rule instances (including opt-in) for config validation and CLI
598pub fn all_rules(config: &crate::config::Config) -> Vec<Box<dyn Rule>> {
599    RULES.iter().map(|entry| (entry.ctor)(config)).collect()
600}
601
602/// Returns the set of rule names that require explicit opt-in
603pub fn opt_in_rules() -> HashSet<&'static str> {
604    RULES
605        .iter()
606        .filter(|entry| entry.opt_in)
607        .map(|entry| entry.name)
608        .collect()
609}
610
611/// Creates a single rule by name with the given config
612///
613/// This enables automatic inline config support - the engine can recreate
614/// any rule with a merged config without per-rule changes.
615///
616/// Returns None if the rule name is not found.
617pub fn create_rule_by_name(name: &str, config: &crate::config::Config) -> Option<Box<dyn Rule>> {
618    RULES
619        .iter()
620        .find(|entry| entry.name == name)
621        .map(|entry| (entry.ctor)(config))
622}
623
624// Filter rules based on config (moved from main.rs)
625// Note: This needs access to GlobalConfig from the config module.
626use crate::config::GlobalConfig;
627use std::collections::HashSet;
628
629/// Check whether the enable list contains the "all" keyword (case-insensitive).
630fn contains_all_keyword(list: &[String]) -> bool {
631    list.iter().any(|s| s.eq_ignore_ascii_case("all"))
632}
633
634/// Build a canonical-form `HashSet` from a rule-name list.
635///
636/// Rewrites every entry through `resolve_rule_name` so aliases
637/// (`"no-inline-html"`) match the same set as canonical IDs (`"MD033"`).
638/// The `"all"` keyword is preserved (case-folded to lowercase) so the
639/// special-case branches in `filter_rules` continue to work.
640fn canonical_rule_set(list: &[String]) -> HashSet<String> {
641    list.iter()
642        .map(|s| {
643            if s.eq_ignore_ascii_case("all") {
644                "all".to_string()
645            } else {
646                crate::config::resolve_rule_name(s)
647            }
648        })
649        .collect()
650}
651
652/// Filter `rules` according to `global_config.{enable,disable,extend_enable,extend_disable}`.
653///
654/// Rule-name entries may be either canonical IDs (`"MD033"`) or aliases
655/// (`"no-inline-html"`); both forms match identically. Canonical IDs are
656/// the norm — every `Config` produced through a mutation boundary
657/// (`From<SourcedConfig> for Config`, LSP `apply_lsp_settings_*`, WASM
658/// `to_config_with_warnings`) is canonicalised by
659/// `Config::canonicalize_rule_lists`. The defensive canonicalisation here
660/// keeps `filter_rules` correct for programmatic callers that build a
661/// `GlobalConfig` without going through those boundaries.
662pub fn filter_rules(rules: &[Box<dyn Rule>], global_config: &GlobalConfig) -> Vec<Box<dyn Rule>> {
663    let mut enabled_rules: Vec<Box<dyn Rule>> = Vec::new();
664    let disabled_rules: HashSet<String> = canonical_rule_set(&global_config.disable);
665    let opt_in_set = opt_in_rules();
666    let extend_enable_set: HashSet<String> = canonical_rule_set(&global_config.extend_enable);
667    let extend_disable_set: HashSet<String> = canonical_rule_set(&global_config.extend_disable);
668
669    let extend_enable_all = contains_all_keyword(&global_config.extend_enable);
670    let extend_disable_all = contains_all_keyword(&global_config.extend_disable);
671
672    // Helper: should this rule be removed by any disable source?
673    let is_disabled = |name: &str| -> bool {
674        disabled_rules.contains(name) || extend_disable_all || extend_disable_set.contains(name)
675    };
676
677    // Handle 'disable: ["all"]'
678    if disabled_rules.contains("all") {
679        // If 'enable' is also provided, only those rules are enabled, overriding "disable all"
680        if !global_config.enable.is_empty() {
681            if contains_all_keyword(&global_config.enable) {
682                // enable: ["ALL"] + disable: ["all"] cancel out → all rules enabled
683                for rule in rules {
684                    enabled_rules.push(dyn_clone::clone_box(&**rule));
685                }
686            } else {
687                let enabled_set: HashSet<String> = canonical_rule_set(&global_config.enable);
688                for rule in rules {
689                    if enabled_set.contains(rule.name()) {
690                        enabled_rules.push(dyn_clone::clone_box(&**rule));
691                    }
692                }
693            }
694        }
695        // If 'enable' is empty and 'disable: ["all"]', return empty vector.
696        return enabled_rules;
697    }
698
699    // If 'enable' is specified, only use those rules
700    if !global_config.enable.is_empty() || global_config.enable_is_explicit {
701        if contains_all_keyword(&global_config.enable) || extend_enable_all {
702            // enable: ["ALL"] or extend-enable: ["ALL"] → all rules including opt-in
703            for rule in rules {
704                if !is_disabled(rule.name()) {
705                    enabled_rules.push(dyn_clone::clone_box(&**rule));
706                }
707            }
708        } else {
709            // Merge enable set with extend-enable
710            let mut enabled_set: HashSet<String> = canonical_rule_set(&global_config.enable);
711            for name in &extend_enable_set {
712                enabled_set.insert(name.clone());
713            }
714            for rule in rules {
715                if enabled_set.contains(rule.name()) && !is_disabled(rule.name()) {
716                    enabled_rules.push(dyn_clone::clone_box(&**rule));
717                }
718            }
719        }
720    } else if extend_enable_all {
721        // No explicit enable, but extend-enable: ["ALL"] → all rules including opt-in
722        for rule in rules {
723            if !is_disabled(rule.name()) {
724                enabled_rules.push(dyn_clone::clone_box(&**rule));
725            }
726        }
727    } else {
728        // No explicit enable: use all non-opt-in rules + extend-enable, minus disable
729        for rule in rules {
730            let is_opt_in = opt_in_set.contains(rule.name());
731            let explicitly_extended = extend_enable_set.contains(rule.name());
732            if (!is_opt_in || explicitly_extended) && !is_disabled(rule.name()) {
733                enabled_rules.push(dyn_clone::clone_box(&**rule));
734            }
735        }
736    }
737
738    enabled_rules
739}
740
741/// Return `rules` with every rule excluded for `path` by `[per-file-ignores]`
742/// removed.
743///
744/// This is the lint/check-side counterpart to the fix coordinator's internal
745/// per-file-ignore handling: callers that lint a specific file run their rule
746/// set through this so diagnostics never report a rule the file has excluded,
747/// mirroring what the coordinator guarantees on the fix side. Returns a clone
748/// of `rules` unchanged when the file excludes nothing.
749pub fn filter_rules_for_file(
750    rules: &[Box<dyn Rule>],
751    config: &crate::config::Config,
752    path: &std::path::Path,
753) -> Vec<Box<dyn Rule>> {
754    let ignored = config.get_ignored_rules_for_file(path);
755    if ignored.is_empty() {
756        return rules.to_vec();
757    }
758    rules
759        .iter()
760        .filter(|rule| !ignored.contains(rule.name()))
761        .map(|r| dyn_clone::clone_box(&**r))
762        .collect()
763}
764
765#[cfg(test)]
766mod filter_rules_alias_tests {
767    use super::*;
768    use crate::config::Config;
769
770    /// `filter_rules` must accept aliases in `disable` even when the caller
771    /// builds a `GlobalConfig` directly (bypassing the canonicalisation
772    /// boundary in `From<SourcedConfig> for Config`). This is the public-API
773    /// guarantee that programmatic library callers depend on.
774    #[test]
775    fn alias_in_disable_filters_canonical_rule() {
776        let config = Config::default();
777        let rules = all_rules(&config);
778        let global = GlobalConfig {
779            disable: vec!["no-inline-html".to_string()],
780            ..Default::default()
781        };
782
783        let filtered = filter_rules(&rules, &global);
784        assert!(
785            !filtered.iter().any(|r| r.name() == "MD033"),
786            "filter_rules must drop MD033 when its alias `no-inline-html` is in disable, \
787             even on a hand-built GlobalConfig. Got: {:?}",
788            filtered.iter().map(|r| r.name()).collect::<Vec<_>>(),
789        );
790    }
791
792    /// Same guarantee for `extend_disable`.
793    #[test]
794    fn alias_in_extend_disable_filters_canonical_rule() {
795        let config = Config::default();
796        let rules = all_rules(&config);
797        let global = GlobalConfig {
798            extend_disable: vec!["line-length".to_string()],
799            ..Default::default()
800        };
801
802        let filtered = filter_rules(&rules, &global);
803        assert!(
804            !filtered.iter().any(|r| r.name() == "MD013"),
805            "filter_rules must drop MD013 when alias `line-length` is in extend_disable. Got: {:?}",
806            filtered.iter().map(|r| r.name()).collect::<Vec<_>>(),
807        );
808    }
809
810    /// `enable` aliases must select the canonical rule.
811    #[test]
812    fn alias_in_enable_selects_canonical_rule() {
813        let config = Config::default();
814        let rules = all_rules(&config);
815        let global = GlobalConfig {
816            enable: vec!["no-inline-html".to_string()],
817            ..Default::default()
818        };
819
820        let filtered = filter_rules(&rules, &global);
821        let names: Vec<&str> = filtered.iter().map(|r| r.name()).collect();
822        assert_eq!(
823            names,
824            vec!["MD033"],
825            "filter_rules must select only MD033 when alias `no-inline-html` is the sole enable. \
826             Got: {names:?}",
827        );
828    }
829
830    /// The canonical-IDs invariant is preserved: a config that is already
831    /// canonical produces the same filter result as one that uses aliases.
832    #[test]
833    fn alias_and_canonical_produce_identical_filter_result() {
834        let config = Config::default();
835        let rules = all_rules(&config);
836
837        let alias_global = GlobalConfig {
838            disable: vec!["no-inline-html".to_string(), "line-length".to_string()],
839            ..Default::default()
840        };
841        let canonical_global = GlobalConfig {
842            disable: vec!["MD033".to_string(), "MD013".to_string()],
843            ..Default::default()
844        };
845
846        let alias_names: Vec<&str> = filter_rules(&rules, &alias_global).iter().map(|r| r.name()).collect();
847        let canonical_names: Vec<&str> = filter_rules(&rules, &canonical_global)
848            .iter()
849            .map(|r| r.name())
850            .collect();
851        assert_eq!(alias_names, canonical_names);
852    }
853}