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
use crate::lexer::{SpannedToken, Token};
use crate::num::ParseIntError;
use crate::string::UnescapeError;
use logos::Span;
use miette::{Diagnostic, SourceOffset, SourceSpan};
use std::error::Error;
use std::fmt::{self, Debug, Display, Formatter};
use std::num::ParseFloatError;
use std::str::ParseBoolError;
use thiserror::Error;

/// Any error that occurred while trying to parse the php literal
#[derive(Error, Debug, Clone, Diagnostic)]
pub enum ParseError {
    #[error(transparent)]
    #[diagnostic(transparent)]
    /// A token that wasn't expected was found while parsing
    UnexpectedToken(#[from] UnexpectedTokenError),
    #[error(transparent)]
    #[diagnostic(transparent)]
    /// A malformed integer, float, boolean or string literal was found
    InvalidPrimitive(#[from] PrimitiveError),
    #[error("Array key not valid for this position")]
    #[diagnostic(transparent)]
    /// An array key was found that is invalid for this position
    UnexpectedArrayKey(ArrayKeyError),
    #[error(transparent)]
    #[diagnostic(transparent)]
    /// Trailing characters after parsing
    TrailingCharacters(#[from] TrailingError),
    #[error("{0}")]
    #[diagnostic(code(php_literal_parser::serde))]
    /// Error while populating serde type
    Serde(String),
}

impl serde::de::Error for ParseError {
    fn custom<T>(msg: T) -> Self
    where
        T: Display,
    {
        ParseError::Serde(msg.to_string())
    }
}

/// A token that wasn't expected was found while parsing
#[derive(Debug, Clone, Diagnostic)]
#[diagnostic(code(php_literal_parser::unexpected_token))]
pub struct UnexpectedTokenError {
    #[source_code]
    src: String,
    #[label("Expected {}", self.expected)]
    err_span: SourceSpan,
    pub expected: TokenList,
    pub found: Option<Token>,
}

impl UnexpectedTokenError {
    pub fn new(
        expected: &[Token],
        found: Option<Token>,
        src: String,
        err_span: SourceSpan,
    ) -> Self {
        UnexpectedTokenError {
            src,
            err_span,
            expected: expected.into(),
            found,
        }
    }
}

/// List of expected tokens
#[derive(Clone)]
pub struct TokenList(Vec<Token>);

impl Debug for TokenList {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl From<&[Token]> for TokenList {
    fn from(list: &[Token]) -> Self {
        TokenList(list.into())
    }
}

impl Display for TokenList {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self.0.len() {
            0 => {}
            1 => write!(f, "{}", self.0[0])?,
            _ => {
                let mut tokens = self.0[0..self.0.len() - 1].iter();
                write!(f, "{}", tokens.next().unwrap())?;
                for token in tokens {
                    write!(f, ", {}", token)?;
                }
                if self.0.len() > 1 {
                    write!(f, " or {}", self.0.last().unwrap())?;
                }
            }
        }
        Ok(())
    }
}

impl Display for UnexpectedTokenError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.found {
            Some(Token::Error) => {
                write!(f, "No valid token found, expected one of {}", self.expected)
            }
            Some(token) => write!(
                f,
                "Unexpected token, found {} expected one of {}",
                token, self.expected
            ),
            None => write!(
                f,
                "Unexpected end of input expected one of {}",
                self.expected
            ),
        }
    }
}

impl Error for UnexpectedTokenError {}

/// A malformed integer, float, boolean or string literal was found
#[derive(Debug, Clone, Error, Diagnostic)]
#[diagnostic(code(php_literal_parser::invalid_primitive))]
#[error("{kind}")]
pub struct PrimitiveError {
    #[source_code]
    src: String,
    #[label("{}", self.kind.desc())]
    err_span: SourceSpan,
    pub kind: PrimitiveErrorKind,
}

#[derive(Error, Debug, Clone)]
pub enum PrimitiveErrorKind {
    #[error("Invalid boolean literal: {0}")]
    InvalidBoolLiteral(#[from] ParseBoolError),
    #[error("Invalid integer literal: {0}")]
    InvalidIntLiteral(#[from] ParseIntError),
    #[error("Invalid float literal: {0}")]
    InvalidFloatLiteral(#[from] ParseFloatError),
    #[error("Invalid string literal")]
    InvalidStringLiteral,
}

impl PrimitiveErrorKind {
    pub fn desc(&self) -> &str {
        match self {
            PrimitiveErrorKind::InvalidBoolLiteral(_) => "Not a boolean",
            PrimitiveErrorKind::InvalidIntLiteral(err) => err.desc(),
            PrimitiveErrorKind::InvalidFloatLiteral(_) => "Not a valid float",
            PrimitiveErrorKind::InvalidStringLiteral => "Not a string literal",
        }
    }
}

impl From<UnescapeError> for PrimitiveErrorKind {
    fn from(_: UnescapeError) -> Self {
        PrimitiveErrorKind::InvalidStringLiteral
    }
}

#[derive(Debug, Clone, Error, Diagnostic)]
#[diagnostic(code(php_literal_parser::invalid_array_key))]
#[error("Invalid array key")]
pub struct ArrayKeyError {
    #[source_code]
    src: String,
    #[label("{}", self.kind)]
    err_span: SourceSpan,
    kind: ArrayKeyErrorKind,
}

#[derive(Debug, Clone)]
pub enum ArrayKeyErrorKind {
    IntegerExpected,
    NonConsecutive,
}

impl Display for ArrayKeyErrorKind {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                ArrayKeyErrorKind::IntegerExpected => "Expected integer key",
                ArrayKeyErrorKind::NonConsecutive => "Expected consecutive integer key",
            }
        )
    }
}

impl ArrayKeyError {
    pub fn new(kind: ArrayKeyErrorKind, source: &str, err_span: Span) -> Self {
        ArrayKeyError {
            src: source.into(),
            err_span: map_span(&err_span),
            kind,
        }
    }
}

#[derive(Debug, Clone, Error, Diagnostic)]
#[diagnostic(code(php_literal_parser::trailing))]
#[error("Trailing characters after parsing")]
pub struct TrailingError {
    #[source_code]
    src: String,
    #[label("end of parsed value")]
    err_span: SourceSpan,
}

impl TrailingError {
    pub fn new(source: &str, err_span: Span) -> Self {
        TrailingError {
            src: source.into(),
            err_span: map_span(&err_span),
        }
    }
}

pub trait ExpectToken<'source> {
    fn expect_token(
        self,
        expected: &[Token],
        source: &str,
    ) -> Result<SpannedToken<'source>, ParseError>;
}

impl<'source> ExpectToken<'source> for Option<SpannedToken<'source>> {
    fn expect_token(
        self,
        expected: &[Token],
        source: &str,
    ) -> Result<SpannedToken<'source>, ParseError> {
        self.ok_or_else(|| {
            UnexpectedTokenError::new(
                expected,
                None,
                source.into(),
                map_span(&(source.len()..source.len())),
            )
            .into()
        })
        .and_then(|token| token.expect_token(expected, source))
    }
}

impl<'a, 'source> ExpectToken<'source> for Option<&'a SpannedToken<'source>> {
    fn expect_token(
        self,
        expected: &[Token],
        source: &str,
    ) -> Result<SpannedToken<'source>, ParseError> {
        self.ok_or_else(|| {
            UnexpectedTokenError::new(
                expected,
                None,
                source.into(),
                map_span(&(source.len()..source.len())),
            )
            .into()
        })
        .and_then(|token| token.clone().expect_token(expected, source))
    }
}

impl<'source> ExpectToken<'source> for SpannedToken<'source> {
    fn expect_token(
        self,
        expected: &[Token],
        source: &str,
    ) -> Result<SpannedToken<'source>, ParseError> {
        if expected.iter().any(|expect| self.token.eq(expect)) {
            Ok(self)
        } else {
            Err(UnexpectedTokenError::new(
                expected,
                Some(self.token),
                source.into(),
                map_span(&self.span),
            )
            .into())
        }
    }
}

fn map_span(span: &Span) -> SourceSpan {
    SourceSpan::new(
        SourceOffset::from(span.start),
        SourceOffset::from(span.end - span.start),
    )
}

pub trait ResultExt<T> {
    fn with_span(self, span: Span, source: &str) -> Result<T, ParseError>;
}

impl<T, E: Into<PrimitiveErrorKind>> ResultExt<T> for Result<T, E> {
    fn with_span(self, span: Span, source: &str) -> Result<T, ParseError> {
        self.map_err(|error| {
            PrimitiveError {
                src: source.into(),
                err_span: map_span(&span),
                kind: error.into(),
            }
            .into()
        })
    }
}