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
//! Public domain models — what a parse produces.
//!
//! All types are read-mostly: the engine constructs them, callers consume through
//! accessors. With the `serde` feature they implement [`serde::Serialize`] (not
//! `Deserialize` — several carry [`Title`]s, which require a [`SiteConfig`]
//! (crate::SiteConfig) to construct meaningfully).

use std::collections::BTreeMap;

use crate::title::Title;

/// A byte range into the original input passed to the parser.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Span {
    /// Start byte offset (inclusive).
    pub start: usize,
    /// End byte offset (exclusive).
    pub end: usize,
}

/// Where an extracted item came from.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum Origin {
    /// Written literally in the parsed input.
    Input,
    /// Produced by expanding the named transcluded page.
    Transclusion(Title),
}

/// One template call, with its full parameter map — including calls nested inside
/// other calls' argument values.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct TemplateCall {
    title: Title,
    name_raw: String,
    params: BTreeMap<String, String>,
    origin: Origin,
    span: Option<Span>,
    resolved: bool,
}

impl TemplateCall {
    pub(crate) fn new(
        title: Title,
        name_raw: String,
        params: BTreeMap<String, String>,
        origin: Origin,
        span: Option<Span>,
        resolved: bool,
    ) -> Self {
        Self {
            title,
            name_raw,
            params,
            origin,
            span,
            resolved,
        }
    }

    /// The normalized target (`{{foo}}` resolves into the Template namespace,
    /// `{{:Page}}` into main).
    #[must_use]
    pub fn title(&self) -> &Title {
        &self.title
    }

    /// The name exactly as written between `{{` and the first `|`, trimmed.
    #[must_use]
    pub fn name_raw(&self) -> &str {
        &self.name_raw
    }

    /// Parameters: named keys as written, positional keys `"1"`, `"2"`, …
    /// MediaWiki whitespace rules applied (named names/values trimmed, positional
    /// values preserved). On duplicate keys the last value wins (and a
    /// [`Warning`](crate::Warning) is emitted).
    #[must_use]
    pub fn params(&self) -> &BTreeMap<String, String> {
        &self.params
    }

    /// A single parameter by key.
    #[must_use]
    pub fn param(&self, key: &str) -> Option<&str> {
        self.params.get(key).map(String::as_str)
    }

    /// Whether the call was written in the input or produced by a transclusion.
    #[must_use]
    pub fn origin(&self) -> &Origin {
        &self.origin
    }

    /// Byte range in the original input; `Some` only for [`Origin::Input`] calls.
    #[must_use]
    pub fn span(&self) -> Option<Span> {
        self.span
    }

    /// False when the target could not be resolved to content: a red link, an
    /// unexpanded `{{#invoke:}}` shell, or an unresolved source under the red-link
    /// policy.
    #[must_use]
    pub fn resolved(&self) -> bool {
        self.resolved
    }
}

/// One `{{#invoke:Module|function|…}}` call (Scribunto is not executed in v1).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct ModuleInvocation {
    module: Title,
    function: String,
    args: BTreeMap<String, String>,
}

impl ModuleInvocation {
    pub(crate) fn new(module: Title, function: String, args: BTreeMap<String, String>) -> Self {
        Self {
            module,
            function,
            args,
        }
    }

    /// The `Module:` page (namespace 828).
    #[must_use]
    pub fn module(&self) -> &Title {
        &self.module
    }

    /// The invoked function name.
    #[must_use]
    pub fn function(&self) -> &str {
        &self.function
    }

    /// Invocation arguments, keyed like template parameters.
    #[must_use]
    pub fn args(&self) -> &BTreeMap<String, String> {
        &self.args
    }
}

/// An internal wikilink (the API's `prop=links` item).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct InternalLink {
    target: Title,
    fragment: Option<String>,
    anchor_text: Option<String>,
    exists: Option<bool>,
    span: Option<Span>,
}

impl InternalLink {
    pub(crate) fn new(
        target: Title,
        fragment: Option<String>,
        anchor_text: Option<String>,
        span: Option<Span>,
    ) -> Self {
        Self {
            target,
            fragment,
            anchor_text,
            exists: None,
            span,
        }
    }

    /// The link target (fragment removed, like the API reports it).
    #[must_use]
    pub fn target(&self) -> &Title {
        &self.target
    }

    /// The `#fragment` written after the target, if any.
    #[must_use]
    pub fn fragment(&self) -> Option<&str> {
        self.fragment.as_deref()
    }

    /// The visible label when a pipe was used (`[[a|label]]`).
    #[must_use]
    pub fn anchor_text(&self) -> Option<&str> {
        self.anchor_text.as_deref()
    }

    /// Whether the target page exists. `None` until existence enrichment is applied.
    #[must_use]
    pub fn exists(&self) -> Option<bool> {
        self.exists
    }

    #[allow(dead_code, reason = "consumed by the existence-enrichment stage")]
    pub(crate) fn set_exists(&mut self, exists: bool) {
        self.exists = Some(exists);
    }

    /// Byte range in the original input, when the link was written there.
    #[must_use]
    pub fn span(&self) -> Option<Span> {
        self.span
    }
}

/// A category membership (the API's `prop=categories` item).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct CategoryLink {
    category: Title,
    sortkey: String,
    hidden: Option<bool>,
    missing: Option<bool>,
    span: Option<Span>,
}

impl CategoryLink {
    pub(crate) fn new(category: Title, sortkey: String, span: Option<Span>) -> Self {
        Self {
            category,
            sortkey,
            hidden: None,
            missing: None,
            span,
        }
    }

    /// The category page title.
    #[must_use]
    pub fn category(&self) -> &Title {
        &self.category
    }

    /// The effective raw sort key (`[[Category:X|key]]`, `{{DEFAULTSORT:…}}`-aware);
    /// empty when unspecified.
    #[must_use]
    pub fn sortkey(&self) -> &str {
        &self.sortkey
    }

    /// Whether the category is hidden (`__HIDDENCAT__` on its page). Requires
    /// existence enrichment; `None` until applied.
    #[must_use]
    pub fn hidden(&self) -> Option<bool> {
        self.hidden
    }

    /// Whether the category page is missing. Requires enrichment; `None` until applied.
    #[must_use]
    pub fn missing(&self) -> Option<bool> {
        self.missing
    }

    #[allow(dead_code, reason = "consumed by the existence-enrichment stage")]
    pub(crate) fn set_facts(&mut self, missing: bool, hidden: Option<bool>) {
        self.missing = Some(missing);
        self.hidden = hidden;
    }

    /// Byte range in the original input, when written there.
    #[must_use]
    pub fn span(&self) -> Option<Span> {
        self.span
    }
}

/// An external link (the API's `externallinks` item).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct ExternalLink {
    url: String,
    display: Option<String>,
    span: Option<Span>,
}

impl ExternalLink {
    pub(crate) fn new(url: String, display: Option<String>, span: Option<Span>) -> Self {
        Self { url, display, span }
    }

    /// The raw URL as written.
    #[must_use]
    pub fn url(&self) -> &str {
        &self.url
    }

    /// The bracketed label text, if one was given.
    #[must_use]
    pub fn display(&self) -> Option<&str> {
        self.display.as_deref()
    }

    /// Byte range in the original input, when written there.
    #[must_use]
    pub fn span(&self) -> Option<Span> {
        self.span
    }
}

/// An interlanguage (or interwiki) sidebar link, e.g. `[[fr:Chat]]`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct InterLanguageLink {
    prefix: String,
    target: String,
}

impl InterLanguageLink {
    pub(crate) fn new(prefix: String, target: String) -> Self {
        Self { prefix, target }
    }

    /// The language/interwiki prefix as written (e.g. `fr`).
    #[must_use]
    pub fn prefix(&self) -> &str {
        &self.prefix
    }

    /// The target page text on the other wiki (unnormalized — foreign title rules).
    #[must_use]
    pub fn target(&self) -> &str {
        &self.target
    }
}

/// A `#REDIRECT [[Target#fragment]]` declaration at the top of the page.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct Redirect {
    target: Title,
    fragment: Option<String>,
}

impl Redirect {
    pub(crate) fn new(target: Title, fragment: Option<String>) -> Self {
        Self { target, fragment }
    }

    /// Where the redirect points.
    #[must_use]
    pub fn target(&self) -> &Title {
        &self.target
    }

    /// The `#fragment` of the target, if any.
    #[must_use]
    pub fn fragment(&self) -> Option<&str> {
        self.fragment.as_deref()
    }
}

/// Structural counts over the parsed document — the replacement for counting
/// `<table`/`<tr` substrings in API HTML.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct StructuralStats {
    pub(crate) tables: u32,
    pub(crate) table_rows: u32,
    pub(crate) table_cells: u32,
    pub(crate) headings: u32,
    pub(crate) refs: u32,
    pub(crate) list_items: u32,
    pub(crate) images: u32,
    pub(crate) internal_links: u32,
    pub(crate) external_links: u32,
    pub(crate) parser_errors: u32,
}

impl StructuralStats {
    /// Number of tables (including nested ones).
    #[must_use]
    pub fn tables(&self) -> u32 {
        self.tables
    }

    /// Number of table rows.
    #[must_use]
    pub fn table_rows(&self) -> u32 {
        self.table_rows
    }

    /// Number of table cells (data + header).
    #[must_use]
    pub fn table_cells(&self) -> u32 {
        self.table_cells
    }

    /// Number of headings.
    #[must_use]
    pub fn headings(&self) -> u32 {
        self.headings
    }

    /// Number of `<ref>` tags.
    #[must_use]
    pub fn refs(&self) -> u32 {
        self.refs
    }

    /// Number of list items across all lists.
    #[must_use]
    pub fn list_items(&self) -> u32 {
        self.list_items
    }

    /// Number of image/file usages.
    #[must_use]
    pub fn images(&self) -> u32 {
        self.images
    }

    /// Number of internal link usages (pre-dedup).
    #[must_use]
    pub fn internal_links(&self) -> u32 {
        self.internal_links
    }

    /// Number of external link usages (pre-dedup).
    #[must_use]
    pub fn external_links(&self) -> u32 {
        self.external_links
    }

    /// Inline parser-error artifacts (expression errors, unexpandable invokes) — the
    /// analog of counting `class="error"` in API HTML.
    #[must_use]
    pub fn parser_errors(&self) -> u32 {
        self.parser_errors
    }
}

/// A heading and the section it introduces, with byte spans into the **original source**
/// (never the flattened text) so a consumer can slice or move the raw wikitext.
///
/// Available only on [`ParsedDocument`](crate::ParsedDocument): expansion rewrites offsets,
/// so the expanded view intentionally exposes no sections. Subsections nest by heading
/// level; a section's `body_span` covers its heading through just before the next heading
/// of the same or a higher level, so it is contiguous and includes all of its subsections.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct Section {
    level: u8,
    heading_span: Span,
    title_span: Span,
    body_span: Span,
    title_text: String,
    children: Vec<Section>,
}

impl Section {
    pub(crate) fn new(
        level: u8,
        heading_span: Span,
        title_span: Span,
        body_span: Span,
        title_text: String,
        children: Vec<Section>,
    ) -> Self {
        Self {
            level,
            heading_span,
            title_span,
            body_span,
            title_text,
            children,
        }
    }

    /// Heading depth, 1–6.
    #[must_use]
    pub fn level(&self) -> u8 {
        self.level
    }

    /// Source span of the whole heading line, both `=` runs included (`== Foo ==`).
    #[must_use]
    pub fn heading_span(&self) -> Span {
        self.heading_span
    }

    /// Source span of the inner title only (the `=` runs and surrounding spaces removed),
    /// so a caller can slice the raw wikitext to inspect struck (`<s>…</s>`) titles or
    /// links written inside the heading.
    #[must_use]
    pub fn title_span(&self) -> Span {
        self.title_span
    }

    /// Source span covering this heading through just before the next heading of the same
    /// or a higher level — contiguous and inclusive of every subsection, safe to move.
    #[must_use]
    pub fn body_span(&self) -> Span {
        self.body_span
    }

    /// Plain-text rendering of the heading title (markup removed).
    #[must_use]
    pub fn title_text(&self) -> &str {
        &self.title_text
    }

    /// Directly nested subsections (the next deeper levels), in document order.
    #[must_use]
    pub fn children(&self) -> &[Section] {
        &self.children
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{NamespaceDef, SiteConfig};

    fn config() -> SiteConfig {
        SiteConfig::builder("ru", "Вики")
            .namespace(NamespaceDef::main())
            .namespace(NamespaceDef::new(10, "Template", "Шаблон", ["Ш"], true))
            .namespace(NamespaceDef::new(
                14,
                "Category",
                "Категория",
                Vec::<String>::new(),
                true,
            ))
            .namespace(NamespaceDef::new(
                828,
                "Module",
                "Модуль",
                Vec::<String>::new(),
                true,
            ))
            .build()
            .unwrap()
    }

    fn title(text: &str) -> Title {
        Title::parse(text, &config()).unwrap()
    }

    #[test]
    fn template_call_exposes_all_facets() {
        let mut params = BTreeMap::new();
        params.insert("1".to_owned(), "позиционный".to_owned());
        params.insert("имя".to_owned(), "значение".to_owned());
        let call = TemplateCall::new(
            title("Шаблон:Карточка"),
            "карточка".to_owned(),
            params,
            Origin::Input,
            Some(Span { start: 4, end: 42 }),
            true,
        );
        assert_eq!(call.title().text(), "Шаблон:Карточка");
        assert_eq!(call.name_raw(), "карточка");
        assert_eq!(call.param("имя"), Some("значение"));
        assert_eq!(call.param("нет"), None);
        assert_eq!(call.params().len(), 2);
        assert_eq!(call.origin(), &Origin::Input);
        assert_eq!(call.span(), Some(Span { start: 4, end: 42 }));
        assert!(call.resolved());
        assert_eq!(call.clone(), call);
    }

    #[test]
    fn transclusion_origin_names_the_source_page() {
        let origin = Origin::Transclusion(title("Шаблон:Родитель"));
        let call = TemplateCall::new(
            title("Шаблон:Вложенный"),
            "Вложенный".to_owned(),
            BTreeMap::new(),
            origin.clone(),
            None,
            false,
        );
        assert_eq!(call.origin(), &origin);
        assert_eq!(call.span(), None);
        assert!(!call.resolved());
        assert_ne!(origin, Origin::Input);
    }

    #[test]
    fn module_invocation_accessors() {
        let mut args = BTreeMap::new();
        args.insert("1".to_owned(), "x".to_owned());
        let invoke = ModuleInvocation::new(title("Модуль:Math"), "round".to_owned(), args);
        assert_eq!(invoke.module().namespace().id(), 828);
        assert_eq!(invoke.function(), "round");
        assert_eq!(invoke.args().get("1").map(String::as_str), Some("x"));
        assert_eq!(invoke.clone(), invoke);
    }

    #[test]
    fn internal_link_enriches_existence() {
        let mut link = InternalLink::new(
            title("Страница"),
            Some("Раздел".to_owned()),
            Some("метка".to_owned()),
            Some(Span { start: 0, end: 20 }),
        );
        assert_eq!(link.target().text(), "Страница");
        assert_eq!(link.fragment(), Some("Раздел"));
        assert_eq!(link.anchor_text(), Some("метка"));
        assert_eq!(link.exists(), None);
        link.set_exists(true);
        assert_eq!(link.exists(), Some(true));
        assert_eq!(link.span(), Some(Span { start: 0, end: 20 }));
    }

    #[test]
    fn category_link_enriches_facts() {
        let mut cat = CategoryLink::new(title("Категория:Люди"), String::new(), None);
        assert_eq!(cat.category().namespace().id(), 14);
        assert_eq!(cat.sortkey(), "");
        assert_eq!((cat.hidden(), cat.missing()), (None, None));
        cat.set_facts(false, Some(true));
        assert_eq!((cat.hidden(), cat.missing()), (Some(true), Some(false)));
        assert_eq!(cat.span(), None);

        let keyed = CategoryLink::new(title("Категория:Люди"), "Ключ".to_owned(), None);
        assert_eq!(keyed.sortkey(), "Ключ");
    }

    #[test]
    fn interlanguage_link_accessors() {
        let link = InterLanguageLink::new("fr".to_owned(), "Chat".to_owned());
        assert_eq!(link.prefix(), "fr");
        assert_eq!(link.target(), "Chat");
        assert_eq!(link.clone(), link);
        assert!(format!("{link:?}").contains("InterLanguageLink"));
    }

    #[test]
    fn external_link_and_redirect_accessors() {
        let ext = ExternalLink::new(
            "https://example.com/x".to_owned(),
            Some("пример".to_owned()),
            Some(Span { start: 1, end: 30 }),
        );
        assert_eq!(ext.url(), "https://example.com/x");
        assert_eq!(ext.display(), Some("пример"));
        assert_eq!(ext.span().map(|s| s.end), Some(30));

        let redirect = Redirect::new(title("Цель"), Some("Якорь".to_owned()));
        assert_eq!(redirect.target().text(), "Цель");
        assert_eq!(redirect.fragment(), Some("Якорь"));
        assert_eq!(redirect.clone(), redirect);
    }

    #[test]
    fn stats_default_to_zero_and_expose_every_counter() {
        let mut stats = StructuralStats::default();
        assert_eq!(stats.tables(), 0);
        stats.tables = 2;
        stats.table_rows = 10;
        stats.table_cells = 40;
        stats.headings = 5;
        stats.refs = 7;
        stats.list_items = 12;
        stats.images = 3;
        stats.internal_links = 90;
        stats.external_links = 4;
        stats.parser_errors = 1;
        assert_eq!(
            (
                stats.tables(),
                stats.table_rows(),
                stats.table_cells(),
                stats.headings(),
                stats.refs(),
                stats.list_items(),
                stats.images(),
                stats.internal_links(),
                stats.external_links(),
                stats.parser_errors(),
            ),
            (2, 10, 40, 5, 7, 12, 3, 90, 4, 1)
        );
        assert_ne!(stats, StructuralStats::default());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn domain_types_serialize() {
        let call = TemplateCall::new(
            title("Шаблон:X"),
            "X".to_owned(),
            BTreeMap::new(),
            Origin::Input,
            None,
            true,
        );
        let json = serde_json::to_string(&call).unwrap();
        assert!(json.contains("\"name_raw\":\"X\""), "{json}");
        let stats_json = serde_json::to_string(&StructuralStats::default()).unwrap();
        assert!(stats_json.contains("\"tables\":0"), "{stats_json}");
    }
}