Skip to main content

rumdl_lib/config/
registry.rs

1use std::sync::LazyLock;
2
3use crate::rule::Rule;
4
5use super::flavor::normalize_key;
6
7/// Lazily-initialized default `RuleRegistry` built from rules with default config.
8///
9/// Rule config schemas (valid keys, types, aliases) are intrinsic to each rule type
10/// and do not change based on runtime configuration. This static registry avoids
11/// repeatedly constructing 67+ rule instances just to extract their schemas.
12static DEFAULT_REGISTRY: LazyLock<RuleRegistry> = LazyLock::new(|| {
13    let default_config = super::types::Config::default();
14    let rules = crate::rules::all_rules(&default_config);
15    RuleRegistry::from_rules(&rules)
16});
17
18/// Returns a reference to the lazily-initialized default `RuleRegistry`.
19///
20/// Use this instead of `all_rules(&Config::default())` + `RuleRegistry::from_rules()`
21/// when you only need rule metadata (names, config schemas, aliases) rather than
22/// configured rule instances for linting.
23pub fn default_registry() -> &'static RuleRegistry {
24    &DEFAULT_REGISTRY
25}
26
27/// Registry of all known rules and their config schemas
28pub struct RuleRegistry {
29    /// Map of rule name (e.g. "MD013") to set of valid config keys and their TOML value types
30    pub rule_schemas: std::collections::BTreeMap<String, toml::map::Map<String, toml::Value>>,
31    /// Map of rule name to config key aliases
32    pub rule_aliases: std::collections::BTreeMap<String, std::collections::HashMap<String, String>>,
33}
34
35impl RuleRegistry {
36    /// Build a registry from a list of rules
37    pub fn from_rules(rules: &[Box<dyn Rule>]) -> Self {
38        let mut rule_schemas = std::collections::BTreeMap::new();
39        let mut rule_aliases = std::collections::BTreeMap::new();
40
41        for rule in rules {
42            let norm_name = if let Some((name, toml::Value::Table(mut table))) = rule.config_schema() {
43                let norm_name = normalize_key(&name); // Normalize the name from config_schema
44                // Overwrite polymorphic keys with the sentinel so the validator skips
45                // type checking for fields whose deserializer accepts multiple TOML
46                // types. The clean default is preserved for `rumdl config --defaults`
47                // because that path calls `default_config_section()` directly.
48                for key in rule.polymorphic_config_keys() {
49                    table.insert(
50                        (*key).to_string(),
51                        crate::rule_config_serde::polymorphic_sentinel_value(),
52                    );
53                }
54                rule_schemas.insert(norm_name.clone(), table);
55                norm_name
56            } else {
57                let norm_name = normalize_key(rule.name()); // Normalize the name from rule.name()
58                rule_schemas.insert(norm_name.clone(), toml::map::Map::new());
59                norm_name
60            };
61
62            // Store aliases if the rule provides them
63            if let Some(aliases) = rule.config_aliases() {
64                rule_aliases.insert(norm_name, aliases);
65            }
66        }
67
68        RuleRegistry {
69            rule_schemas,
70            rule_aliases,
71        }
72    }
73
74    /// Get all known rule names
75    pub fn rule_names(&self) -> std::collections::BTreeSet<String> {
76        self.rule_schemas.keys().cloned().collect()
77    }
78
79    /// Get the valid configuration keys for a rule, including both original and normalized variants
80    pub fn config_keys_for(&self, rule: &str) -> Option<std::collections::BTreeSet<String>> {
81        self.rule_schemas.get(rule).map(|schema| {
82            let mut all_keys = std::collections::BTreeSet::new();
83
84            // Always allow 'severity' and 'enabled' for any rule
85            all_keys.insert("severity".to_string());
86            all_keys.insert("enabled".to_string());
87
88            // Add original keys from schema
89            for key in schema.keys() {
90                all_keys.insert(key.clone());
91            }
92
93            // Add normalized variants for markdownlint compatibility
94            for key in schema.keys() {
95                // Add kebab-case variant
96                all_keys.insert(key.replace('_', "-"));
97                // Add snake_case variant
98                all_keys.insert(key.replace('-', "_"));
99                // Add normalized variant
100                all_keys.insert(normalize_key(key));
101            }
102
103            // Add any aliases defined by the rule
104            if let Some(aliases) = self.rule_aliases.get(rule) {
105                for alias_key in aliases.keys() {
106                    all_keys.insert(alias_key.clone());
107                    // Also add normalized variants of the alias
108                    all_keys.insert(alias_key.replace('_', "-"));
109                    all_keys.insert(alias_key.replace('-', "_"));
110                    all_keys.insert(normalize_key(alias_key));
111                }
112            }
113
114            all_keys
115        })
116    }
117
118    /// Resolve a key as the user wrote it to the schema key it names, trying the rule's
119    /// aliases and the separator/case variants.
120    ///
121    /// Returns `None` when the rule does not accept the key at all. A key that resolves
122    /// may still carry a sentinel value, so this answers "is this key known?" where
123    /// [`RuleRegistry::expected_value_for`] answers "what type must it be?".
124    pub fn canonical_config_key(&self, rule: &str, key: &str) -> Option<&str> {
125        let schema = self.rule_schemas.get(rule)?;
126
127        // Check if this key is an alias
128        if let Some(aliases) = self.rule_aliases.get(rule)
129            && let Some(canonical_key) = aliases.get(key)
130            && let Some((schema_key, _)) = schema.get_key_value(canonical_key)
131        {
132            return Some(schema_key);
133        }
134
135        // Try the original key
136        if let Some((schema_key, _)) = schema.get_key_value(key) {
137            return Some(schema_key);
138        }
139
140        // Try key variants
141        let key_variants = [
142            key.replace('-', "_"), // Convert kebab-case to snake_case
143            key.replace('_', "-"), // Convert snake_case to kebab-case
144            normalize_key(key),    // Normalized key (lowercase, kebab-case)
145        ];
146
147        for variant in &key_variants {
148            if let Some((schema_key, _)) = schema.get_key_value(variant) {
149                return Some(schema_key);
150            }
151        }
152
153        None
154    }
155
156    /// Get the expected value type for a rule's configuration key, trying variants.
157    /// Returns `None` both for an unknown key and for sentinel values (nullable Option
158    /// fields, polymorphic fields that accept multiple TOML types), which signals the
159    /// caller to skip type checking while still recognizing the key as valid. Use
160    /// [`RuleRegistry::canonical_config_key`] to tell those two cases apart.
161    pub fn expected_value_for(&self, rule: &str, key: &str) -> Option<&toml::Value> {
162        let schema = self.rule_schemas.get(rule)?;
163        let canonical = self.canonical_config_key(rule, key)?;
164        filter_type_check_sentinels(schema.get(canonical)?)
165    }
166
167    /// Resolve any rule name (canonical or alias) to its canonical form
168    /// Returns None if the rule name is not recognized
169    ///
170    /// Resolution order:
171    /// 1. Direct canonical name match
172    /// 2. Static aliases (built-in markdownlint aliases)
173    pub fn resolve_rule_name(&self, name: &str) -> Option<String> {
174        // Try normalized canonical name first
175        let normalized = normalize_key(name);
176        if self.rule_schemas.contains_key(&normalized) {
177            return Some(normalized);
178        }
179
180        // Try static alias resolution (built-in markdownlint aliases)
181        resolve_rule_name_alias(name).map(std::string::ToString::to_string)
182    }
183}
184
185/// Returns `None` if the value is a sentinel that signals "skip type check"
186/// (nullable Option fields, polymorphic fields that accept multiple types).
187/// Otherwise returns `Some(value)` so the validator can compare types.
188fn filter_type_check_sentinels(value: &toml::Value) -> Option<&toml::Value> {
189    if crate::rule_config_serde::is_nullable_sentinel(value) || crate::rule_config_serde::is_polymorphic_sentinel(value)
190    {
191        None
192    } else {
193        Some(value)
194    }
195}
196
197/// A read-only string map looked up by binary search.
198///
199/// The rule-name tables below are fixed at compile time and read on every config
200/// load, so they want a lookup with no build step and no hashing: at these sizes
201/// a binary search is a handful of comparisons over data the linker places in
202/// `.rodata`. Entries may be a literal slice or a projection of the rule
203/// catalog; keeping either source sorted is the caller's job, which tests pin.
204pub struct StaticMap {
205    source: StaticMapSource,
206}
207
208#[derive(Clone, Copy)]
209enum StaticMapSource {
210    Entries(&'static [(&'static str, &'static str)]),
211    RulePrimaryAliases,
212}
213
214struct StaticMapEntries {
215    source: StaticMapSource,
216    index: usize,
217}
218
219impl Iterator for StaticMapEntries {
220    type Item = (&'static str, &'static str);
221
222    fn next(&mut self) -> Option<Self::Item> {
223        let entry = match self.source {
224            StaticMapSource::Entries(entries) => entries.get(self.index).copied(),
225            StaticMapSource::RulePrimaryAliases => crate::rules::rule_identity(self.index),
226        };
227        self.index += usize::from(entry.is_some());
228        entry
229    }
230}
231
232impl StaticMap {
233    const fn new(entries: &'static [(&'static str, &'static str)]) -> Self {
234        Self {
235            source: StaticMapSource::Entries(entries),
236        }
237    }
238
239    const fn rule_primary_aliases() -> Self {
240        Self {
241            source: StaticMapSource::RulePrimaryAliases,
242        }
243    }
244
245    /// The value for `key`, or `None` if the map has no such key.
246    pub fn get(&self, key: &str) -> Option<&'static str> {
247        match self.source {
248            StaticMapSource::Entries(entries) => entries
249                .binary_search_by_key(&key, |(entry_key, _)| entry_key)
250                .ok()
251                .map(|index| entries[index].1),
252            StaticMapSource::RulePrimaryAliases => crate::rules::primary_alias(key),
253        }
254    }
255
256    /// Every key, in sorted order.
257    pub fn keys(&self) -> impl Iterator<Item = &'static str> {
258        self.entries().map(|(key, _)| key)
259    }
260
261    /// Every key/value pair, in sorted order.
262    pub fn entries(&self) -> impl Iterator<Item = (&'static str, &'static str)> {
263        StaticMapEntries {
264            source: self.source,
265            index: 0,
266        }
267    }
268
269    /// Whether the backing array is sorted by key, the invariant [`get`](Self::get) needs.
270    ///
271    /// Nothing at runtime can act on the answer, so this exists for the tests that
272    /// hold the tables to the order they are written in.
273    #[cfg(test)]
274    fn is_sorted_by_key(&self) -> bool {
275        self.entries()
276            .map(|(key, _)| key)
277            .try_fold(None, |previous, key| match previous {
278                Some(previous) if previous >= key => Err(()),
279                _ => Ok(Some(key)),
280            })
281            .is_ok()
282    }
283}
284
285/// Every spelling rumdl accepts for a rule, mapped to its canonical ID.
286///
287/// Keys are the normalized form [`resolve_rule_name_alias`] produces: uppercase
288/// with hyphens. Sorted, because [`StaticMap`] binary-searches it; the
289/// `rule_alias_map_is_sorted` test holds new entries to that.
290pub static RULE_ALIAS_MAP: StaticMap = StaticMap::new(&[
291    ("BLANK-LINE-AFTER-FRONTMATTER", "MD071"),
292    ("BLANKS-AROUND-FENCES", "MD031"),
293    ("BLANKS-AROUND-HEADINGS", "MD022"),
294    ("BLANKS-AROUND-HORIZONTAL-RULES", "MD065"),
295    ("BLANKS-AROUND-LISTS", "MD032"),
296    ("BLANKS-AROUND-TABLES", "MD058"),
297    ("CHUNK-LABEL-SPACES", "MD079"),
298    ("CJK-SPACING", "MD089"),
299    ("CODE-BLOCK-STYLE", "MD046"),
300    ("CODE-FENCE-STYLE", "MD048"),
301    ("COMMANDS-SHOW-OUTPUT", "MD014"),
302    ("DESCRIPTIVE-LINK-TEXT", "MD059"),
303    ("EMPHASIS-STYLE", "MD049"),
304    ("EMPTY-FOOTNOTE-DEFINITION", "MD068"),
305    ("EXISTING-RELATIVE-LINKS", "MD057"),
306    ("FENCED-CODE-LANGUAGE", "MD040"),
307    ("FIRST-LINE-H1", "MD041"),
308    ("FIRST-LINE-HEADING", "MD041"),
309    ("FOOTNOTE-DEFINITION-ORDER", "MD067"),
310    ("FOOTNOTE-VALIDATION", "MD066"),
311    ("FORBIDDEN-TERMS", "MD061"),
312    ("FRONTMATTER-KEY-SORT", "MD072"),
313    ("HEADING-ANCHOR-COLLISION", "MD080"),
314    ("HEADING-CAPITALIZATION", "MD063"),
315    ("HEADING-INCREMENT", "MD001"),
316    ("HEADING-START-LEFT", "MD023"),
317    ("HEADING-STYLE", "MD003"),
318    ("HR-STYLE", "MD035"),
319    ("INVALID-ENCODING", "MD094"),
320    ("INVISIBLE-CHARACTERS", "MD084"),
321    ("LINE-LENGTH", "MD013"),
322    ("LINK-DESTINATION-WHITESPACE", "MD062"),
323    ("LINK-FRAGMENTS", "MD051"),
324    ("LINK-IMAGE-REFERENCE-DEFINITIONS", "MD053"),
325    ("LINK-IMAGE-STYLE", "MD054"),
326    ("LIST-CONTINUATION-INDENT", "MD077"),
327    ("LIST-INDENT", "MD005"),
328    ("LIST-ITEM-SPACING", "MD076"),
329    ("LIST-MARKER-SPACE", "MD030"),
330    ("MD001", "MD001"),
331    ("MD003", "MD003"),
332    ("MD004", "MD004"),
333    ("MD005", "MD005"),
334    ("MD007", "MD007"),
335    ("MD009", "MD009"),
336    ("MD010", "MD010"),
337    ("MD011", "MD011"),
338    ("MD012", "MD012"),
339    ("MD013", "MD013"),
340    ("MD014", "MD014"),
341    ("MD018", "MD018"),
342    ("MD019", "MD019"),
343    ("MD020", "MD020"),
344    ("MD021", "MD021"),
345    ("MD022", "MD022"),
346    ("MD023", "MD023"),
347    ("MD024", "MD024"),
348    ("MD025", "MD025"),
349    ("MD026", "MD026"),
350    ("MD027", "MD027"),
351    ("MD028", "MD028"),
352    ("MD029", "MD029"),
353    ("MD030", "MD030"),
354    ("MD031", "MD031"),
355    ("MD032", "MD032"),
356    ("MD033", "MD033"),
357    ("MD034", "MD034"),
358    ("MD035", "MD035"),
359    ("MD036", "MD036"),
360    ("MD037", "MD037"),
361    ("MD038", "MD038"),
362    ("MD039", "MD039"),
363    ("MD040", "MD040"),
364    ("MD041", "MD041"),
365    ("MD042", "MD042"),
366    ("MD043", "MD043"),
367    ("MD044", "MD044"),
368    ("MD045", "MD045"),
369    ("MD046", "MD046"),
370    ("MD047", "MD047"),
371    ("MD048", "MD048"),
372    ("MD049", "MD049"),
373    ("MD050", "MD050"),
374    ("MD051", "MD051"),
375    ("MD052", "MD052"),
376    ("MD053", "MD053"),
377    ("MD054", "MD054"),
378    ("MD055", "MD055"),
379    ("MD056", "MD056"),
380    ("MD057", "MD057"),
381    ("MD058", "MD058"),
382    ("MD059", "MD059"),
383    ("MD060", "MD060"),
384    ("MD061", "MD061"),
385    ("MD062", "MD062"),
386    ("MD063", "MD063"),
387    ("MD064", "MD064"),
388    ("MD065", "MD065"),
389    ("MD066", "MD066"),
390    ("MD067", "MD067"),
391    ("MD068", "MD068"),
392    ("MD069", "MD069"),
393    ("MD070", "MD070"),
394    ("MD071", "MD071"),
395    ("MD072", "MD072"),
396    ("MD073", "MD073"),
397    ("MD074", "MD074"),
398    ("MD075", "MD075"),
399    ("MD076", "MD076"),
400    ("MD077", "MD077"),
401    ("MD078", "MD078"),
402    ("MD079", "MD079"),
403    ("MD080", "MD080"),
404    ("MD081", "MD081"),
405    ("MD082", "MD082"),
406    ("MD083", "MD083"),
407    ("MD084", "MD084"),
408    ("MD085", "MD085"),
409    ("MD086", "MD086"),
410    ("MD087", "MD087"),
411    ("MD088", "MD088"),
412    ("MD089", "MD089"),
413    ("MD090", "MD090"),
414    ("MD091", "MD091"),
415    ("MD092", "MD092"),
416    ("MD093", "MD093"),
417    ("MD094", "MD094"),
418    ("MERGE-CONFLICT", "MD092"),
419    ("MISSING-CHUNK-LABELS", "MD078"),
420    ("MKDOCS-NAV", "MD074"),
421    ("MOJIBAKE", "MD083"),
422    ("NESTED-CODE-FENCE", "MD070"),
423    ("NO-ALT-TEXT", "MD045"),
424    ("NO-BARE-URLS", "MD034"),
425    ("NO-BLANKS-BLOCKQUOTE", "MD028"),
426    ("NO-DUPLICATE-HEADING", "MD024"),
427    ("NO-DUPLICATE-LIST-MARKERS", "MD069"),
428    ("NO-EMPHASIS-AS-HEADING", "MD036"),
429    ("NO-EMPTY-LINKS", "MD042"),
430    ("NO-EMPTY-SECTIONS", "MD082"),
431    ("NO-EXCESSIVE-EMPHASIS", "MD081"),
432    ("NO-FORMATTING-IN-HEADINGS", "MD093"),
433    ("NO-HARD-TABS", "MD010"),
434    ("NO-HR-BEFORE-HEADING", "MD090"),
435    ("NO-INLINE-HTML", "MD033"),
436    ("NO-MARKDOWN-IN-HTML", "MD091"),
437    ("NO-MISSING-SPACE-ATX", "MD018"),
438    ("NO-MISSING-SPACE-CLOSED-ATX", "MD020"),
439    ("NO-MULTIPLE-BLANKS", "MD012"),
440    ("NO-MULTIPLE-CONSECUTIVE-SPACES", "MD064"),
441    ("NO-MULTIPLE-SPACE-ATX", "MD019"),
442    ("NO-MULTIPLE-SPACE-BLOCKQUOTE", "MD027"),
443    ("NO-MULTIPLE-SPACE-CLOSED-ATX", "MD021"),
444    ("NO-REVERSED-LINKS", "MD011"),
445    ("NO-SPACE-IN-CODE", "MD038"),
446    ("NO-SPACE-IN-EMPHASIS", "MD037"),
447    ("NO-SPACE-IN-LINK-DESTINATION", "MD062"),
448    ("NO-SPACE-IN-LINKS", "MD039"),
449    ("NO-TRAILING-PUNCTUATION", "MD026"),
450    ("NO-TRAILING-SPACES", "MD009"),
451    ("NO-UNCLOSED-COMMENTS", "MD086"),
452    ("OL-PREFIX", "MD029"),
453    ("ORPHANED-TABLE-ROWS", "MD075"),
454    ("PARAGRAPH-CONTINUATION-INDENT", "MD085"),
455    ("PROPER-NAMES", "MD044"),
456    ("QUOTES-DASHES", "MD088"),
457    ("REFERENCE-LINKS-IMAGES", "MD052"),
458    ("REQUIRED-HEADINGS", "MD043"),
459    ("SINGLE-H1", "MD025"),
460    ("SINGLE-TITLE", "MD025"),
461    ("SINGLE-TRAILING-NEWLINE", "MD047"),
462    ("STRONG-STYLE", "MD050"),
463    ("TABLE-CELL-ALIGNMENT", "MD060"),
464    ("TABLE-COLUMN-COUNT", "MD056"),
465    ("TABLE-FORMAT", "MD060"),
466    ("TABLE-PIPE-STYLE", "MD055"),
467    ("TOC-VALIDATION", "MD073"),
468    ("UL-INDENT", "MD007"),
469    ("UL-STYLE", "MD004"),
470    ("UNUSED-DISABLE-COMMENT", "MD087"),
471]);
472
473/// The name rumdl uses when it writes a rule name itself, one per rule.
474///
475/// A rule can answer to several aliases, so the readable name it is given in
476/// generated output (a disable comment written by the language server, the name
477/// `rumdl rule` reports) has to be chosen rather than derived. The choice is the
478/// alias each rule's documentation lists first.
479///
480/// Read-only compatibility view over primary aliases owned by the rule catalog.
481/// The primary readable alias for each canonical rule ID. The public type stays
482/// `StaticMap`; its entries are projected directly from the sorted rule catalog.
483pub static RULE_PRIMARY_ALIAS: StaticMap = StaticMap::rule_primary_aliases();
484pub fn primary_alias(rule_id: &str) -> Option<&'static str> {
485    RULE_PRIMARY_ALIAS.get(rule_id)
486}
487
488/// Resolve a rule name alias to its canonical form
489/// Converts rule aliases (like "ul-style", "line-length") to canonical IDs (like "MD004", "MD013")
490/// Returns None if the rule name is not recognized
491pub fn resolve_rule_name_alias(key: &str) -> Option<&'static str> {
492    // Normalize: uppercase and replace underscores with hyphens
493    let normalized_key = key.to_ascii_uppercase().replace('_', "-");
494
495    RULE_ALIAS_MAP.get(normalized_key.as_str())
496}
497
498/// Resolves a rule name to its canonical ID, supporting both rule IDs and aliases.
499/// Returns the canonical ID (e.g., "MD001") for any valid input:
500/// - "MD001" → "MD001" (canonical)
501/// - "heading-increment" → "MD001" (alias)
502/// - "HEADING_INCREMENT" → "MD001" (case-insensitive, underscore variant)
503///
504/// For unknown names, falls back to normalization (uppercase for MDxxx pattern, otherwise kebab-case).
505pub fn resolve_rule_name(name: &str) -> String {
506    resolve_rule_name_alias(name).map_or_else(|| normalize_key(name), std::string::ToString::to_string)
507}
508
509/// Resolves a comma-separated list of rule names to canonical IDs.
510/// Handles CLI input like "MD001,line-length,heading-increment".
511/// Empty entries and whitespace are filtered out.
512pub fn resolve_rule_names(input: &str) -> std::collections::HashSet<String> {
513    input
514        .split(',')
515        .map(str::trim)
516        .filter(|s| !s.is_empty())
517        .map(resolve_rule_name)
518        .collect()
519}
520
521/// Checks if a rule name (or alias) is valid.
522/// Returns true if the name resolves to a known rule.
523/// Handles the special "all" value and all aliases.
524pub fn is_valid_rule_name(name: &str) -> bool {
525    // Check for special "all" value (case-insensitive)
526    if name.eq_ignore_ascii_case("all") {
527        return true;
528    }
529    resolve_rule_name_alias(name).is_some()
530}
531
532/// Canonicalizes a rule-name list in place: every entry is rewritten to its canonical
533/// rule ID via [`resolve_rule_name`], duplicates are removed (keeping first occurrence),
534/// and the special `"all"` keyword is preserved as-is (case-insensitive).
535///
536/// This enforces the runtime invariant that rule lists in `Config` (`enable`, `disable`,
537/// `extend_enable`, `extend_disable`, `fixable`, `unfixable`, and per-file ignore values)
538/// always contain canonical rule IDs. Consumers can therefore compare against
539/// `rule.name()` with simple string equality without needing alias resolution at every
540/// call site.
541///
542/// The operation is idempotent: running it twice produces the same result as once.
543pub fn canonicalize_rule_list_in_place(list: &mut Vec<String>) {
544    if list.is_empty() {
545        return;
546    }
547    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::with_capacity(list.len());
548    let mut out: Vec<String> = Vec::with_capacity(list.len());
549    for entry in list.drain(..) {
550        let canonical = if entry.eq_ignore_ascii_case("all") {
551            "all".to_string()
552        } else {
553            resolve_rule_name(&entry)
554        };
555        if seen.insert(canonical.clone()) {
556            out.push(canonical);
557        }
558    }
559    *list = out;
560}
561
562#[cfg(test)]
563mod primary_alias_tests {
564    use super::{RULE_ALIAS_MAP, RULE_PRIMARY_ALIAS, default_registry, primary_alias, resolve_rule_name_alias};
565
566    /// Every rule ID the alias map knows, paired with the aliases it answers to.
567    fn aliases_by_rule() -> std::collections::BTreeMap<&'static str, Vec<&'static str>> {
568        let mut by_rule: std::collections::BTreeMap<&'static str, Vec<&'static str>> =
569            std::collections::BTreeMap::new();
570        for (alias, rule_id) in RULE_ALIAS_MAP.entries() {
571            let entry = by_rule.entry(rule_id).or_default();
572            if alias != rule_id {
573                entry.push(alias);
574            }
575        }
576        by_rule
577    }
578
579    /// A lookup answers correctly only while the array it binary-searches is sorted,
580    /// and an out-of-order entry silently becomes unreachable rather than failing to
581    /// compile, so the order is asserted rather than assumed.
582    #[test]
583    fn the_rule_name_tables_are_sorted_by_key() {
584        assert!(RULE_ALIAS_MAP.is_sorted_by_key(), "RULE_ALIAS_MAP is out of order");
585        assert!(
586            RULE_PRIMARY_ALIAS.is_sorted_by_key(),
587            "RULE_PRIMARY_ALIAS is out of order"
588        );
589    }
590
591    /// The control for the test above: every key the tables hold is reachable, which
592    /// is what sortedness buys and what an unsorted table would quietly break.
593    #[test]
594    fn every_key_in_the_rule_name_tables_is_reachable() {
595        for (key, value) in RULE_ALIAS_MAP.entries() {
596            assert_eq!(RULE_ALIAS_MAP.get(key), Some(value), "RULE_ALIAS_MAP lost '{key}'");
597        }
598        for (key, value) in RULE_PRIMARY_ALIAS.entries() {
599            assert_eq!(
600                RULE_PRIMARY_ALIAS.get(key),
601                Some(value),
602                "RULE_PRIMARY_ALIAS lost '{key}'"
603            );
604        }
605        assert_eq!(
606            RULE_ALIAS_MAP.get("NOT-A-RULE"),
607            None,
608            "control: a name the table does not hold answers None"
609        );
610    }
611
612    #[test]
613    fn every_rule_has_a_readable_name() {
614        let rule_ids = default_registry().rule_names();
615        assert!(
616            rule_ids.contains("MD013"),
617            "control: the registry lists rules by canonical ID, got {rule_ids:?}"
618        );
619        let missing: Vec<_> = rule_ids
620            .into_iter()
621            .filter(|rule_id| primary_alias(rule_id).is_none())
622            .collect();
623        assert!(
624            missing.is_empty(),
625            "these rules have no entry in RULE_PRIMARY_ALIAS: {missing:?}"
626        );
627    }
628
629    #[test]
630    fn a_readable_name_is_one_of_the_rules_own_aliases() {
631        let by_rule = aliases_by_rule();
632        for (rule_id, primary) in RULE_PRIMARY_ALIAS.entries() {
633            let aliases = by_rule
634                .get(rule_id)
635                .unwrap_or_else(|| panic!("{rule_id} has a readable name but is not in RULE_ALIAS_MAP"));
636            assert!(
637                aliases.iter().any(|alias| alias.eq_ignore_ascii_case(primary)),
638                "{rule_id}'s readable name '{primary}' is not one of its aliases {aliases:?}"
639            );
640        }
641    }
642
643    #[test]
644    fn a_readable_name_resolves_back_to_its_rule() {
645        for (rule_id, primary) in RULE_PRIMARY_ALIAS.entries() {
646            assert_eq!(
647                resolve_rule_name_alias(primary),
648                Some(rule_id),
649                "'{primary}' must be usable anywhere a rule name is accepted"
650            );
651        }
652    }
653
654    #[test]
655    fn a_name_that_is_not_a_rule_id_has_no_readable_name() {
656        // Control: the lookup takes canonical IDs, so an alias or a typo answers None
657        // rather than something plausible.
658        assert_eq!(primary_alias("MD013"), Some("line-length"));
659        assert_eq!(primary_alias("line-length"), None);
660        assert_eq!(primary_alias("MD999"), None);
661    }
662}
663
664#[cfg(test)]
665mod canonicalize_tests {
666    use super::canonicalize_rule_list_in_place;
667
668    #[test]
669    fn rewrites_aliases_to_canonical_ids() {
670        let mut list = vec!["no-inline-html".to_string(), "line-length".to_string()];
671        canonicalize_rule_list_in_place(&mut list);
672        assert_eq!(list, vec!["MD033".to_string(), "MD013".to_string()]);
673    }
674
675    #[test]
676    fn dedupes_alias_and_canonical_preserving_order() {
677        let mut list = vec!["MD033".to_string(), "no-inline-html".to_string(), "MD013".to_string()];
678        canonicalize_rule_list_in_place(&mut list);
679        assert_eq!(list, vec!["MD033".to_string(), "MD013".to_string()]);
680    }
681
682    #[test]
683    fn preserves_all_keyword_normalized() {
684        let mut list = vec!["ALL".to_string(), "MD013".to_string()];
685        canonicalize_rule_list_in_place(&mut list);
686        assert_eq!(list, vec!["all".to_string(), "MD013".to_string()]);
687    }
688
689    #[test]
690    fn is_idempotent() {
691        let mut list = vec!["no-inline-html".to_string(), "MD013".to_string()];
692        canonicalize_rule_list_in_place(&mut list);
693        let once = list.clone();
694        canonicalize_rule_list_in_place(&mut list);
695        assert_eq!(list, once);
696    }
697
698    #[test]
699    fn handles_empty_and_unknown_inputs() {
700        let mut empty: Vec<String> = Vec::new();
701        canonicalize_rule_list_in_place(&mut empty);
702        assert!(empty.is_empty());
703
704        let mut unknown = vec!["custom-rule".to_string(), "Custom-Rule".to_string()];
705        canonicalize_rule_list_in_place(&mut unknown);
706        // Both normalize to the same kebab-case form, so they dedupe.
707        assert_eq!(unknown, vec!["custom-rule".to_string()]);
708    }
709}