envuse_parser/errors/
program_error.rs1use super::super::envuse::program::Program;
2use super::parser_error::ParseError;
3use crate::parser::span::Span;
4use crate::syntax_error::SyntaxError;
5use crate::utils::display_syntax::{DisplaySyntax, DisplaySyntaxDebugOptions};
6use std::error::Error;
7use std::fmt;
8
9#[derive(Debug)]
10pub struct ProgramError {
11 pub message: String,
12 pub span: Option<Span>,
13 pub source: String,
14 pub location: Option<String>,
15 pub cause: Option<Box<dyn Error>>,
16}
17
18impl ProgramError {
19 pub fn get_message(&self) -> String {
20 let mut debug_options = DisplaySyntaxDebugOptions::new();
21 debug_options.location = self.location.clone();
22
23 match &self.cause {
24 Some(error) if error.is::<SyntaxError>() => {
25 let syntax_error = error.downcast_ref::<SyntaxError>().unwrap();
26 let display_syntax = DisplaySyntax::new(
27 format!("SyntaxError: {}", syntax_error.message),
28 syntax_error.span.clone(),
29 );
30
31 display_syntax.debug_payload_configurable(&self.source, &debug_options)
32 }
33 Some(error) if error.is::<ParseError>() => {
34 let parse_error = error.downcast_ref::<ParseError>().unwrap();
35 let display_syntax = DisplaySyntax::new(
36 format!("ParseError: {}", parse_error.message),
37 parse_error.span.clone(),
38 );
39
40 display_syntax.debug_payload_configurable(&self.source, &debug_options)
41 }
42 _ => self.message.to_string(),
43 }
44 }
45}
46
47impl fmt::Display for ProgramError {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 write!(f, "{}", self.get_message().to_string())
50 }
51}
52
53impl std::error::Error for ProgramError {}
54
55impl From<(&Program, &str)> for ProgramError {
56 fn from(arg: (&Program, &str)) -> Self {
57 let (program, str) = arg;
58 ProgramError {
59 message: String::from(str),
60 span: None,
61 source: program.source.clone(),
62 location: program.location.clone(),
63 cause: None,
64 }
65 }
66}