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