wikioxide 0.1.0

MediaWiki wikitext parser producing typed domain models (templates, links, categories, warnings) with template expansion — no HTML, no network
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
//! Per-wiki configuration, compiled once for fast lookups during parsing.
//!
//! A [`SiteConfig`] carries everything wiki-specific: namespaces with their localized
//! names and aliases, magic words, extension tags, external-link protocols, the
//! link-trail character class, interwiki prefixes and magic-link toggles. Construct one
//! programmatically with [`SiteConfig::builder`], or (with the `presets` feature) load a
//! vendored preset such as `SiteConfig::ruwiki()`.

mod limits;
#[cfg(feature = "presets")]
mod presets;

use std::collections::{HashMap, HashSet};

pub use limits::Limits;

use crate::error::ConfigError;
use crate::title::Namespace;

/// MediaWiki's default external-link protocols (`$wgUrlProtocols`).
const DEFAULT_PROTOCOLS: &[&str] = &[
    "//",
    "bitcoin:",
    "ftp://",
    "ftps://",
    "geo:",
    "git://",
    "gopher://",
    "http://",
    "https://",
    "irc://",
    "ircs://",
    "magnet:",
    "mailto:",
    "matrix:",
    "mms://",
    "news:",
    "nntp://",
    "redis://",
    "sftp://",
    "sip:",
    "sips:",
    "sms:",
    "ssh://",
    "svn://",
    "tel:",
    "telnet://",
    "urn:",
    "worldwind://",
    "xmpp:",
];

/// One namespace definition fed to [`SiteConfigBuilder::namespace`].
#[derive(Debug, Clone)]
pub struct NamespaceDef {
    /// MediaWiki namespace id (0 = main, 10 = Template, 14 = Category, 828 = Module).
    pub id: i32,
    /// Canonical English name; empty for the main namespace.
    pub canonical: String,
    /// Localized name, used by [`Title::text`](crate::Title::text); empty for main.
    pub localized: String,
    /// Additional accepted aliases (e.g. `Изображение` for `File:` on Russian wikis).
    pub aliases: Vec<String>,
    /// Whether page names in this namespace are first-letter case-insensitive.
    pub first_letter: bool,
}

impl NamespaceDef {
    /// The main (article) namespace definition.
    #[must_use]
    pub fn main() -> Self {
        Self {
            id: 0,
            canonical: String::new(),
            localized: String::new(),
            aliases: Vec::new(),
            first_letter: true,
        }
    }

    /// A namespace definition with the given id, names and case rule.
    pub fn new<A>(
        id: i32,
        canonical: impl Into<String>,
        localized: impl Into<String>,
        aliases: A,
        first_letter: bool,
    ) -> Self
    where
        A: IntoIterator,
        A::Item: Into<String>,
    {
        Self {
            id,
            canonical: canonical.into(),
            localized: localized.into(),
            aliases: aliases.into_iter().map(Into::into).collect(),
            first_letter,
        }
    }
}

/// One magic word — a variable, parser function or behavior switch — with its aliases.
///
/// Aliases are stored the way `meta=siteinfo` reports them: parser-function aliases
/// without the `#` prefix (`if` for `{{#if:}}`), behavior switches with their underscores
/// (`__NOTOC__`), redirect keywords with the leading `#` (`#REDIRECT`).
#[derive(Debug, Clone)]
pub struct MagicWordDef {
    /// Stable MediaWiki identifier (e.g. `if`, `redirect`, `toc`, `pagename`).
    pub id: String,
    /// Accepted spellings.
    pub aliases: Vec<String>,
    /// Whether the aliases match case-sensitively.
    pub case_sensitive: bool,
}

impl MagicWordDef {
    /// A magic word definition.
    pub fn new<A>(id: impl Into<String>, aliases: A, case_sensitive: bool) -> Self
    where
        A: IntoIterator,
        A::Item: Into<String>,
    {
        Self {
            id: id.into(),
            aliases: aliases.into_iter().map(Into::into).collect(),
            case_sensitive,
        }
    }
}

/// How an extension tag's body is treated by the parser.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExtTagContent {
    /// The body is opaque: captured verbatim, never parsed as wikitext (`<nowiki>`,
    /// `<math>`, `<syntaxhighlight>`, …).
    Opaque,
    /// The body is parsed as inline wikitext (`<poem>`, `<ref>` content).
    InlineWikitext,
}

/// Toggles for MediaWiki's RFC/PMID/ISBN "magic links" (still enabled on Wikimedia wikis).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MagicLinks {
    /// `RFC 2324` auto-links to the IETF RFC.
    pub rfc: bool,
    /// `PMID 12345` auto-links to PubMed.
    pub pmid: bool,
    /// `ISBN 978-...` auto-links to the book-sources page.
    pub isbn: bool,
}

impl Default for MagicLinks {
    fn default() -> Self {
        Self {
            rfc: true,
            pmid: true,
            isbn: true,
        }
    }
}

/// Localized month names in the three forms MediaWiki date formatting uses. The
/// genitive form is the one that appears in signature timestamps (Russian
/// `8 мая 2026` uses the genitive `мая`); English uses the nominative for all three.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MonthNames {
    /// Genitive month names (MediaWiki `xg` format code); index 0 = January.
    pub genitive: [String; 12],
    /// Nominative month names (MediaWiki `F` format code).
    pub nominative: [String; 12],
    /// Three-letter abbreviations (MediaWiki `M` format code).
    pub abbreviations: [String; 12],
}

impl Default for MonthNames {
    fn default() -> Self {
        let full = [
            "January",
            "February",
            "March",
            "April",
            "May",
            "June",
            "July",
            "August",
            "September",
            "October",
            "November",
            "December",
        ]
        .map(String::from);
        let abbr = [
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        ]
        .map(String::from);
        Self {
            genitive: full.clone(),
            nominative: full,
            abbreviations: abbr,
        }
    }
}

/// Compiled per-wiki configuration. Cheap to share (`Clone` clones the compiled tables);
/// build one per wiki and reuse it for every parse.
#[derive(Debug, Clone)]
pub struct SiteConfig {
    lang: String,
    site_name: String,
    namespaces: Vec<NamespaceDef>,
    ns_index: HashMap<i32, usize>,
    ns_aliases: HashMap<String, i32>,
    magic_words: Vec<MagicWordDef>,
    magic_exact: HashMap<String, usize>,
    magic_folded: HashMap<String, usize>,
    redirect_aliases: Vec<String>,
    ext_tags: HashMap<String, ExtTagContent>,
    protocols: Vec<String>,
    link_trail: LinkTrail,
    interwiki: HashSet<String>,
    magic_links: MagicLinks,
    months: MonthNames,
    lang_converter: bool,
}

impl SiteConfig {
    /// Starts building a configuration for a wiki with the given content language code
    /// and site name.
    #[must_use]
    pub fn builder(lang: impl Into<String>, site_name: impl Into<String>) -> SiteConfigBuilder {
        SiteConfigBuilder::new(lang, site_name)
    }

    /// The wiki's content-language code (e.g. `"ru"`).
    #[must_use]
    pub fn lang(&self) -> &str {
        &self.lang
    }

    /// The wiki's site name (e.g. `"Википедия"`), the `{{SITENAME}}` value.
    #[must_use]
    pub fn site_name(&self) -> &str {
        &self.site_name
    }

    /// Resolves a namespace prefix (canonical, localized or alias; case-insensitive,
    /// underscore/space-insensitive) to a namespace.
    #[must_use]
    pub fn resolve_namespace(&self, prefix: &str) -> Option<Namespace> {
        let folded = fold(prefix);
        if folded.is_empty() {
            return None;
        }
        self.ns_aliases.get(&folded).copied().map(Namespace::new)
    }

    /// The localized name of a namespace this config defines (empty string for main).
    #[must_use]
    pub fn namespace_name(&self, ns: Namespace) -> Option<&str> {
        self.ns_index
            .get(&ns.id())
            .map(|&i| self.namespaces[i].localized.as_str())
    }

    /// Whether titles in `ns` are first-letter case-insensitive (true for unknown ids,
    /// matching MediaWiki's default).
    #[must_use]
    pub fn ns_first_letter(&self, ns: Namespace) -> bool {
        self.ns_index
            .get(&ns.id())
            .is_none_or(|&i| self.namespaces[i].first_letter)
    }

    /// Resolves a magic-word alias to its stable id, honoring per-word case sensitivity.
    #[must_use]
    pub fn resolve_magic_word(&self, alias: &str) -> Option<&str> {
        let index = self
            .magic_exact
            .get(alias)
            .or_else(|| self.magic_folded.get(&fold(alias)))?;
        Some(self.magic_words[*index].id.as_str())
    }

    /// The accepted redirect keywords (`#REDIRECT`, `#ПЕРЕНАПРАВЛЕНИЕ`, …), folded.
    #[must_use]
    pub fn redirect_aliases(&self) -> &[String] {
        &self.redirect_aliases
    }

    /// How the given extension tag treats its body, if the tag is registered.
    /// Lookup is case-insensitive (`<NoWiki>` works).
    #[must_use]
    pub fn ext_tag(&self, name: &str) -> Option<ExtTagContent> {
        self.ext_tags.get(&name.to_lowercase()).copied()
    }

    /// External-link protocols, longest first (so `https://` wins over `http://` — and
    /// both over `//`).
    #[must_use]
    pub fn protocols(&self) -> &[String] {
        &self.protocols
    }

    /// Whether `c` may extend a link label past the closing brackets (`[[dog]]s`).
    #[must_use]
    pub fn trail_accepts(&self, c: char) -> bool {
        self.link_trail.accepts(c)
    }

    /// Whether `prefix` is a known interwiki prefix (case-insensitive).
    #[must_use]
    pub fn is_interwiki_prefix(&self, prefix: &str) -> bool {
        self.interwiki.contains(&fold(prefix))
    }

    /// The RFC/PMID/ISBN magic-link toggles.
    #[must_use]
    pub fn magic_links(&self) -> MagicLinks {
        self.magic_links
    }

    /// Whether LanguageConverter markup (`-{ … }-`) is recognized on this wiki.
    #[must_use]
    pub fn lang_converter(&self) -> bool {
        self.lang_converter
    }

    /// The localized month names (genitive/nominative/abbreviated) used by the
    /// signature-timestamp matcher.
    #[must_use]
    pub fn months(&self) -> &MonthNames {
        &self.months
    }
}

/// Builder for [`SiteConfig`] — the JSON-free construction path.
#[derive(Debug)]
pub struct SiteConfigBuilder {
    lang: String,
    site_name: String,
    namespaces: Vec<NamespaceDef>,
    magic_words: Vec<MagicWordDef>,
    ext_tags: Vec<(String, ExtTagContent)>,
    protocols: Vec<String>,
    link_trail: String,
    interwiki: Vec<String>,
    magic_links: MagicLinks,
    months: MonthNames,
    lang_converter: bool,
}

impl SiteConfigBuilder {
    fn new(lang: impl Into<String>, site_name: impl Into<String>) -> Self {
        Self {
            lang: lang.into(),
            site_name: site_name.into(),
            namespaces: Vec::new(),
            magic_words: Vec::new(),
            ext_tags: Vec::new(),
            protocols: DEFAULT_PROTOCOLS.iter().map(|&p| p.to_owned()).collect(),
            link_trail: "a-z".to_owned(),
            interwiki: Vec::new(),
            magic_links: MagicLinks::default(),
            months: MonthNames::default(),
            lang_converter: false,
        }
    }

    /// Sets the localized month names used by the signature-timestamp matcher.
    #[must_use]
    pub fn months(mut self, months: MonthNames) -> Self {
        self.months = months;
        self
    }

    /// Adds a namespace definition.
    #[must_use]
    pub fn namespace(mut self, def: NamespaceDef) -> Self {
        self.namespaces.push(def);
        self
    }

    /// Adds a magic-word definition.
    #[must_use]
    pub fn magic_word(mut self, def: MagicWordDef) -> Self {
        self.magic_words.push(def);
        self
    }

    /// Registers an extension tag and how its body is treated.
    #[must_use]
    pub fn ext_tag(mut self, name: impl Into<String>, content: ExtTagContent) -> Self {
        self.ext_tags.push((name.into(), content));
        self
    }

    /// Replaces the external-link protocol list (defaults to MediaWiki's).
    #[must_use]
    pub fn protocols<P>(mut self, protocols: P) -> Self
    where
        P: IntoIterator,
        P::Item: Into<String>,
    {
        self.protocols = protocols.into_iter().map(Into::into).collect();
        self
    }

    /// Sets the link-trail character class body (default `"a-z"`; `""` disables trails).
    #[must_use]
    pub fn link_trail(mut self, class: impl Into<String>) -> Self {
        self.link_trail = class.into();
        self
    }

    /// Replaces the interwiki prefix list.
    #[must_use]
    pub fn interwiki<P>(mut self, prefixes: P) -> Self
    where
        P: IntoIterator,
        P::Item: Into<String>,
    {
        self.interwiki = prefixes.into_iter().map(Into::into).collect();
        self
    }

    /// Sets the RFC/PMID/ISBN magic-link toggles.
    #[must_use]
    pub fn magic_links(mut self, links: MagicLinks) -> Self {
        self.magic_links = links;
        self
    }

    /// Enables or disables LanguageConverter markup recognition.
    #[must_use]
    pub fn lang_converter(mut self, enabled: bool) -> Self {
        self.lang_converter = enabled;
        self
    }

    /// Validates the definitions and compiles the lookup tables.
    pub fn build(self) -> Result<SiteConfig, ConfigError> {
        let mut ns_index: HashMap<i32, usize> = HashMap::new();
        for (i, def) in self.namespaces.iter().enumerate() {
            if ns_index.insert(def.id, i).is_some() {
                return Err(ConfigError::DuplicateNamespace(def.id));
            }
        }
        if !ns_index.contains_key(&0) {
            return Err(ConfigError::MissingMainNamespace);
        }

        let mut ns_aliases: HashMap<String, i32> = HashMap::new();
        for def in &self.namespaces {
            let names = std::iter::once(&def.canonical)
                .chain(std::iter::once(&def.localized))
                .chain(def.aliases.iter());
            for name in names {
                let folded = fold(name);
                if folded.is_empty() {
                    continue;
                }
                match ns_aliases.get(&folded) {
                    Some(&existing) if existing != def.id => {
                        return Err(ConfigError::ConflictingNamespaceAlias {
                            alias: folded,
                            first: existing,
                            second: def.id,
                        });
                    }
                    _ => {
                        ns_aliases.insert(folded, def.id);
                    }
                }
            }
        }

        let mut magic_exact = HashMap::new();
        let mut magic_folded = HashMap::new();
        let mut redirect_aliases = Vec::new();
        for (i, word) in self.magic_words.iter().enumerate() {
            for alias in &word.aliases {
                if word.case_sensitive {
                    magic_exact.insert(alias.clone(), i);
                } else {
                    magic_folded.insert(fold(alias), i);
                }
                if word.id == "redirect" {
                    redirect_aliases.push(fold(alias));
                }
            }
        }

        let ext_tags = self
            .ext_tags
            .into_iter()
            .map(|(name, content)| (name.to_lowercase(), content))
            .collect();

        let mut protocols = self.protocols;
        protocols.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.cmp(b)));

        let link_trail =
            LinkTrail::parse(&self.link_trail).ok_or_else(|| ConfigError::LinkTrail {
                pattern: self.link_trail.clone(),
            })?;

        let interwiki = self.interwiki.iter().map(|p| fold(p)).collect();

        Ok(SiteConfig {
            lang: self.lang,
            site_name: self.site_name,
            namespaces: self.namespaces,
            ns_index,
            ns_aliases,
            magic_words: self.magic_words,
            magic_exact,
            magic_folded,
            redirect_aliases,
            ext_tags,
            protocols,
            link_trail,
            interwiki,
            magic_links: self.magic_links,
            months: self.months,
            lang_converter: self.lang_converter,
        })
    }
}

/// Case- and whitespace-insensitive key form shared by every lookup table: underscores
/// and whitespace runs collapse to single spaces, ends trimmed, lower-cased.
pub(crate) fn fold(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut pending_space = false;
    for c in s.chars() {
        if c == '_' || c.is_whitespace() {
            pending_space = true;
            continue;
        }
        if pending_space && !out.is_empty() {
            out.push(' ');
        }
        pending_space = false;
        out.extend(c.to_lowercase());
    }
    out
}

/// A compiled link-trail character class (the `[a-zа-яё]` part of MediaWiki's
/// `linktrail` regex).
#[derive(Debug, Clone, Default)]
struct LinkTrail {
    ranges: Vec<(char, char)>,
}

impl LinkTrail {
    /// Parses a character-class body: plain characters and `lo-hi` ranges. A `-` at the
    /// start or end is a literal. Returns `None` on an inverted range.
    fn parse(class: &str) -> Option<Self> {
        let chars: Vec<char> = class.chars().collect();
        let mut ranges = Vec::new();
        let mut i = 0;
        while i < chars.len() {
            if i + 2 < chars.len() && chars[i + 1] == '-' {
                let (lo, hi) = (chars[i], chars[i + 2]);
                if lo > hi {
                    return None;
                }
                ranges.push((lo, hi));
                i += 3;
            } else {
                ranges.push((chars[i], chars[i]));
                i += 1;
            }
        }
        ranges.sort_unstable();
        Some(Self { ranges })
    }

    fn accepts(&self, c: char) -> bool {
        self.ranges.iter().any(|&(lo, hi)| lo <= c && c <= hi)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn base() -> SiteConfigBuilder {
        SiteConfig::builder("ru", "Википедия")
            .namespace(NamespaceDef::main())
            .namespace(NamespaceDef::new(
                10,
                "Template",
                "Шаблон",
                ["Ш", "T"],
                true,
            ))
            .namespace(NamespaceDef::new(6, "File", "Файл", ["Изображение"], true))
    }

    #[test]
    fn builder_compiles_and_exposes_identity() {
        let config = base().build().unwrap();
        assert_eq!(config.lang(), "ru");
        assert_eq!(config.site_name(), "Википедия");
        assert!(!config.lang_converter());
        assert_eq!(config.magic_links(), MagicLinks::default());
        assert!(format!("{config:?}").contains("SiteConfig"));
        let _clone = config.clone();
    }

    #[test]
    fn namespace_resolution_folds_case_and_underscores() {
        let config = base().build().unwrap();
        for prefix in ["Шаблон", "шаблон", "TEMPLATE", "т"] {
            let resolved = config.resolve_namespace(prefix);
            if prefix == "т" {
                assert_eq!(resolved, None, "unknown alias must not resolve");
            } else {
                assert_eq!(resolved.map(Namespace::id), Some(10), "{prefix}");
            }
        }
        assert_eq!(
            config.resolve_namespace("_изображение_").map(Namespace::id),
            Some(6)
        );
        assert_eq!(config.resolve_namespace(""), None);
        assert_eq!(config.namespace_name(Namespace::TEMPLATE), Some("Шаблон"));
        assert_eq!(config.namespace_name(Namespace::MAIN), Some(""));
        assert_eq!(config.namespace_name(Namespace::MODULE), None);
        assert!(
            config.ns_first_letter(Namespace::MODULE),
            "unknown ns defaults to first-letter"
        );
    }

    #[test]
    fn missing_main_namespace_is_rejected() {
        let err = SiteConfig::builder("en", "Wiki")
            .namespace(NamespaceDef::new(
                10,
                "Template",
                "Template",
                Vec::<String>::new(),
                true,
            ))
            .build()
            .unwrap_err();
        assert!(matches!(err, ConfigError::MissingMainNamespace));
    }

    #[test]
    fn duplicate_namespace_ids_are_rejected() {
        let err = base()
            .namespace(NamespaceDef::new(
                10,
                "Other",
                "Другое",
                Vec::<String>::new(),
                true,
            ))
            .build()
            .unwrap_err();
        assert!(matches!(err, ConfigError::DuplicateNamespace(10)));
    }

    #[test]
    fn conflicting_aliases_are_rejected() {
        let err = base()
            .namespace(NamespaceDef::new(828, "Module", "Модуль", ["Ш"], true))
            .build()
            .unwrap_err();
        assert_eq!(
            err,
            ConfigError::ConflictingNamespaceAlias {
                alias: "ш".to_owned(),
                first: 10,
                second: 828,
            }
        );
    }

    #[test]
    fn same_alias_on_the_same_namespace_is_fine() {
        let config = base()
            .namespace(NamespaceDef::new(
                14,
                "Category",
                "Category",
                ["category"],
                true,
            ))
            .build()
            .unwrap();
        assert_eq!(
            config.resolve_namespace("Category").map(Namespace::id),
            Some(14)
        );
    }

    #[test]
    fn magic_words_respect_case_sensitivity() {
        let config = base()
            .magic_word(MagicWordDef::new("notoc", ["__NOTOC__"], true))
            .magic_word(MagicWordDef::new(
                "redirect",
                ["#REDIRECT", "#перенаправление"],
                false,
            ))
            .build()
            .unwrap();
        assert_eq!(config.resolve_magic_word("__NOTOC__"), Some("notoc"));
        assert_eq!(
            config.resolve_magic_word("__notoc__"),
            None,
            "case-sensitive word"
        );
        assert_eq!(config.resolve_magic_word("#Redirect"), Some("redirect"));
        assert_eq!(
            config.resolve_magic_word("#ПЕРЕНАПРАВЛЕНИЕ"),
            Some("redirect")
        );
        assert_eq!(config.resolve_magic_word("nope"), None);
        assert_eq!(config.redirect_aliases(), ["#redirect", "#перенаправление"]);
    }

    #[test]
    fn ext_tags_look_up_case_insensitively() {
        let config = base()
            .ext_tag("nowiki", ExtTagContent::Opaque)
            .ext_tag("Poem", ExtTagContent::InlineWikitext)
            .build()
            .unwrap();
        assert_eq!(config.ext_tag("NoWiki"), Some(ExtTagContent::Opaque));
        assert_eq!(config.ext_tag("POEM"), Some(ExtTagContent::InlineWikitext));
        assert_eq!(config.ext_tag("ref"), None);
    }

    #[test]
    fn protocols_default_to_mediawiki_list_sorted_longest_first() {
        let config = base().build().unwrap();
        let protocols = config.protocols();
        assert!(protocols.iter().any(|p| p == "https://"));
        assert!(protocols.iter().any(|p| p == "//"));
        for pair in protocols.windows(2) {
            assert!(pair[0].len() >= pair[1].len(), "{pair:?}");
        }
        let custom = base().protocols(["http://"]).build().unwrap();
        assert_eq!(custom.protocols(), ["http://"]);
    }

    #[test]
    fn link_trail_classes_parse_ranges_singles_and_literal_dashes() {
        let config = base().link_trail("a-zа-яё-").build().unwrap();
        for c in ['a', 'z', 'м', 'ё', '-'] {
            assert!(config.trail_accepts(c), "{c}");
        }
        for c in ['A', 'Я', '1', ' '] {
            assert!(!config.trail_accepts(c), "{c}");
        }

        let disabled = base().link_trail("").build().unwrap();
        assert!(!disabled.trail_accepts('a'));

        let err = base().link_trail("z-a").build().unwrap_err();
        assert!(matches!(err, ConfigError::LinkTrail { pattern } if pattern == "z-a"));
    }

    #[test]
    fn interwiki_prefixes_fold_case() {
        let config = base().interwiki(["fr", "De"]).build().unwrap();
        assert!(config.is_interwiki_prefix("FR"));
        assert!(config.is_interwiki_prefix("de"));
        assert!(!config.is_interwiki_prefix("en"));
    }

    #[test]
    fn magic_links_and_lang_converter_toggles() {
        let config = base()
            .magic_links(MagicLinks {
                rfc: false,
                pmid: true,
                isbn: false,
            })
            .lang_converter(true)
            .build()
            .unwrap();
        assert!(!config.magic_links().rfc);
        assert!(config.magic_links().pmid);
        assert!(!config.magic_links().isbn);
        assert!(config.lang_converter());
    }

    #[test]
    fn months_default_to_english_and_the_builder_overrides_them() {
        // Default: English in all three forms.
        let default = base().build().unwrap();
        assert_eq!(default.months().genitive[0], "January");
        assert_eq!(default.months().nominative[4], "May");
        assert_eq!(default.months().abbreviations[11], "Dec");
        assert_eq!(default.months(), &MonthNames::default());

        // Override: Russian genitive (the signature form).
        let ru_gen = [
            "января",
            "февраля",
            "марта",
            "апреля",
            "мая",
            "июня",
            "июля",
            "августа",
            "сентября",
            "октября",
            "ноября",
            "декабря",
        ]
        .map(String::from);
        let months = MonthNames {
            genitive: ru_gen.clone(),
            ..MonthNames::default()
        };
        let config = base().months(months).build().unwrap();
        assert_eq!(config.months().genitive, ru_gen);
        assert_eq!(
            config.months().nominative[0],
            "January",
            "untouched form stays default"
        );
        assert!(format!("{:?}", config.months()).contains("января"));
    }

    #[test]
    fn fold_collapses_and_lowercases() {
        assert_eq!(fold("  Foo__BAR baz "), "foo bar baz");
        assert_eq!(fold("ЁЖ"), "ёж");
        assert_eq!(fold("___"), "");
    }

    #[test]
    fn definition_types_are_cloneable_and_debuggable() {
        let ns = NamespaceDef::new(4, "Project", "Проект", ["ВП"], true);
        let word = MagicWordDef::new("if", ["if"], false);
        let rendered = format!(
            "{:?} {:?} {:?}",
            ns.clone(),
            word.clone(),
            ExtTagContent::Opaque
        );
        assert!(rendered.contains("NamespaceDef"));
        assert_eq!(ns.aliases, ["ВП"]);
        assert!(!word.case_sensitive);
    }
}