cynic_parser/
errors.rs

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
#[cfg(feature = "report")]
mod report;

use std::fmt;

#[cfg(feature = "report")]
pub use report::Report;

use crate::{
    lexer,
    parser::AdditionalErrors,
    type_system::{DirectiveLocation, MalformedDirectiveLocation},
    Span,
};

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
    /// Generated by the parser when it encounters a token (or EOF) it did not
    /// expect.
    InvalidToken { location: usize },

    /// Generated by the parser when it encounters an EOF it did not expect.
    UnrecognizedEof {
        /// The end of the final token
        location: usize,

        /// The set of expected tokens: these names are taken from the
        /// grammar and hence may not necessarily be suitable for
        /// presenting to the user.
        expected: Vec<String>,
    },

    /// Generated by the parser when it encounters a token it did not expect.
    UnrecognizedToken {
        /// The unexpected token of type `T` with a span given by the two `L` values.
        token: (usize, String, usize),

        /// The set of expected tokens: these names are taken from the
        /// grammar and hence may not necessarily be suitable for
        /// presenting to the user.
        expected: Vec<String>,
    },

    /// Generated by the parser when it encounters additional, unexpected tokens.
    ExtraToken { token: (usize, String, usize) },

    /// Lexing errors
    Lexical(lexer::LexicalError),

    /// Malformed string literal
    MalformedStringLiteral(crate::common::MalformedStringError),

    /// Malformed directive location
    MalformedDirectiveLocation(usize, String, usize),

    /// Variable found in const position
    VariableInConstPosition(usize, String, usize),
}

impl Error {
    pub fn span(&self) -> Span {
        match self {
            Error::InvalidToken { location } => Span::new(*location, *location),
            Error::UnrecognizedEof { location, .. } => Span::new(*location, *location),
            Error::UnrecognizedToken {
                token: (start, _, end),
                ..
            } => Span::new(*start, *end),
            Error::ExtraToken {
                token: (start, _, end),
                ..
            } => Span::new(*start, *end),
            Error::Lexical(error) => error.span(),
            Error::MalformedStringLiteral(error) => error.span(),
            Error::MalformedDirectiveLocation(lhs, _, rhs) => Span::new(*lhs, *rhs),
            Error::VariableInConstPosition(lhs, _, rhs) => Span::new(*lhs, *rhs),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::InvalidToken { .. }
            | Error::UnrecognizedEof { .. }
            | Error::UnrecognizedToken { .. }
            | Error::ExtraToken { .. }
            | Error::MalformedStringLiteral(..)
            | Error::MalformedDirectiveLocation(..)
            | Error::VariableInConstPosition(..) => None,
            Error::Lexical(error) => Some(error),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::InvalidToken { location: _ } => {
                write!(f, "invalid token")
            }
            Error::UnrecognizedEof {
                location: _,
                expected,
            } => {
                write!(f, "unexpected end of file (expected one of ")?;
                for (i, item) in expected.iter().enumerate() {
                    if i != 1 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{item}")?;
                }
                write!(f, ")")
            }
            Error::UnrecognizedToken {
                token: (_, token, _),
                expected,
            } => {
                write!(f, "unexpected {token} token (expected one of ")?;
                for (i, item) in expected.iter().enumerate() {
                    if i != 1 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{item}")?;
                }
                write!(f, ")")
            }
            Error::ExtraToken {
                token: (_, token, _),
            } => {
                write!(f, "found a {token} after the expected end of the document")
            }
            Error::Lexical(error) => {
                write!(f, "{error}")
            }
            Error::MalformedStringLiteral(error) => {
                write!(f, "malformed string literal: {error}")
            }
            Error::MalformedDirectiveLocation(_, location, _) => {
                write!(
                    f,
                    "unknown directive location: {location}. expected one of "
                )?;

                for (i, location) in DirectiveLocation::all_locations().iter().enumerate() {
                    if i != 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{location}")?;
                }
                Ok(())
            }
            Error::VariableInConstPosition(_, name, _) => {
                write!(
                    f,
                    "the variable ${name} was found in a position that does not allow variables"
                )?;
                Ok(())
            }
        }
    }
}

impl From<lalrpop_util::ParseError<usize, lexer::Token<'_>, AdditionalErrors>> for Error {
    fn from(value: lalrpop_util::ParseError<usize, lexer::Token<'_>, AdditionalErrors>) -> Self {
        use lalrpop_util::ParseError;
        match value {
            ParseError::InvalidToken { location } => Error::InvalidToken { location },
            ParseError::UnrecognizedEof { location, expected } => {
                Error::UnrecognizedEof { location, expected }
            }
            ParseError::UnrecognizedToken {
                token: (lspan, token, rspan),
                expected,
            } => Error::UnrecognizedToken {
                token: (lspan, token.to_string(), rspan),
                expected,
            },
            ParseError::ExtraToken {
                token: (lspan, token, rspan),
            } => Error::ExtraToken {
                token: (lspan, token.to_string(), rspan),
            },
            ParseError::User {
                error: AdditionalErrors::Lexical(error),
            } => Error::Lexical(error),
            ParseError::User {
                error: AdditionalErrors::MalformedString(error),
            } => Error::MalformedStringLiteral(error),
            ParseError::User {
                error: AdditionalErrors::MalformedDirectiveLocation(lhs, location, rhs),
            } => Error::MalformedDirectiveLocation(lhs, location, rhs),
            ParseError::User {
                error: AdditionalErrors::VariableInConstPosition(lhs, name, rhs),
            } => Error::MalformedDirectiveLocation(lhs, name, rhs),
        }
    }
}

impl MalformedDirectiveLocation {
    pub(crate) fn into_lalrpop_error<'a>(
        self,
        (lhs, rhs): (usize, usize),
    ) -> lalrpop_util::ParseError<usize, lexer::Token<'a>, AdditionalErrors> {
        lalrpop_util::ParseError::User {
            error: AdditionalErrors::MalformedDirectiveLocation(lhs, self.0, rhs),
        }
    }
}