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
use crate::error::ParserErrorKind;
use crate::level_stack::LevelStack;
use crate::tokenizer::{MultipeekTokenizer, Token, Tokenizer};
use crate::wikitext::{Attribute, Headline, Line, Text, TextFormatting, TextPiece, Wikitext};
use crate::ParserError;
use log::debug;
use std::mem;

pub const MAX_SECTION_DEPTH: usize = 6;

#[cfg(not(test))]
static DO_PARSER_DEBUG_PRINTS: bool = false;
#[cfg(test)]
static DO_PARSER_DEBUG_PRINTS: bool = true;

/// Parse textual wikitext into a semantic representation.
pub fn parse_wikitext(
    wikitext: &str,
    headline: String,
    mut error_consumer: impl FnMut(ParserError),
) -> Wikitext {
    let mut level_stack = LevelStack::new(headline);
    let mut tokenizer = MultipeekTokenizer::new(Tokenizer::new(wikitext));

    loop {
        tokenizer.peek(1);
        if DO_PARSER_DEBUG_PRINTS {
            println!(
                "parse_wikitext tokens: {:?} {:?}",
                tokenizer.repeek(0),
                tokenizer.repeek(1),
            );
        }

        if tokenizer.repeek(0).unwrap().0 == Token::Newline
            && tokenizer.repeek(1).unwrap().0 == Token::Newline
        {
            level_stack.new_paragraph();
            tokenizer.next();
            continue;
        }

        let (token, _) = tokenizer.peek(0);

        if matches!(token, Token::Equals) {
            if let Some(headline) = parse_potential_headline(&mut tokenizer, &mut error_consumer) {
                level_stack.append_headline(headline);
                continue;
            }
        } else if token == &Token::Eof {
            break;
        }

        level_stack.append_line(parse_line(&mut tokenizer, &mut error_consumer));
    }

    Wikitext {
        root_section: level_stack.into_root_section(),
    }
}

fn parse_line(
    tokenizer: &mut MultipeekTokenizer,
    error_consumer: &mut impl FnMut(ParserError),
) -> Line {
    debug_assert_eq!(parse_potential_headline(tokenizer, error_consumer), None);

    let mut list_prefix = String::new();

    // parse list_prefix
    while let token @ (Token::Colon | Token::Semicolon | Token::Star | Token::Sharp) =
        &tokenizer.peek(0).0
    {
        list_prefix.push_str(token.to_str());
        tokenizer.next();
    }

    // parse remaining text
    if !list_prefix.is_empty() {
        let mut text_formatting = TextFormatting::Normal;
        let text = parse_text_until(
            tokenizer,
            error_consumer,
            Text::new(),
            &mut text_formatting,
            &|token: &Token<'_>| matches!(token, Token::Newline | Token::Eof),
        );
        let (_, text_position) = tokenizer.next();
        if text_formatting != TextFormatting::Normal {
            debug!("Line contains unclosed text formatting expression at {text_position:?}");
        }
        Line::List { list_prefix, text }
    } else {
        let mut text_formatting = TextFormatting::Normal;
        let text = parse_text_until(
            tokenizer,
            error_consumer,
            Text::new(),
            &mut text_formatting,
            &|token| matches!(token, Token::Newline | Token::Eof),
        );
        let (_, text_position) = tokenizer.next();
        if text_formatting != TextFormatting::Normal {
            debug!("Line contains unclosed text formatting expression at {text_position:?}");
        }
        Line::Normal { text }
    }
}

fn parse_text_until(
    tokenizer: &mut MultipeekTokenizer,
    error_consumer: &mut impl FnMut(ParserError),
    mut prefix: Text,
    text_formatting: &mut TextFormatting,
    terminator: &impl Fn(&Token<'_>) -> bool,
) -> Text {
    loop {
        if DO_PARSER_DEBUG_PRINTS {
            println!("parse_text_until token: {:?}", tokenizer.peek(0));
        }
        let (token, text_position) = tokenizer.peek(0);
        if terminator(token) {
            break;
        }

        match token {
            token @ (Token::Text(_)
            | Token::Equals
            | Token::Colon
            | Token::Semicolon
            | Token::Star
            | Token::Sharp
            | Token::Newline
            | Token::VerticalBar) => {
                prefix.extend_with_formatted_text(*text_formatting, token.to_str());
                tokenizer.next();
            }
            Token::DoubleOpenBrace => prefix.pieces.push(parse_double_brace_expression(
                tokenizer,
                error_consumer,
                text_formatting,
            )),
            Token::DoubleOpenBracket => {
                prefix = parse_internal_link(tokenizer, error_consumer, prefix, text_formatting);
            }
            Token::NoWikiOpen => {
                prefix = parse_nowiki(tokenizer, error_consumer, prefix, text_formatting);
            }
            Token::DoubleCloseBrace => {
                error_consumer(
                    ParserErrorKind::UnmatchedDoubleCloseBrace.into_parser_error(*text_position),
                );
                prefix.extend_with_formatted_text(*text_formatting, token.to_str());
                tokenizer.next();
            }
            Token::DoubleCloseBracket => {
                error_consumer(
                    ParserErrorKind::UnmatchedDoubleCloseBracket.into_parser_error(*text_position),
                );
                prefix.extend_with_formatted_text(*text_formatting, token.to_str());
                tokenizer.next();
            }
            Token::NoWikiClose => {
                error_consumer(
                    ParserErrorKind::UnmatchedNoWikiClose.into_parser_error(*text_position),
                );
                prefix.extend_with_formatted_text(*text_formatting, token.to_str());
                tokenizer.next();
            }
            Token::Apostrophe => {
                tokenizer.peek(4);
                let apostrophe_prefix_length = (0..5)
                    .take_while(|i| tokenizer.peek(*i).0 == Token::Apostrophe)
                    .count();
                if apostrophe_prefix_length == 1 {
                    prefix.extend_with_formatted_text(*text_formatting, "'");
                    tokenizer.next();
                } else {
                    let apostrophe_prefix_length = if apostrophe_prefix_length == 4 {
                        3
                    } else {
                        apostrophe_prefix_length
                    };
                    *text_formatting = text_formatting.next_formatting(apostrophe_prefix_length);
                    for _ in 0..apostrophe_prefix_length {
                        tokenizer.next();
                    }
                }
            }
            Token::Eof => {
                error_consumer(ParserErrorKind::UnexpectedEof.into_parser_error(*text_position));
                break;
            }
        }
    }

    prefix
}

fn parse_nowiki(
    tokenizer: &mut MultipeekTokenizer,
    error_consumer: &mut impl FnMut(ParserError),
    mut text: Text,
    text_formatting: &TextFormatting,
) -> Text {
    tokenizer.expect(&Token::NoWikiOpen).unwrap();

    loop {
        if DO_PARSER_DEBUG_PRINTS {
            println!("parse_nowiki token: {:?}", tokenizer.peek(0));
        }
        let (token, text_position) = tokenizer.peek(0);

        match token {
            Token::NoWikiClose => {
                tokenizer.next();
                break;
            }
            Token::Eof => {
                error_consumer(
                    ParserErrorKind::UnmatchedNoWikiOpen.into_parser_error(*text_position),
                );
                break;
            }
            token => {
                text.extend_with_formatted_text(*text_formatting, token.to_str());
                tokenizer.next();
            }
        }
    }

    text
}

fn parse_potential_headline(
    tokenizer: &mut MultipeekTokenizer,
    error_consumer: &mut impl FnMut(ParserError),
) -> Option<Headline> {
    if DO_PARSER_DEBUG_PRINTS {
        tokenizer.peek(2 * MAX_SECTION_DEPTH + 2);
        println!(
            "parse_potential_headline initial tokens: {:?}",
            (0..2 * MAX_SECTION_DEPTH + 3)
                .map(|i| tokenizer.repeek(i))
                .collect::<Vec<_>>()
        );
    }

    let text_position = tokenizer.peek(0).1;
    let prefix_length = (0..MAX_SECTION_DEPTH)
        .take_while(|i| tokenizer.peek(*i).0 == Token::Equals)
        .count();
    if prefix_length == 0 {
        return None;
    }

    let mut label = String::new();
    let mut text_limit = prefix_length;
    loop {
        let (token, _) = tokenizer.peek(text_limit);
        if DO_PARSER_DEBUG_PRINTS {
            println!("parse_potential_headline label token: {:?}", token);
        }

        match token {
            Token::Newline | Token::Eof | Token::Equals => break,
            token @ (Token::Text(_) | Token::Apostrophe) => {
                label.push_str(token.to_str());
            }
            _ => return None,
        }

        text_limit += 1;
    }

    tokenizer.peek(text_limit + prefix_length + 1);
    let suffix_length = ((text_limit)..=(text_limit + prefix_length + 1))
        .take_while(|i| tokenizer.repeek(*i).unwrap().0 == Token::Equals)
        .count();

    if prefix_length == suffix_length {
        let whitespace_after_headline =
            match &tokenizer.repeek(text_limit + suffix_length).unwrap().0 {
                Token::Text(text) => {
                    debug_assert!(text.chars().all(|c| c != '\n'));
                    if text.chars().all(|c| c.is_ascii_whitespace()) {
                        if matches!(
                            tokenizer.repeek(text_limit + suffix_length + 1).unwrap().0,
                            Token::Newline | Token::Eof
                        ) {
                            Some(2)
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                }
                Token::Newline | Token::Eof => Some(1),
                _ => None,
            };

        if let Some(whitespace_after_headline) = whitespace_after_headline {
            let label = label.trim().to_string();
            for _ in 0..text_limit + suffix_length + whitespace_after_headline {
                tokenizer.next();
            }

            if prefix_length == 1 {
                error_consumer(
                    ParserErrorKind::SecondRootSection {
                        label: label.clone(),
                    }
                    .into_parser_error(text_position),
                );
            }

            Some(Headline {
                label,
                level: prefix_length.try_into().unwrap(),
            })
        } else {
            None
        }
    } else {
        None
    }
}

fn parse_double_brace_expression(
    tokenizer: &mut MultipeekTokenizer,
    error_consumer: &mut impl FnMut(ParserError),
    text_formatting: &mut TextFormatting,
) -> TextPiece {
    tokenizer.expect(&Token::DoubleOpenBrace).unwrap();
    if DO_PARSER_DEBUG_PRINTS {
        println!(
            "parse_double_brace_expression initial token: {:?}",
            tokenizer.peek(0)
        );
    }
    let tag = parse_tag(tokenizer, error_consumer);
    let mut attributes = Vec::new();

    // parse attributes
    loop {
        if DO_PARSER_DEBUG_PRINTS {
            println!(
                "parse_double_brace_expression token: {:?}",
                tokenizer.peek(0)
            );
        }
        let (token, text_position) = tokenizer.peek(0);
        match token {
            Token::VerticalBar => {
                attributes.push(parse_attribute(tokenizer, error_consumer, text_formatting))
            }
            Token::DoubleCloseBrace => {
                tokenizer.next();
                break;
            }
            token @ (Token::Text(_)
            | Token::Equals
            | Token::DoubleOpenBrace
            | Token::DoubleOpenBracket
            | Token::NoWikiOpen
            | Token::DoubleCloseBracket
            | Token::NoWikiClose
            | Token::Apostrophe
            | Token::Newline
            | Token::Colon
            | Token::Semicolon
            | Token::Star
            | Token::Sharp) => {
                error_consumer(
                    ParserErrorKind::UnexpectedToken {
                        expected: "| or }}".to_string(),
                        actual: token.to_string(),
                    }
                    .into_parser_error(*text_position),
                );
                tokenizer.next();
            }
            Token::Eof => {
                error_consumer(
                    ParserErrorKind::UnmatchedDoubleOpenBrace.into_parser_error(*text_position),
                );
                break;
            }
        }
    }

    TextPiece::DoubleBraceExpression { tag, attributes }
}

fn parse_tag(
    tokenizer: &mut MultipeekTokenizer,
    error_consumer: &mut impl FnMut(ParserError),
) -> Text {
    if DO_PARSER_DEBUG_PRINTS {
        println!("parse_tag initial token: {:?}", tokenizer.peek(0));
    }
    let text_position = tokenizer.peek(0).1;
    let mut text_formatting = TextFormatting::Normal;
    let mut tag = Text::new();

    loop {
        tag = parse_text_until(
            tokenizer,
            error_consumer,
            tag,
            &mut text_formatting,
            &|token: &Token<'_>| {
                matches!(
                    token,
                    Token::DoubleCloseBrace
                        | Token::VerticalBar
                        | Token::DoubleOpenBracket
                        | Token::Eof
                )
            },
        );
        let (token, text_position) = tokenizer.peek(0);
        match token {
            Token::DoubleCloseBrace | Token::VerticalBar => break,
            token @ Token::DoubleOpenBracket => {
                error_consumer(
                    ParserErrorKind::UnexpectedTokenInTag {
                        token: token.to_string(),
                    }
                    .into_parser_error(*text_position),
                );
                tag.extend_with_formatted_text(text_formatting, token.to_str());
                tokenizer.next();
            }
            Token::Eof => {
                error_consumer(
                    ParserErrorKind::UnmatchedDoubleOpenBrace.into_parser_error(*text_position),
                );
                break;
            }
            token => unreachable!("Not a stop token above: {token:?}"),
        }
    }

    if text_formatting != TextFormatting::Normal {
        error_consumer(
            ParserErrorKind::UnclosedTextFormatting {
                formatting: text_formatting,
            }
            .into_parser_error(text_position),
        );
    }

    tag.trim_self();
    tag
}

fn parse_attribute(
    tokenizer: &mut MultipeekTokenizer,
    error_consumer: &mut impl FnMut(ParserError),
    text_formatting: &mut TextFormatting,
) -> Attribute {
    tokenizer.expect(&Token::VerticalBar).unwrap();
    let mut name = Some(String::new());
    let mut value = Text::new();

    // parse name
    loop {
        if DO_PARSER_DEBUG_PRINTS {
            println!("parse_attribute name token: {:?}", tokenizer.peek(0));
        }
        let (token, text_position) = tokenizer.peek(0);
        match token {
            Token::Text(text) => {
                name.as_mut().unwrap().push_str(text);
                tokenizer.next();
            }
            Token::Newline => {
                name.as_mut().unwrap().push('\n');
                tokenizer.next();
            }
            Token::Equals => {
                tokenizer.next();
                break;
            }
            Token::DoubleOpenBrace
            | Token::DoubleOpenBracket
            | Token::NoWikiOpen
            | Token::DoubleCloseBrace
            | Token::NoWikiClose
            | Token::VerticalBar
            | Token::Apostrophe
            | Token::Colon
            | Token::Semicolon
            | Token::Star
            | Token::Sharp => {
                value.pieces.push(TextPiece::Text {
                    text: name.take().unwrap(),
                    formatting: *text_formatting,
                });
                break;
            }
            token @ Token::DoubleCloseBracket => {
                error_consumer(
                    ParserErrorKind::UnexpectedTokenInParameter {
                        token: token.to_string(),
                    }
                    .into_parser_error(*text_position),
                );
                name.as_mut().unwrap().push_str(token.to_str());
                tokenizer.next();
            }
            Token::Eof => {
                error_consumer(
                    ParserErrorKind::UnmatchedDoubleOpenBrace.into_parser_error(*text_position),
                );
                break;
            }
        }
    }

    // parse value
    let mut value = parse_text_until(
        tokenizer,
        error_consumer,
        value,
        text_formatting,
        &|token: &Token<'_>| matches!(token, Token::VerticalBar | Token::DoubleCloseBrace),
    );

    // whitespace is stripped from named attribute names and values, but not from unnamed attributes
    if let Some(name) = &mut name {
        *name = name.trim().to_string();
        value.trim_self();
    }

    Attribute { name, value }
}

fn parse_internal_link(
    tokenizer: &mut MultipeekTokenizer,
    error_consumer: &mut impl FnMut(ParserError),
    mut text: Text,
    text_formatting: &mut TextFormatting,
) -> Text {
    tokenizer.expect(&Token::DoubleOpenBracket).unwrap();
    let surrounding_depth = if tokenizer.peek(0).0 == Token::DoubleOpenBracket {
        tokenizer.next();
        1
    } else {
        0
    };
    let mut target = Text::new();
    let mut options = Vec::new();
    let mut label = None;

    // parse target
    target = parse_text_until(
        tokenizer,
        error_consumer,
        target,
        text_formatting,
        &|token: &Token<'_>| {
            matches!(
                token,
                Token::DoubleCloseBracket
                    | Token::VerticalBar
                    | Token::DoubleCloseBrace
                    | Token::DoubleOpenBracket
                    | Token::Newline
                    | Token::Eof
            )
        },
    );
    if DO_PARSER_DEBUG_PRINTS {
        println!("parse_link target token: {:?}", tokenizer.peek(0));
    }
    let (token, text_position) = tokenizer.peek(0);
    match token {
        token @ (Token::Text(_)
        | Token::Colon
        | Token::Sharp
        | Token::Semicolon
        | Token::Star
        | Token::Apostrophe
        | Token::Equals
        | Token::DoubleOpenBrace
        | Token::NoWikiOpen
        | Token::NoWikiClose) => {
            unreachable!("Not a stop token above: {token:?}");
        }
        Token::DoubleCloseBracket => {
            tokenizer.next();
        }
        Token::VerticalBar => {
            tokenizer.next();
            label = Some(Text::new());
        }
        token @ (Token::Newline | Token::Eof) => {
            error_consumer(
                ParserErrorKind::UnmatchedDoubleOpenBracket.into_parser_error(*text_position),
            );
            if token != &Token::Eof {
                text.extend_with_formatted_text(*text_formatting, token.to_str());
            }
            tokenizer.next();
        }
        token @ (Token::DoubleCloseBrace | Token::DoubleOpenBracket) => {
            error_consumer(
                ParserErrorKind::UnexpectedTokenInLink {
                    token: token.to_string(),
                }
                .into_parser_error(*text_position),
            );
            text.extend_with_formatted_text(*text_formatting, token.to_str());
            tokenizer.next();
        }
    }

    // parse options and label
    let label = label.map(|mut label| {
        let mut link_finished = false;

        // parse options
        loop {
            if DO_PARSER_DEBUG_PRINTS {
                println!("parse_link options token: {:?}", tokenizer.peek(0));
            }
            let (token, text_position) = tokenizer.peek(0);
            match token {
                token @ (Token::Equals | Token::Text(_)) => {
                    label.extend_with_formatted_text(*text_formatting, token.to_str());
                    tokenizer.next();
                }
                Token::VerticalBar => {
                    let mut new_label = Text::new();
                    mem::swap(&mut label, &mut new_label);
                    if new_label.pieces.is_empty() {
                        options.push(Default::default());
                    } else {
                        options.push(new_label);
                    }
                    tokenizer.next();
                }
                Token::DoubleCloseBracket => {
                    tokenizer.next();
                    link_finished = true;
                    break;
                }
                Token::Apostrophe => {
                    label = parse_text_until(
                        tokenizer,
                        error_consumer,
                        label,
                        text_formatting,
                        &|token| !matches!(token, Token::Apostrophe),
                    );
                }
                Token::DoubleOpenBrace
                | Token::DoubleOpenBracket
                | Token::NoWikiOpen
                | Token::NoWikiClose
                | Token::Colon
                | Token::Semicolon
                | Token::Star
                | Token::Sharp
                | Token::Newline => {
                    break;
                }
                token @ Token::DoubleCloseBrace => {
                    error_consumer(
                        ParserErrorKind::UnexpectedTokenInLinkLabel {
                            token: token.to_string(),
                        }
                        .into_parser_error(*text_position),
                    );
                    label.extend_with_formatted_text(*text_formatting, token.to_str());
                    tokenizer.next();
                }
                Token::Eof => {
                    error_consumer(
                        ParserErrorKind::UnmatchedDoubleOpenBracket
                            .into_parser_error(*text_position),
                    );
                    break;
                }
            }
        }

        if !link_finished {
            // parse label
            loop {
                label = parse_text_until(
                    tokenizer,
                    error_consumer,
                    label,
                    text_formatting,
                    &|token: &Token<'_>| {
                        matches!(
                            token,
                            Token::DoubleCloseBracket
                                | Token::VerticalBar
                                | Token::Newline
                                | Token::Eof
                        )
                    },
                );

                let (token, text_position) = tokenizer.peek(0);
                match token {
                    Token::DoubleCloseBracket => {
                        tokenizer.next();
                        break;
                    }
                    token @ Token::VerticalBar => {
                        error_consumer(
                            ParserErrorKind::UnexpectedTokenInLinkLabel {
                                token: token.to_string(),
                            }
                            .into_parser_error(*text_position),
                        );
                        label.extend_with_formatted_text(*text_formatting, token.to_str());
                        tokenizer.next();
                    }
                    Token::Newline | Token::Eof => {
                        error_consumer(
                            ParserErrorKind::UnmatchedDoubleOpenBracket
                                .into_parser_error(*text_position),
                        );
                        tokenizer.next();
                        break;
                    }
                    token => unreachable!("Not a stop token above: {token:?}"),
                }
            }

            label
        } else {
            label
        }
    });

    // update text
    for _ in 0..surrounding_depth {
        text.extend_with_formatted_text(*text_formatting, "[[");
    }
    text.pieces.push(TextPiece::InternalLink {
        target,
        options,
        label,
    });
    for _ in 0..surrounding_depth {
        let (token, text_position) = tokenizer.peek(0);
        match token {
            token @ Token::DoubleCloseBracket => {
                text.extend_with_formatted_text(*text_formatting, token.to_str());
                tokenizer.next();
            }
            _ => {
                error_consumer(
                    ParserErrorKind::UnmatchedDoubleOpenBracket.into_parser_error(*text_position),
                );
            }
        }
    }

    text
}