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