summaryrefslogtreecommitdiff
path: root/matrix-lang/src/value/exception.rs
blob: 0df6f5c0479f6eefe37aef592e2b490fc4812c25 (plain)
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
use std::{fmt::{Debug, Display}, error::Error};
use crate::prelude::*;

#[macro_export]
macro_rules! exception {
    ($type:expr) => {
        $crate::prelude::Exception::new($type)
    };
    ($type:expr, $($arg:tt)*) => {
        $crate::prelude::Exception::msg($type, format!($($arg)*).as_str())
    };
}

pub const HASH_EXCEPTION: &'static str = "hash";
pub const VALUE_EXCEPTION: &'static str = "value";
pub const PARSE_EXCEPTION: &'static str = "parse";
pub const COMPILE_EXCEPTION: &'static str = "compile";
pub const RUNTIME_EXCEPTION: &'static str = "runtime";
pub const BINARY_EXECPTION: &'static str = "binary";
pub const IO_EXECPTION: &'static str = "io";

#[derive(Clone)]
pub struct Exception(Gc<ExceptionInner>);

#[derive(Clone)]
struct ExceptionInner {
    ty: Rc<str>,
    msg: Rc<str>,
    trace: Vec<(Rc<str>, Position)>
}

impl Exception {
    pub fn msg(ty: &str, msg: &str) -> Self {
        Self(Gc::new(ExceptionInner { ty: ty.into(), msg: msg.into(), trace: Vec::new() }))
    }

    pub fn pos(mut self, pos: Position) -> Self {
        self.0.trace.push((
                Rc::from("<root>"),
                pos
        ));
        self
    }

    pub fn trace(mut self, block: Rc<str>, pos: Position) -> Self {
        self.0.trace.push((
                block,
                pos
        ));
        self
    }
}

impl Display for Exception {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let ty = self.0.ty.as_ref();
        let msg = self.0.msg.as_ref();
        write!(f, "{}\n    Type <{}>", msg, ty)?;
        for (block, pos) in self.0.trace.iter() {
            write!(f, "\n    In {block} at {pos}\n")?;
        }
        Ok(())
    }
}

impl Debug for Exception {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[Exception {}]", self.0.ty.as_ref())
    }
}

impl Error for Exception {}

impl<T> From<Exception> for Result<T> {
    fn from(value: Exception) -> Self {
        Err(value)
    }
}