cedar_policy_core/parser/
err.rs

1/*
2 * Copyright 2022-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use lalrpop_util as lalr;
18use std::fmt::Display;
19use thiserror::Error;
20
21/// For errors during parsing
22#[derive(Debug, Error, PartialEq, Clone)]
23pub enum ParseError {
24    /// Error from the lalrpop parser, no additional information
25    #[error("{0}")]
26    ToCST(String),
27    /// Error in the cst -> ast transform, mostly well-formedness issues
28    #[error("poorly formed: {0}")]
29    ToAST(String),
30    /// (Potentially) multiple errors. This variant includes a "context" for
31    /// what we were trying to do when we encountered these errors
32    #[error("error while {context}: {}", MultipleParseErrors(errs))]
33    WithContext {
34        /// What we were trying to do
35        context: String,
36        /// Error(s) we encountered while doing it
37        errs: Vec<ParseError>,
38    },
39    /// Error concerning restricted expressions
40    #[error(transparent)]
41    RestrictedExpressionError(#[from] crate::ast::RestrictedExpressionError),
42}
43
44impl<L: Display, T: Display, E: Display> From<lalr::ParseError<L, T, E>> for ParseError {
45    fn from(e: lalr::ParseError<L, T, E>) -> Self {
46        ParseError::ToCST(format!("{}", e))
47    }
48}
49
50impl<L: Display, T: Display, E: Display> From<lalr::ErrorRecovery<L, T, E>> for ParseError {
51    fn from(e: lalr::ErrorRecovery<L, T, E>) -> Self {
52        e.error.into()
53    }
54}
55
56/// if you wrap a `Vec<ParseError>` in this struct, it gains a Display impl
57/// that displays each parse error on its own line, indented.
58#[derive(Debug, Error)]
59pub struct ParseErrors(pub Vec<ParseError>);
60
61impl ParseErrors {
62    /// returns a Vec with stringified versions of the ParserErrors
63    pub fn errors_as_strings(&self) -> Vec<String> {
64        self.0
65            .iter()
66            .map(|parser_error| format!("{}", parser_error))
67            .collect()
68    }
69}
70
71impl std::fmt::Display for ParseErrors {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        write!(f, "{}", MultipleParseErrors(&self.0))
74    }
75}
76
77impl From<ParseError> for ParseErrors {
78    fn from(e: ParseError) -> ParseErrors {
79        ParseErrors(vec![e])
80    }
81}
82
83/// Like [`ParseErrors`], but you don't have to own the `Vec`
84#[derive(Debug, Error)]
85pub struct MultipleParseErrors<'a>(pub &'a [ParseError]);
86
87impl<'a> std::fmt::Display for MultipleParseErrors<'a> {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        if self.0.is_empty() {
90            write!(f, "no errors found")
91        } else {
92            for err in self.0 {
93                write!(f, "\n  {}", err)?;
94            }
95            Ok(())
96        }
97    }
98}