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
//! Document-level fact collection: one iterative walk over the parsed block/inline
//! tree gathering internal links, categories, interlanguage links, external links
//! and structural statistics — in document order, without deduplication (the facade
//! dedups for API-parity lists later).

use crate::engine::ast::{Block, DocTree, Inline, InlineContent, ListItem, Table};
use crate::engine::strip::{StripPayload, StripState};
use crate::model::{CategoryLink, ExternalLink, InternalLink, StructuralStats};

use super::plaintext;

/// Everything the extractor reads off one parsed document in a single pass.
#[derive(Debug, Default)]
pub(crate) struct DocumentFacts {
    /// Internal links in document order, not deduplicated; spans are `None` in M2.
    pub(crate) links: Vec<InternalLink>,
    /// Category memberships with raw sort keys (`""` when unspecified —
    /// `DEFAULTSORT` awareness arrives with expansion).
    pub(crate) categories: Vec<CategoryLink>,
    /// Interlanguage links as `(prefix, target)` pairs.
    pub(crate) interlanguage: Vec<(String, String)>,
    /// External links: bracketed ones carry their label as `display`, bare
    /// auto-links carry `None`.
    pub(crate) external_links: Vec<ExternalLink>,
    /// Structural counters; `parser_errors` stays 0 until expansion lands.
    pub(crate) stats: StructuralStats,
}

/// One pending unit of walk work.
enum Work<'a> {
    /// A block still to visit.
    Block(&'a Block),
    /// An inline node still to visit.
    Inline(&'a Inline),
}

/// Walks every block and inline node of `doc` (explicit stack — nested labels,
/// captions, list children and table-cell children included) and collects the
/// document facts.
///
/// Anchor/display text renders through the store-less
/// [`plaintext::label_text`] helper — the contract carries no [`SourceStore`]
/// (`crate::engine::source::SourceStore`), so strip-marker bodies (e.g. a
/// `<nowiki>` inside a label) contribute nothing to those strings in M2.
pub(crate) fn collect(doc: &DocTree, flat: &str, strips: &StripState) -> DocumentFacts {
    let mut facts = DocumentFacts::default();
    let mut stack: Vec<Work<'_>> = doc.blocks.iter().rev().map(Work::Block).collect();
    while let Some(work) = stack.pop() {
        match work {
            Work::Block(block) => visit_block(block, &mut stack, &mut facts),
            Work::Inline(inline) => visit_inline(inline, flat, strips, &mut stack, &mut facts),
        }
    }
    facts
}

/// Visits one block: counts it where relevant and schedules its content (in
/// document order — the stack is LIFO, so everything is pushed reversed).
fn visit_block<'a>(block: &'a Block, stack: &mut Vec<Work<'a>>, facts: &mut DocumentFacts) {
    match block {
        Block::Paragraph { lines } | Block::IndentPre { lines } => {
            for line in lines.iter().rev() {
                push_inlines(stack, content_inlines(line));
            }
        }
        Block::Heading { content, .. } => {
            facts.stats.headings += 1;
            push_inlines(stack, content_inlines(content));
        }
        Block::HorizontalRule => {}
        Block::List { items, .. } => push_list_items(stack, items, facts),
        Block::Table(table) => push_table(stack, table, facts),
    }
}

/// Counts the items of one list level and schedules their content and nested
/// blocks; nested lists count their own items when their block is visited.
fn push_list_items<'a>(
    stack: &mut Vec<Work<'a>>,
    items: &'a [ListItem],
    facts: &mut DocumentFacts,
) {
    for item in items.iter().rev() {
        facts.stats.list_items += 1;
        stack.extend(item.children.iter().rev().map(Work::Block));
        if let Some(content) = &item.content {
            push_inlines(stack, content_inlines(content));
        }
    }
}

/// Counts one table (rows and cells included) and schedules caption, cell content
/// and cell block continuations; nested tables count when their block is visited.
fn push_table<'a>(stack: &mut Vec<Work<'a>>, table: &'a Table, facts: &mut DocumentFacts) {
    facts.stats.tables += 1;
    for row in table.rows.iter().rev() {
        facts.stats.table_rows += 1;
        for cell in row.cells.iter().rev() {
            facts.stats.table_cells += 1;
            stack.extend(cell.children.iter().rev().map(Work::Block));
            push_inlines(stack, content_inlines(&cell.content));
        }
    }
    if let Some(caption) = &table.caption {
        push_inlines(stack, content_inlines(&caption.content));
    }
}

/// Visits one inline node: records its fact (if any) and schedules nested inline
/// vectors (labels, captions, bold/italic children) for the same walk.
fn visit_inline<'a>(
    inline: &'a Inline,
    flat: &str,
    strips: &StripState,
    stack: &mut Vec<Work<'a>>,
    facts: &mut DocumentFacts,
) {
    match inline {
        Inline::Text(_)
        | Inline::Entity { .. }
        | Inline::MagicLink { .. }
        | Inline::HtmlTag { .. }
        | Inline::BehaviorSwitch { .. } => {}
        Inline::Marker { id, .. } => {
            if let Some(StripPayload::ExtTag { name, .. }) = strips.get(*id) {
                facts.stats.refs += u32::from(name.eq_ignore_ascii_case("ref"));
            }
        }
        Inline::Link {
            target,
            fragment,
            label,
            ..
        } => {
            facts.stats.internal_links += 1;
            let anchor = label
                .as_deref()
                .map(|nodes| plaintext::label_text(nodes, flat, strips));
            facts.links.push(InternalLink::new(
                target.clone(),
                fragment.clone(),
                anchor,
                None,
            ));
            if let Some(label) = label {
                push_inlines(stack, label);
            }
        }
        Inline::Category { category, sortkey } => {
            facts.categories.push(CategoryLink::new(
                category.clone(),
                sortkey.clone().unwrap_or_default(),
                None,
            ));
        }
        Inline::InterLanguage {
            prefix,
            target,
            escaped,
        } => {
            // `[[:fr:X]]` renders inline and is neither a langlink nor a local link
            if !*escaped {
                facts.interlanguage.push((prefix.clone(), target.clone()));
            }
        }
        Inline::Image { caption, .. } => {
            facts.stats.images += 1;
            if let Some(caption) = caption {
                push_inlines(stack, caption);
            }
        }
        Inline::ExternalLink { url, label } => {
            facts.stats.external_links += 1;
            let display = label
                .as_deref()
                .map(|nodes| plaintext::label_text(nodes, flat, strips));
            facts
                .external_links
                .push(ExternalLink::new(url.clone(), display, None));
            if let Some(label) = label {
                push_inlines(stack, label);
            }
        }
        Inline::AutoUrl { url, .. } => {
            facts.stats.external_links += 1;
            facts
                .external_links
                .push(ExternalLink::new(url.clone(), None, None));
        }
        Inline::Bold(children) | Inline::Italic(children) => push_inlines(stack, children),
    }
}

/// The parsed nodes of an inline slot; `Raw` (pre-inline-pass) content is ignored
/// defensively — the extractor contract runs after the inline pass.
fn content_inlines(content: &InlineContent) -> &[Inline] {
    match content {
        InlineContent::Parsed(nodes) => nodes,
        InlineContent::Raw(_) => &[],
    }
}

/// Pushes inline nodes reversed so the LIFO walk visits them in document order.
fn push_inlines<'a>(stack: &mut Vec<Work<'a>>, nodes: &'a [Inline]) {
    stack.extend(nodes.iter().rev().map(Work::Inline));
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{NamespaceDef, SiteConfig};
    use crate::engine::ast::{
        ListItemKind, ListKind, MagicLinkKind, TableCaption, TableCell, TableRow, TextRange,
    };
    use crate::engine::pp::PpNodeId;
    use crate::engine::source::{SourceId, Span};
    use crate::engine::strip::{MarkerId, MarkerKind};
    use crate::title::Title;

    fn cfg() -> SiteConfig {
        SiteConfig::builder("ru", "Википедия")
            .namespace(NamespaceDef::main())
            .namespace(NamespaceDef::new(
                14,
                "Category",
                "Категория",
                Vec::<String>::new(),
                true,
            ))
            .namespace(NamespaceDef::new(6, "File", "Файл", ["Изображение"], true))
            .build()
            .unwrap()
    }

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

    /// Grows the flattened text and hands out ranges into it.
    #[derive(Default)]
    struct Flat {
        text: String,
    }

    impl Flat {
        fn r(&mut self, s: &str) -> TextRange {
            let start = self.text.len() as u32;
            self.text.push_str(s);
            TextRange::new(start, self.text.len() as u32)
        }
    }

    fn text_inline(flat: &mut Flat, s: &str) -> Inline {
        Inline::Text(flat.r(s))
    }

    fn bare_link(target: &str) -> Inline {
        Inline::Link {
            target: t(target),
            written: TextRange::new(0, 0),
            fragment: None,
            label: None,
            trail: None,
            pipe_trick: false,
        }
    }

    fn marker(id: MarkerId, kind: MarkerKind) -> Inline {
        Inline::Marker { id, kind }
    }

    fn ext_tag(name: &str) -> StripPayload {
        StripPayload::ExtTag {
            name: name.to_owned(),
            attributes: None,
            body: Some(Span::new(SourceId(0), 0, 0)),
        }
    }

    #[test]
    fn one_walk_collects_every_fact_in_document_order() {
        let mut strips = StripState::new();
        let mut scratch = String::new();
        let ref1 = strips.add(&mut scratch, ext_tag("ref"));
        let ref2 = strips.add(&mut scratch, ext_tag("REF"));
        let math = strips.add(&mut scratch, ext_tag("math"));
        let tpl = strips.add(&mut scratch, StripPayload::Template(PpNodeId(0)));

        let mut flat = Flat::default();

        let heading = Block::Heading {
            level: 2,
            line: TextRange::new(0, 0),
            inner: TextRange::new(0, 0),
            content: InlineContent::Parsed(vec![text_inline(&mut flat, "Заголовок")]),
        };

        let para_links = Block::Paragraph {
            lines: vec![
                InlineContent::Parsed(vec![
                    Inline::Link {
                        target: t("Цель"),
                        written: TextRange::new(0, 0),
                        fragment: Some("Сек".to_owned()),
                        label: Some(vec![text_inline(&mut flat, "якорь")]),
                        trail: None,
                        pipe_trick: false,
                    },
                    text_inline(&mut flat, " и "),
                    Inline::Link {
                        target: t("Другая"),
                        written: TextRange::new(0, 0),
                        fragment: None,
                        label: None,
                        trail: Some(flat.r("ми")),
                        pipe_trick: false,
                    },
                    Inline::Category {
                        category: t("Категория:Люди"),
                        sortkey: Some("ключ".to_owned()),
                    },
                    Inline::Bold(vec![Inline::Category {
                        category: t("Категория:Города"),
                        sortkey: None,
                    }]),
                    Inline::InterLanguage {
                        prefix: "de".to_owned(),
                        target: "Hund".to_owned(),
                        escaped: false,
                    },
                    // escaped: renders inline, so it must NOT become a langlink entry
                    Inline::InterLanguage {
                        prefix: "fr".to_owned(),
                        target: "Chat".to_owned(),
                        escaped: true,
                    },
                ]),
                InlineContent::Raw(TextRange::new(0, 0)),
            ],
        };

        let para_misc = Block::Paragraph {
            lines: vec![InlineContent::Parsed(vec![
                Inline::ExternalLink {
                    url: "https://example.org/a".to_owned(),
                    label: Some(vec![text_inline(&mut flat, "метка")]),
                },
                Inline::ExternalLink {
                    url: "https://example.org/b".to_owned(),
                    label: None,
                },
                Inline::AutoUrl {
                    url: "https://auto.example".to_owned(),
                    range: flat.r("https://auto.example"),
                },
                marker(ref1, MarkerKind::ExtTag),
                marker(math, MarkerKind::ExtTag),
                marker(tpl, MarkerKind::Template),
                marker(MarkerId(99), MarkerKind::ExtTag),
                Inline::Image {
                    target: t("Файл:Пример.jpg"),
                    params: vec![flat.r("thumb")],
                    caption: Some(vec![
                        text_inline(&mut flat, "подпись "),
                        bare_link("Вложенная"),
                    ]),
                },
                Inline::Image {
                    target: t("Файл:Пустой.jpg"),
                    params: vec![],
                    caption: None,
                },
                Inline::HtmlTag {
                    name: "sup".to_owned(),
                    closing: false,
                    self_closing: false,
                    attributes: None,
                },
                Inline::BehaviorSwitch {
                    id: "toc".to_owned(),
                    range: flat.r("__TOC__"),
                },
                Inline::Entity {
                    range: flat.r("&nbsp;"),
                    decoded: '\u{a0}',
                },
                Inline::MagicLink {
                    kind: MagicLinkKind::Rfc,
                    range: flat.r("RFC 1"),
                },
            ])],
        };

        let list = Block::List {
            kind: ListKind::Bullet,
            items: vec![
                ListItem {
                    kind: ListItemKind::Item,
                    content: Some(InlineContent::Parsed(vec![text_inline(&mut flat, "один")])),
                    children: vec![Block::List {
                        kind: ListKind::Ordered,
                        items: vec![ListItem {
                            kind: ListItemKind::Item,
                            content: Some(InlineContent::Parsed(vec![marker(
                                ref2,
                                MarkerKind::ExtTag,
                            )])),
                            children: vec![],
                        }],
                    }],
                },
                ListItem {
                    kind: ListItemKind::Definition,
                    content: None,
                    children: vec![],
                },
            ],
        };

        let nested_table = Table {
            attributes: None,
            caption: None,
            rows: vec![TableRow {
                attributes: None,
                cells: vec![TableCell {
                    header: false,
                    attributes: None,
                    content: InlineContent::Parsed(vec![text_inline(&mut flat, "N")]),
                    children: vec![],
                }],
            }],
            closed: true,
        };
        let table = Block::Table(Table {
            attributes: None,
            caption: Some(TableCaption {
                attributes: None,
                content: InlineContent::Parsed(vec![bare_link("Из подписи")]),
            }),
            rows: vec![TableRow {
                attributes: None,
                cells: vec![
                    TableCell {
                        header: true,
                        attributes: None,
                        content: InlineContent::Parsed(vec![text_inline(&mut flat, "A")]),
                        children: vec![],
                    },
                    TableCell {
                        header: false,
                        attributes: None,
                        content: InlineContent::Parsed(vec![text_inline(&mut flat, "B")]),
                        children: vec![Block::Table(nested_table)],
                    },
                ],
            }],
            closed: true,
        });

        let doc = DocTree {
            blocks: vec![
                heading,
                para_links,
                para_misc,
                list,
                table,
                Block::HorizontalRule,
            ],
        };

        let facts = collect(&doc, &flat.text, &strips);

        let link_keys: Vec<&str> = facts.links.iter().map(|l| l.target().dbkey()).collect();
        assert_eq!(link_keys, ["Цель", "Другая", "Вложенная", "Из_подписи"]);
        assert_eq!(facts.links[0].fragment(), Some("Сек"));
        assert_eq!(facts.links[0].anchor_text(), Some("якорь"));
        assert_eq!(facts.links[1].anchor_text(), None);
        assert_eq!(facts.links[0].span(), None);

        let cat_keys: Vec<(&str, &str)> = facts
            .categories
            .iter()
            .map(|c| (c.category().dbkey(), c.sortkey()))
            .collect();
        assert_eq!(cat_keys, [("Люди", "ключ"), ("Города", "")]);

        assert_eq!(facts.interlanguage, [("de".to_owned(), "Hund".to_owned())]);

        let ext: Vec<(&str, Option<&str>)> = facts
            .external_links
            .iter()
            .map(|e| (e.url(), e.display()))
            .collect();
        assert_eq!(
            ext,
            [
                ("https://example.org/a", Some("метка")),
                ("https://example.org/b", None),
                ("https://auto.example", None),
            ]
        );

        assert_eq!(facts.stats.headings(), 1);
        assert_eq!(facts.stats.internal_links(), 4);
        assert_eq!(facts.stats.external_links(), 3);
        assert_eq!(facts.stats.images(), 2);
        assert_eq!(facts.stats.refs(), 2);
        assert_eq!(facts.stats.list_items(), 3);
        assert_eq!(facts.stats.tables(), 2);
        assert_eq!(facts.stats.table_rows(), 2);
        assert_eq!(facts.stats.table_cells(), 3);
        assert_eq!(facts.stats.parser_errors(), 0);
    }

    #[test]
    fn anchor_text_skips_marker_bodies_without_a_store() {
        let mut strips = StripState::new();
        let mut scratch = String::new();
        let nowiki = strips.add(&mut scratch, ext_tag("nowiki"));

        let mut flat = Flat::default();
        let doc = DocTree {
            blocks: vec![Block::Paragraph {
                lines: vec![InlineContent::Parsed(vec![Inline::Link {
                    target: t("Цель"),
                    written: TextRange::new(0, 0),
                    fragment: None,
                    label: Some(vec![
                        text_inline(&mut flat, "см"),
                        marker(nowiki, MarkerKind::ExtTag),
                    ]),
                    trail: None,
                    pipe_trick: false,
                }])],
            }],
        };

        let facts = collect(&doc, &flat.text, &strips);
        assert_eq!(facts.links[0].anchor_text(), Some("см"));
    }

    #[test]
    fn empty_document_collects_nothing() {
        let facts = collect(&DocTree::default(), "", &StripState::new());
        assert!(facts.links.is_empty());
        assert!(facts.categories.is_empty());
        assert!(facts.interlanguage.is_empty());
        assert!(facts.external_links.is_empty());
        assert_eq!(facts.stats, StructuralStats::default());
    }
}