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
/*
 * Copyright 2022-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use lalrpop_util as lalr;
use std::fmt::Display;
use thiserror::Error;

/// For errors during parsing
#[derive(Debug, Error, PartialEq, Clone)]
pub enum ParseError {
    /// Error from the lalrpop parser, no additional information
    #[error("{0}")]
    ToCST(String),
    /// Error in the cst -> ast transform, mostly well-formedness issues
    #[error("poorly formed: {0}")]
    ToAST(String),
    /// (Potentially) multiple errors. This variant includes a "context" for
    /// what we were trying to do when we encountered these errors
    #[error("error while {context}: {}", MultipleParseErrors(errs))]
    WithContext {
        /// What we were trying to do
        context: String,
        /// Error(s) we encountered while doing it
        errs: Vec<ParseError>,
    },
    /// Error concerning restricted expressions
    #[error(transparent)]
    RestrictedExpressionError(#[from] crate::ast::RestrictedExpressionError),
}

impl<L: Display, T: Display, E: Display> From<lalr::ParseError<L, T, E>> for ParseError {
    fn from(e: lalr::ParseError<L, T, E>) -> Self {
        ParseError::ToCST(format!("{}", e))
    }
}

impl<L: Display, T: Display, E: Display> From<lalr::ErrorRecovery<L, T, E>> for ParseError {
    fn from(e: lalr::ErrorRecovery<L, T, E>) -> Self {
        e.error.into()
    }
}

/// if you wrap a `Vec<ParseError>` in this struct, it gains a Display impl
/// that displays each parse error on its own line, indented.
#[derive(Debug, Error)]
pub struct ParseErrors(pub Vec<ParseError>);

impl ParseErrors {
    /// returns a Vec with stringified versions of the ParserErrors
    pub fn errors_as_strings(&self) -> Vec<String> {
        self.0
            .iter()
            .map(|parser_error| format!("{}", parser_error))
            .collect()
    }
}

impl std::fmt::Display for ParseErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", MultipleParseErrors(&self.0))
    }
}

impl From<ParseError> for ParseErrors {
    fn from(e: ParseError) -> ParseErrors {
        ParseErrors(vec![e])
    }
}

/// Like [`ParseErrors`], but you don't have to own the `Vec`
#[derive(Debug, Error)]
pub struct MultipleParseErrors<'a>(pub &'a [ParseError]);

impl<'a> std::fmt::Display for MultipleParseErrors<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.0.is_empty() {
            write!(f, "no errors found")
        } else {
            for err in self.0 {
                write!(f, "\n  {}", err)?;
            }
            Ok(())
        }
    }
}

impl From<Vec<ParseError>> for ParseErrors {
    fn from(errs: Vec<ParseError>) -> Self {
        ParseErrors(errs)
    }
}

impl FromIterator<ParseError> for ParseErrors {
    fn from_iter<T: IntoIterator<Item = ParseError>>(errs: T) -> Self {
        ParseErrors(errs.into_iter().collect())
    }
}

impl IntoIterator for ParseErrors {
    type Item = ParseError;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a ParseErrors {
    type Item = &'a ParseError;
    type IntoIter = std::slice::Iter<'a, ParseError>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl<'a> IntoIterator for &'a mut ParseErrors {
    type Item = &'a mut ParseError;
    type IntoIter = std::slice::IterMut<'a, ParseError>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter_mut()
    }
}