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    ("INVISIBLE-CHARACTERS", "MD084"),
320    ("LINE-LENGTH", "MD013"),
321    ("LINK-DESTINATION-WHITESPACE", "MD062"),
322    ("LINK-FRAGMENTS", "MD051"),
323    ("LINK-IMAGE-REFERENCE-DEFINITIONS", "MD053"),
324    ("LINK-IMAGE-STYLE", "MD054"),
325    ("LIST-CONTINUATION-INDENT", "MD077"),
326    ("LIST-INDENT", "MD005"),
327    ("LIST-ITEM-SPACING", "MD076"),
328    ("LIST-MARKER-SPACE", "MD030"),
329    ("MD001", "MD001"),
330    ("MD003", "MD003"),
331    ("MD004", "MD004"),
332    ("MD005", "MD005"),
333    ("MD007", "MD007"),
334    ("MD009", "MD009"),
335    ("MD010", "MD010"),
336    ("MD011", "MD011"),
337    ("MD012", "MD012"),
338    ("MD013", "MD013"),
339    ("MD014", "MD014"),
340    ("MD018", "MD018"),
341    ("MD019", "MD019"),
342    ("MD020", "MD020"),
343    ("MD021", "MD021"),
344    ("MD022", "MD022"),
345    ("MD023", "MD023"),
346    ("MD024", "MD024"),
347    ("MD025", "MD025"),
348    ("MD026", "MD026"),
349    ("MD027", "MD027"),
350    ("MD028", "MD028"),
351    ("MD029", "MD029"),
352    ("MD030", "MD030"),
353    ("MD031", "MD031"),
354    ("MD032", "MD032"),
355    ("MD033", "MD033"),
356    ("MD034", "MD034"),
357    ("MD035", "MD035"),
358    ("MD036", "MD036"),
359    ("MD037", "MD037"),
360    ("MD038", "MD038"),
361    ("MD039", "MD039"),
362    ("MD040", "MD040"),
363    ("MD041", "MD041"),
364    ("MD042", "MD042"),
365    ("MD043", "MD043"),
366    ("MD044", "MD044"),
367    ("MD045", "MD045"),
368    ("MD046", "MD046"),
369    ("MD047", "MD047"),
370    ("MD048", "MD048"),
371    ("MD049", "MD049"),
372    ("MD050", "MD050"),
373    ("MD051", "MD051"),
374    ("MD052", "MD052"),
375    ("MD053", "MD053"),
376    ("MD054", "MD054"),
377    ("MD055", "MD055"),
378    ("MD056", "MD056"),
379    ("MD057", "MD057"),
380    ("MD058", "MD058"),
381    ("MD059", "MD059"),
382    ("MD060", "MD060"),
383    ("MD061", "MD061"),
384    ("MD062", "MD062"),
385    ("MD063", "MD063"),
386    ("MD064", "MD064"),
387    ("MD065", "MD065"),
388    ("MD066", "MD066"),
389    ("MD067", "MD067"),
390    ("MD068", "MD068"),
391    ("MD069", "MD069"),
392    ("MD070", "MD070"),
393    ("MD071", "MD071"),
394    ("MD072", "MD072"),
395    ("MD073", "MD073"),
396    ("MD074", "MD074"),
397    ("MD075", "MD075"),
398    ("MD076", "MD076"),
399    ("MD077", "MD077"),
400    ("MD078", "MD078"),
401    ("MD079", "MD079"),
402    ("MD080", "MD080"),
403    ("MD081", "MD081"),
404    ("MD082", "MD082"),
405    ("MD083", "MD083"),
406    ("MD084", "MD084"),
407    ("MD085", "MD085"),
408    ("MD086", "MD086"),
409    ("MD087", "MD087"),
410    ("MD088", "MD088"),
411    ("MD089", "MD089"),
412    ("MISSING-CHUNK-LABELS", "MD078"),
413    ("MKDOCS-NAV", "MD074"),
414    ("MOJIBAKE", "MD083"),
415    ("NESTED-CODE-FENCE", "MD070"),
416    ("NO-ALT-TEXT", "MD045"),
417    ("NO-BARE-URLS", "MD034"),
418    ("NO-BLANKS-BLOCKQUOTE", "MD028"),
419    ("NO-DUPLICATE-HEADING", "MD024"),
420    ("NO-DUPLICATE-LIST-MARKERS", "MD069"),
421    ("NO-EMPHASIS-AS-HEADING", "MD036"),
422    ("NO-EMPTY-LINKS", "MD042"),
423    ("NO-EMPTY-SECTIONS", "MD082"),
424    ("NO-EXCESSIVE-EMPHASIS", "MD081"),
425    ("NO-HARD-TABS", "MD010"),
426    ("NO-INLINE-HTML", "MD033"),
427    ("NO-MISSING-SPACE-ATX", "MD018"),
428    ("NO-MISSING-SPACE-CLOSED-ATX", "MD020"),
429    ("NO-MULTIPLE-BLANKS", "MD012"),
430    ("NO-MULTIPLE-CONSECUTIVE-SPACES", "MD064"),
431    ("NO-MULTIPLE-SPACE-ATX", "MD019"),
432    ("NO-MULTIPLE-SPACE-BLOCKQUOTE", "MD027"),
433    ("NO-MULTIPLE-SPACE-CLOSED-ATX", "MD021"),
434    ("NO-REVERSED-LINKS", "MD011"),
435    ("NO-SPACE-IN-CODE", "MD038"),
436    ("NO-SPACE-IN-EMPHASIS", "MD037"),
437    ("NO-SPACE-IN-LINK-DESTINATION", "MD062"),
438    ("NO-SPACE-IN-LINKS", "MD039"),
439    ("NO-TRAILING-PUNCTUATION", "MD026"),
440    ("NO-TRAILING-SPACES", "MD009"),
441    ("NO-UNCLOSED-COMMENTS", "MD086"),
442    ("OL-PREFIX", "MD029"),
443    ("ORPHANED-TABLE-ROWS", "MD075"),
444    ("PARAGRAPH-CONTINUATION-INDENT", "MD085"),
445    ("PROPER-NAMES", "MD044"),
446    ("QUOTES-DASHES", "MD088"),
447    ("REFERENCE-LINKS-IMAGES", "MD052"),
448    ("REQUIRED-HEADINGS", "MD043"),
449    ("SINGLE-H1", "MD025"),
450    ("SINGLE-TITLE", "MD025"),
451    ("SINGLE-TRAILING-NEWLINE", "MD047"),
452    ("STRONG-STYLE", "MD050"),
453    ("TABLE-CELL-ALIGNMENT", "MD060"),
454    ("TABLE-COLUMN-COUNT", "MD056"),
455    ("TABLE-FORMAT", "MD060"),
456    ("TABLE-PIPE-STYLE", "MD055"),
457    ("TOC-VALIDATION", "MD073"),
458    ("UL-INDENT", "MD007"),
459    ("UL-STYLE", "MD004"),
460    ("UNUSED-DISABLE-COMMENT", "MD087"),
461]);
462
463/// The name rumdl uses when it writes a rule name itself, one per rule.
464///
465/// A rule can answer to several aliases, so the readable name it is given in
466/// generated output (a disable comment written by the language server, the name
467/// `rumdl rule` reports) has to be chosen rather than derived. The choice is the
468/// alias each rule's documentation lists first.
469///
470/// Read-only compatibility view over primary aliases owned by the rule catalog.
471/// The primary readable alias for each canonical rule ID. The public type stays
472/// `StaticMap`; its entries are projected directly from the sorted rule catalog.
473pub static RULE_PRIMARY_ALIAS: StaticMap = StaticMap::rule_primary_aliases();
474pub fn primary_alias(rule_id: &str) -> Option<&'static str> {
475    RULE_PRIMARY_ALIAS.get(rule_id)
476}
477
478/// Resolve a rule name alias to its canonical form
479/// Converts rule aliases (like "ul-style", "line-length") to canonical IDs (like "MD004", "MD013")
480/// Returns None if the rule name is not recognized
481pub fn resolve_rule_name_alias(key: &str) -> Option<&'static str> {
482    // Normalize: uppercase and replace underscores with hyphens
483    let normalized_key = key.to_ascii_uppercase().replace('_', "-");
484
485    RULE_ALIAS_MAP.get(normalized_key.as_str())
486}
487
488/// Resolves a rule name to its canonical ID, supporting both rule IDs and aliases.
489/// Returns the canonical ID (e.g., "MD001") for any valid input:
490/// - "MD001" → "MD001" (canonical)
491/// - "heading-increment" → "MD001" (alias)
492/// - "HEADING_INCREMENT" → "MD001" (case-insensitive, underscore variant)
493///
494/// For unknown names, falls back to normalization (uppercase for MDxxx pattern, otherwise kebab-case).
495pub fn resolve_rule_name(name: &str) -> String {
496    resolve_rule_name_alias(name).map_or_else(|| normalize_key(name), std::string::ToString::to_string)
497}
498
499/// Resolves a comma-separated list of rule names to canonical IDs.
500/// Handles CLI input like "MD001,line-length,heading-increment".
501/// Empty entries and whitespace are filtered out.
502pub fn resolve_rule_names(input: &str) -> std::collections::HashSet<String> {
503    input
504        .split(',')
505        .map(str::trim)
506        .filter(|s| !s.is_empty())
507        .map(resolve_rule_name)
508        .collect()
509}
510
511/// Checks if a rule name (or alias) is valid.
512/// Returns true if the name resolves to a known rule.
513/// Handles the special "all" value and all aliases.
514pub fn is_valid_rule_name(name: &str) -> bool {
515    // Check for special "all" value (case-insensitive)
516    if name.eq_ignore_ascii_case("all") {
517        return true;
518    }
519    resolve_rule_name_alias(name).is_some()
520}
521
522/// Canonicalizes a rule-name list in place: every entry is rewritten to its canonical
523/// rule ID via [`resolve_rule_name`], duplicates are removed (keeping first occurrence),
524/// and the special `"all"` keyword is preserved as-is (case-insensitive).
525///
526/// This enforces the runtime invariant that rule lists in `Config` (`enable`, `disable`,
527/// `extend_enable`, `extend_disable`, `fixable`, `unfixable`, and per-file ignore values)
528/// always contain canonical rule IDs. Consumers can therefore compare against
529/// `rule.name()` with simple string equality without needing alias resolution at every
530/// call site.
531///
532/// The operation is idempotent: running it twice produces the same result as once.
533pub fn canonicalize_rule_list_in_place(list: &mut Vec<String>) {
534    if list.is_empty() {
535        return;
536    }
537    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::with_capacity(list.len());
538    let mut out: Vec<String> = Vec::with_capacity(list.len());
539    for entry in list.drain(..) {
540        let canonical = if entry.eq_ignore_ascii_case("all") {
541            "all".to_string()
542        } else {
543            resolve_rule_name(&entry)
544        };
545        if seen.insert(canonical.clone()) {
546            out.push(canonical);
547        }
548    }
549    *list = out;
550}
551
552#[cfg(test)]
553mod primary_alias_tests {
554    use super::{RULE_ALIAS_MAP, RULE_PRIMARY_ALIAS, default_registry, primary_alias, resolve_rule_name_alias};
555
556    /// Every rule ID the alias map knows, paired with the aliases it answers to.
557    fn aliases_by_rule() -> std::collections::BTreeMap<&'static str, Vec<&'static str>> {
558        let mut by_rule: std::collections::BTreeMap<&'static str, Vec<&'static str>> =
559            std::collections::BTreeMap::new();
560        for (alias, rule_id) in RULE_ALIAS_MAP.entries() {
561            let entry = by_rule.entry(rule_id).or_default();
562            if alias != rule_id {
563                entry.push(alias);
564            }
565        }
566        by_rule
567    }
568
569    /// A lookup answers correctly only while the array it binary-searches is sorted,
570    /// and an out-of-order entry silently becomes unreachable rather than failing to
571    /// compile, so the order is asserted rather than assumed.
572    #[test]
573    fn the_rule_name_tables_are_sorted_by_key() {
574        assert!(RULE_ALIAS_MAP.is_sorted_by_key(), "RULE_ALIAS_MAP is out of order");
575        assert!(
576            RULE_PRIMARY_ALIAS.is_sorted_by_key(),
577            "RULE_PRIMARY_ALIAS is out of order"
578        );
579    }
580
581    /// The control for the test above: every key the tables hold is reachable, which
582    /// is what sortedness buys and what an unsorted table would quietly break.
583    #[test]
584    fn every_key_in_the_rule_name_tables_is_reachable() {
585        for (key, value) in RULE_ALIAS_MAP.entries() {
586            assert_eq!(RULE_ALIAS_MAP.get(key), Some(value), "RULE_ALIAS_MAP lost '{key}'");
587        }
588        for (key, value) in RULE_PRIMARY_ALIAS.entries() {
589            assert_eq!(
590                RULE_PRIMARY_ALIAS.get(key),
591                Some(value),
592                "RULE_PRIMARY_ALIAS lost '{key}'"
593            );
594        }
595        assert_eq!(
596            RULE_ALIAS_MAP.get("NOT-A-RULE"),
597            None,
598            "control: a name the table does not hold answers None"
599        );
600    }
601
602    #[test]
603    fn every_rule_has_a_readable_name() {
604        let rule_ids = default_registry().rule_names();
605        assert!(
606            rule_ids.contains("MD013"),
607            "control: the registry lists rules by canonical ID, got {rule_ids:?}"
608        );
609        let missing: Vec<_> = rule_ids
610            .into_iter()
611            .filter(|rule_id| primary_alias(rule_id).is_none())
612            .collect();
613        assert!(
614            missing.is_empty(),
615            "these rules have no entry in RULE_PRIMARY_ALIAS: {missing:?}"
616        );
617    }
618
619    #[test]
620    fn a_readable_name_is_one_of_the_rules_own_aliases() {
621        let by_rule = aliases_by_rule();
622        for (rule_id, primary) in RULE_PRIMARY_ALIAS.entries() {
623            let aliases = by_rule
624                .get(rule_id)
625                .unwrap_or_else(|| panic!("{rule_id} has a readable name but is not in RULE_ALIAS_MAP"));
626            assert!(
627                aliases.iter().any(|alias| alias.eq_ignore_ascii_case(primary)),
628                "{rule_id}'s readable name '{primary}' is not one of its aliases {aliases:?}"
629            );
630        }
631    }
632
633    #[test]
634    fn a_readable_name_resolves_back_to_its_rule() {
635        for (rule_id, primary) in RULE_PRIMARY_ALIAS.entries() {
636            assert_eq!(
637                resolve_rule_name_alias(primary),
638                Some(rule_id),
639                "'{primary}' must be usable anywhere a rule name is accepted"
640            );
641        }
642    }
643
644    #[test]
645    fn a_name_that_is_not_a_rule_id_has_no_readable_name() {
646        // Control: the lookup takes canonical IDs, so an alias or a typo answers None
647        // rather than something plausible.
648        assert_eq!(primary_alias("MD013"), Some("line-length"));
649        assert_eq!(primary_alias("line-length"), None);
650        assert_eq!(primary_alias("MD999"), None);
651    }
652}
653
654#[cfg(test)]
655mod canonicalize_tests {
656    use super::canonicalize_rule_list_in_place;
657
658    #[test]
659    fn rewrites_aliases_to_canonical_ids() {
660        let mut list = vec!["no-inline-html".to_string(), "line-length".to_string()];
661        canonicalize_rule_list_in_place(&mut list);
662        assert_eq!(list, vec!["MD033".to_string(), "MD013".to_string()]);
663    }
664
665    #[test]
666    fn dedupes_alias_and_canonical_preserving_order() {
667        let mut list = vec!["MD033".to_string(), "no-inline-html".to_string(), "MD013".to_string()];
668        canonicalize_rule_list_in_place(&mut list);
669        assert_eq!(list, vec!["MD033".to_string(), "MD013".to_string()]);
670    }
671
672    #[test]
673    fn preserves_all_keyword_normalized() {
674        let mut list = vec!["ALL".to_string(), "MD013".to_string()];
675        canonicalize_rule_list_in_place(&mut list);
676        assert_eq!(list, vec!["all".to_string(), "MD013".to_string()]);
677    }
678
679    #[test]
680    fn is_idempotent() {
681        let mut list = vec!["no-inline-html".to_string(), "MD013".to_string()];
682        canonicalize_rule_list_in_place(&mut list);
683        let once = list.clone();
684        canonicalize_rule_list_in_place(&mut list);
685        assert_eq!(list, once);
686    }
687
688    #[test]
689    fn handles_empty_and_unknown_inputs() {
690        let mut empty: Vec<String> = Vec::new();
691        canonicalize_rule_list_in_place(&mut empty);
692        assert!(empty.is_empty());
693
694        let mut unknown = vec!["custom-rule".to_string(), "Custom-Rule".to_string()];
695        canonicalize_rule_list_in_place(&mut unknown);
696        // Both normalize to the same kebab-case form, so they dedupe.
697        assert_eq!(unknown, vec!["custom-rule".to_string()]);
698    }
699}