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

/// Multipurpose error type.
#[derive(Debug)]
pub enum Error {
    Syntax {
        exp: String,
    },
    Type {
        expected: &'static str,
        given: String,
    },
    UndefinedSymbol {
        sym: String,
    },
    Arity {
        expected: usize,
        given: usize,
    },
    ArityMin {
        expected: usize,
        given: usize,
    },
    ArityMax {
        expected: usize,
        given: usize,
    },
    NotAList {
        atom: String,
    },
    NullList,
    NotAProcedure {
        exp: String,
    },
    Index {
        i: usize,
    },
    IO(::std::fmt::Error),
}

impl ::std::error::Error for Error {}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::Syntax { exp } => write!(f, "Could not parse expression: {}", exp),
            Error::Type { expected, given } => {
                write!(f, "Type error: expected {}, got {}", expected, given)
            }
            Error::UndefinedSymbol { sym } => write!(f, "Undefined symbol: {}", sym),
            Error::Arity { expected, given } => write!(
                f,
                "Arity mismatch: expected {} parameters, got {}.",
                expected, given
            ),
            Error::ArityMin { expected, given } => write!(
                f,
                "Arity mismatch: expected at least {} parameters, got {}.",
                expected, given
            ),
            Error::ArityMax { expected, given } => write!(
                f,
                "Arity mismatch: expected at most {} parameters, got {}.",
                expected, given
            ),
            Error::NotAList { atom } => write!(f, "Expected a list, got {}", atom),
            Error::NullList => write!(f, "Expected a pair, got null."),
            Error::NotAProcedure { exp } => write!(f, "{} is not a procedure.", exp),
            Error::Index { i } => write!(f, "Tried to access invalid index: [{}]", i),
            Error::IO(err) => write!(f, "I/O error: {}", err),
        }
    }
}