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