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