summaryrefslogtreecommitdiff
path: root/src/chomp/ast/error.rs
blob: ea145a769944c600d13959aa5bbef62da29343a8 (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
use super::{Expression, Lambda, NamedExpression};
use proc_macro2::Span;
use std::{
    error::Error,
    fmt::{self, Display},
};

#[derive(Debug)]
pub enum ReductionError {
    CallNotAFunction {
        on: Expression,
        span: Span,
    },
    WrongArgCount {
        lambda: Lambda,
        args: Vec<NamedExpression>,
        span: Span,
    },
}

impl From<ReductionError> for syn::Error {
    fn from(e: ReductionError) -> Self {
        let msg = e.to_string();
        let span = match e {
            ReductionError::CallNotAFunction { span, .. }
            | ReductionError::WrongArgCount { span, .. } => span,
        };

        Self::new(span, msg)
    }
}

impl Display for ReductionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CallNotAFunction { .. } => {
                write!(f, "call expected a function")
            }
            Self::WrongArgCount { lambda, args, .. } => match (lambda.args.len(), args.len()) {
                (1, n) => write!(f, "this function takes 1 argument but {} were supplied", n),
                (m, 1) => write!(f, "this function takes {} arguments but 1 was supplied", m),
                (m, n) => write!(
                    f,
                    "this function takes {} arguments but {} were supplied",
                    m, n
                ),
            },
        }
    }
}

impl Error for ReductionError {}