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
use core::fmt;
use std::error::Error;

use crate::utils;
use crate::debug::{DebugSymbol, SourceError};


pub type CompileResult<T> = Result<T, CompileError>;

#[derive(Debug)]
pub enum ErrorKind {
    CantAssignImmutable,
    CantAssignNonLocal,
    TupleLenMismatch,
    CantUpdateAssignTuple,
    InternalLimit(&'static str),
}

#[derive(Debug)]
pub struct CompileError {
    kind: ErrorKind,
    symbol: Option<DebugSymbol>,
    cause: Option<Box<dyn Error>>,
}

impl CompileError {
    pub fn new(kind: ErrorKind) -> Self {
        Self { kind, symbol: None, cause: None }
    }
    
    pub fn with_symbol(mut self, symbol: DebugSymbol) -> Self {
        self.symbol.get_or_insert(symbol); self 
    }
    
    pub fn caused_by(mut self, error: impl Error + 'static) -> Self {
        self.cause.replace(Box::new(error)); self
    }
    
    pub fn kind(&self) -> &ErrorKind { &self.kind }
}

impl From<ErrorKind> for CompileError {
    fn from(kind: ErrorKind) -> Self {
        Self::new(kind)
    }
}

impl Error for CompileError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.cause.as_ref().map(|o| o.as_ref())
    }
}

impl SourceError for CompileError {
    fn debug_symbol(&self) -> Option<&DebugSymbol> { self.symbol.as_ref() }
}

impl fmt::Display for CompileError {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        
        let message = match self.kind() {
            ErrorKind::CantAssignImmutable => "can't assign to immutable local variable",
            ErrorKind::CantAssignNonLocal => "can't assign to a non-local variable without the \"nonlocal\" keyword",
            ErrorKind::TupleLenMismatch => "can't assign tuples of different lengths",
            ErrorKind::CantUpdateAssignTuple => "can't use update-assigment when assigning to a tuple",
            ErrorKind::InternalLimit(message) => message,
        };
        
        utils::format_error(fmt, "Compile error", Some(message), self.source())
    }
}