leo_grammar/errors/
parser.rs

1// Copyright (C) 2019-2020 Aleo Systems Inc.
2// This file is part of the Leo library.
3
4// The Leo library is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// The Leo library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
16
17use crate::{ast::Rule, errors::SyntaxError};
18
19use pest::error::Error;
20use std::path::{Path, PathBuf};
21
22#[derive(Debug, Error)]
23pub enum ParserError {
24    #[error("{}: {}", _0, _1)]
25    Crate(&'static str, String),
26
27    #[error("Cannot read from the provided file path - {:?}", _0)]
28    FileReadError(PathBuf),
29
30    #[error("{}", _0)]
31    JsonError(#[from] serde_json::error::Error),
32
33    #[error("{}", _0)]
34    SyntaxError(#[from] SyntaxError),
35
36    #[error("Unable to construct program abstract syntax tree")]
37    SyntaxTreeError,
38}
39
40impl ParserError {
41    pub fn set_path(&mut self, path: &Path) {
42        if let ParserError::SyntaxError(error) = self {
43            let new_error: Error<Rule> = match error {
44                SyntaxError::Error(error) => {
45                    let new_error = error.clone();
46                    new_error.with_path(path.to_str().unwrap())
47                }
48            };
49
50            tracing::error!("{}", new_error);
51
52            *error = SyntaxError::Error(new_error);
53        }
54    }
55}
56
57impl From<Error<Rule>> for ParserError {
58    fn from(error: Error<Rule>) -> Self {
59        ParserError::SyntaxError(SyntaxError::from(error))
60    }
61}
62
63impl From<std::io::Error> for ParserError {
64    fn from(error: std::io::Error) -> Self {
65        ParserError::Crate("std::io", error.to_string())
66    }
67}