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
use std::error::Error;
use std::fmt::Display;

use crate::tokenizer::TextPosition;
use crate::wikitext::TextFormatting;

pub type Result<T> = std::result::Result<T, ParserError>;

/// Error type of this crate.
#[derive(Debug, Eq, PartialEq)]
pub struct ParserError {
    /// The kind of error.
    pub kind: ParserErrorKind,
    /// The position of the error in text.
    pub position: TextPosition,
    /// Further information about the error.
    pub annotations: Vec<String>,
}

/// The kind of parser error.
#[derive(Debug, Eq, PartialEq)]
pub enum ParserErrorKind {
    /// Found a second root section, but only one is allowed.
    SecondRootSection {
        /// The label of the second root section.
        label: String,
    },

    /// Found a section at a level that is deeper than supported.
    SectionLevelTooDeep {
        /// The too deep level.
        level: usize,
    },

    /// Found a double close brace that does not match any opened one.
    UnmatchedDoubleCloseBrace,

    /// Found a double open brace that does not match any closed one.
    UnmatchedDoubleOpenBrace,

    /// Found a double close bracket that does not match any opened one.
    UnmatchedDoubleCloseBracket,

    /// Found a double open bracket that does not match any closed one.
    UnmatchedDoubleOpenBracket,

    /// Found a `</nowiki>` that does not match any `<nowiki>`.
    UnmatchedNoWikiClose,

    /// Found a `<nowiki>` that does not match any `</nowiki>`.
    UnmatchedNoWikiOpen,

    /// A tag contains a token that does not belong there.
    UnexpectedTokenInTag {
        /// The unexpected token.
        token: String,
    },

    /// A parameter contains a token that does not belong there.
    UnexpectedTokenInParameter {
        /// The unexpected token.
        token: String,
    },

    /// A link contains a token that does not belong there.
    UnexpectedTokenInLink {
        /// The unexpected token.
        token: String,
    },

    /// A link label contains a token that does not belong there.
    UnexpectedTokenInLinkLabel {
        /// The unexpected token.
        token: String,
    },

    /// A formatted piece of text contains a token that does not belong there.
    UnexpectedTokenInFormattedText {
        /// The unexpected token.
        token: String,
    },

    /// A link label contains a token that does not belong there.
    UnexpectedTokenInListItem {
        /// The unexpected token.
        token: String,
    },

    /// A token was found at a place where it does not belong.
    UnexpectedToken {
        /// The expected token, or a list of possible expected tokens.
        expected: String,
        /// The token that was found.
        actual: String,
    },

    /// A text formatting expression was not closed.
    UnclosedTextFormatting {
        /// The unclosed formatting expression.
        formatting: TextFormatting,
    },

    /// The end of file was found, but further tokens were expected.
    UnexpectedEof,
}

impl Display for ParserErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ParserErrorKind::SecondRootSection { label } => {
                write!(f, "found second root section {label:?}")
            }
            ParserErrorKind::SectionLevelTooDeep { level } => {
                write!(f, "found a section of a too deep level {level}")
            }
            ParserErrorKind::UnmatchedDoubleCloseBrace => {
                write!(f, "found an unmatched double closing brace }}}}")
            }
            ParserErrorKind::UnmatchedDoubleOpenBrace => {
                write!(f, "found an unmatched double open brace {{{{")
            }
            ParserErrorKind::UnmatchedDoubleCloseBracket => {
                write!(f, "found an unmatched double close bracket ]]")
            }
            ParserErrorKind::UnmatchedDoubleOpenBracket => {
                write!(f, "found an unmatched double open bracket [[")
            }
            ParserErrorKind::UnmatchedNoWikiClose => {
                write!(f, "found an unmatched nowiki close tag </nowiki>")
            }
            ParserErrorKind::UnmatchedNoWikiOpen => {
                write!(f, "found an unmatched nowiki open tag <nowiki>")
            }
            ParserErrorKind::UnexpectedTokenInTag { token } => {
                write!(f, "found an unexpected token {token:?} in a tag")
            }
            ParserErrorKind::UnexpectedTokenInParameter { token } => {
                write!(f, "found an unexpected token {token:?} in a parameter")
            }
            ParserErrorKind::UnexpectedTokenInLink { token } => {
                write!(f, "found an unexpected token {token:?} in a link")
            }
            ParserErrorKind::UnexpectedTokenInLinkLabel { token } => {
                write!(f, "found an unexpected token {token:?} in a link label")
            }
            ParserErrorKind::UnexpectedTokenInFormattedText { token } => {
                write!(f, "found an unexpected token {token:?} in formatted text")
            }
            ParserErrorKind::UnexpectedTokenInListItem { token } => {
                write!(f, "found an unexpected token {token:?} in a list item")
            }
            ParserErrorKind::UnexpectedToken { expected, actual } => write!(
                f,
                "found an unexpected token {actual:?} where {expected:?} was expected"
            ),
            ParserErrorKind::UnclosedTextFormatting { formatting } => write!(
                f,
                "found an unclosed text formatting expression {formatting}:?"
            ),
            ParserErrorKind::UnexpectedEof => {
                write!(f, "the file ended, but we expected more content")
            }
        }
    }
}

impl Display for ParserError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} at line {}, column {}",
            self.kind, self.position.line, self.position.column
        )?;

        if !self.annotations.is_empty() {
            write!(f, "; additional information: [")?;
            let mut once = true;
            for annotation in &self.annotations {
                if once {
                    once = false;
                } else {
                    write!(f, ", ")?;
                }
                write!(f, "{annotation}")?;
            }
            write!(f, "]")?;
        }

        Ok(())
    }
}

impl Error for ParserError {}

impl ParserError {
    /// Add the given annotation to the error.
    pub fn annotate(&mut self, annotation: String) {
        self.annotations.push(annotation);
    }

    /// Add the given annotation to the error.
    pub fn annotate_self(mut self, annotation: String) -> Self {
        self.annotations.push(annotation);
        self
    }
}

impl ParserErrorKind {
    pub(crate) fn into_parser_error(self, position: TextPosition) -> ParserError {
        ParserError {
            kind: self,
            position,
            annotations: Default::default(),
        }
    }
}