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