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