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
79
80
81
82
83
84
85
86
87
88
89
90
91
use {
    crate::{Env, Result, Value},
    std::{ops, vec},
};

/// The `Args` struct makes it easier to work with arguments when
/// writing Hatter functions in Rust.
#[derive(Debug)]
pub struct Args<'e> {
    pub env: &'e mut Env,
    args: Vec<Value>,
}

impl<'e> ops::Deref for Args<'e> {
    type Target = Vec<Value>;
    fn deref(&self) -> &Self::Target {
        &self.args
    }
}

impl<'e> ops::DerefMut for Args<'e> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.args
    }
}

impl<'e> IntoIterator for Args<'e> {
    type Item = Value;
    type IntoIter = vec::IntoIter<Value>;
    fn into_iter(self) -> Self::IntoIter {
        self.args.into_iter()
    }
}

impl<'e> Args<'e> {
    pub fn new(env: &'e mut Env, args: Vec<Value>) -> Args<'e> {
        Args { env, args }
    }

    pub fn get(&self, idx: usize) -> Option<&Value> {
        self.args.get(idx)
    }

    /// Like `get()` but returns an error.
    pub fn need(&self, idx: usize) -> Result<Value> {
        self.args.get(idx).map(Value::clone).ok_or(error_kind!(
            ArgNotFound,
            "Argument Not Found: {}",
            idx
        ))
    }

    /// Errors if the arg doesn't exist or isn't a Number.
    pub fn need_number(&self, idx: usize) -> Result<f64> {
        if let Value::Number(num) = self.need(idx)? {
            Ok(num)
        } else {
            Err(error_kind!(
                WrongArgType,
                "Expected Number, got: {:?}",
                self.need(idx)?
            ))
        }
    }

    /// Errors if the arg doesn't exist or isn't a String.
    pub fn need_string(&self, idx: usize) -> Result<&str> {
        if let Some(Value::String(s)) = self.args.get(idx) {
            Ok(s.to_str())
        } else {
            Err(error_kind!(
                WrongArgType,
                "Expected String, got: {:?}",
                self.need(idx)?
            ))
        }
    }

    /// Errors if the arg doesn't exist or isn't a String.
    pub fn need_list(&self, idx: usize) -> Result<Value> {
        if let Some(li @ Value::List(..)) = self.args.get(idx) {
            Ok(li.clone())
        } else {
            Err(error_kind!(
                WrongArgType,
                "Expected List, got: {:?}",
                self.need(idx)?
            ))
        }
    }
}