summaryrefslogtreecommitdiff
path: root/src/eval/args.rs
blob: d11deac601732a09f2d4a47074bca2d0fa129e7f (plain) (blame)
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
//! Simplifies argument parsing.

use std::mem;

use super::{Convert, RefKey, ValueDict};
use crate::layout::LayoutContext;
use crate::syntax::{SpanWith, Spanned};

/// A wrapper around a dictionary value that simplifies argument parsing in
/// functions.
pub struct Args(pub Spanned<ValueDict>);

impl Args {
    /// Retrieve and remove the argument associated with the given key if there
    /// is any.
    ///
    /// Generates an error if the key exists, but the value can't be converted
    /// into the type `T`.
    pub fn get<'a, K, T>(&mut self, ctx: &mut LayoutContext, key: K) -> Option<T>
    where
        K: Into<RefKey<'a>>,
        T: Convert,
    {
        self.0.v.remove(key).and_then(|entry| {
            let span = entry.value.span;
            let (result, diag) = T::convert(entry.value);
            if let Some(diag) = diag {
                ctx.f.diags.push(diag.span_with(span))
            }
            result.ok()
        })
    }

    /// This is the same as [`get`], except that it generates an error about a
    /// missing argument with the given `name` if the key does not exist.
    ///
    /// [`get`]: #method.get
    pub fn need<'a, K, T>(
        &mut self,
        ctx: &mut LayoutContext,
        key: K,
        name: &str,
    ) -> Option<T>
    where
        K: Into<RefKey<'a>>,
        T: Convert,
    {
        match self.0.v.remove(key) {
            Some(entry) => {
                let span = entry.value.span;
                let (result, diag) = T::convert(entry.value);
                if let Some(diag) = diag {
                    ctx.f.diags.push(diag.span_with(span))
                }
                result.ok()
            }
            None => {
                ctx.f.diags.push(error!(self.0.span, "missing argument: {}", name));
                None
            }
        }
    }

    /// Retrieve and remove the first matching positional argument.
    pub fn find<T>(&mut self) -> Option<T>
    where
        T: Convert,
    {
        for (&key, entry) in self.0.v.nums_mut() {
            let span = entry.value.span;
            match T::convert(mem::take(&mut entry.value)).0 {
                Ok(t) => {
                    self.0.v.remove(key);
                    return Some(t);
                }
                Err(v) => entry.value = v.span_with(span),
            }
        }
        None
    }

    /// Retrieve and remove all matching positional arguments.
    pub fn find_all<T>(&mut self) -> impl Iterator<Item = T> + '_
    where
        T: Convert,
    {
        let mut skip = 0;
        std::iter::from_fn(move || {
            for (&key, entry) in self.0.v.nums_mut().skip(skip) {
                let span = entry.value.span;
                match T::convert(mem::take(&mut entry.value)).0 {
                    Ok(t) => {
                        self.0.v.remove(key);
                        return Some(t);
                    }
                    Err(v) => entry.value = v.span_with(span),
                }
                skip += 1;
            }
            None
        })
    }

    /// Retrieve and remove all matching keyword arguments.
    pub fn find_all_str<T>(&mut self) -> impl Iterator<Item = (String, T)> + '_
    where
        T: Convert,
    {
        let mut skip = 0;
        std::iter::from_fn(move || {
            for (key, entry) in self.0.v.strs_mut().skip(skip) {
                let span = entry.value.span;
                match T::convert(mem::take(&mut entry.value)).0 {
                    Ok(t) => {
                        let key = key.clone();
                        self.0.v.remove(&key);
                        return Some((key, t));
                    }
                    Err(v) => entry.value = v.span_with(span),
                }
                skip += 1;
            }

            None
        })
    }

    /// Generated _unexpected argument_ errors for all remaining entries.
    pub fn done(&self, ctx: &mut LayoutContext) {
        for entry in self.0.v.values() {
            let span = entry.key_span.join(entry.value.span);
            ctx.diag(error!(span, "unexpected argument"));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::super::{Dict, SpannedEntry, Value};
    use super::*;

    fn entry(value: Value) -> SpannedEntry<Value> {
        SpannedEntry::value(Spanned::zero(value))
    }

    #[test]
    fn test_args_find() {
        let mut args = Args(Spanned::zero(Dict::new()));
        args.0.v.insert(1, entry(Value::Bool(false)));
        args.0.v.insert(2, entry(Value::Str("hi".to_string())));
        assert_eq!(args.find::<String>(), Some("hi".to_string()));
        assert_eq!(args.0.v.len(), 1);
        assert_eq!(args.find::<bool>(), Some(false));
        assert!(args.0.v.is_empty());
    }

    #[test]
    fn test_args_find_all() {
        let mut args = Args(Spanned::zero(Dict::new()));
        args.0.v.insert(1, entry(Value::Bool(false)));
        args.0.v.insert(3, entry(Value::Float(0.0)));
        args.0.v.insert(7, entry(Value::Bool(true)));
        assert_eq!(args.find_all::<bool>().collect::<Vec<_>>(), [false, true]);
        assert_eq!(args.0.v.len(), 1);
        assert_eq!(args.0.v[3].value.v, Value::Float(0.0));
    }
}