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
//! # Helper data structure do handle option lookups

use errors::Result;
use {Loc, OptionEntry, RpNumber, WithSpan};

/// Helper for looking up and dealing with options.
pub trait Options {
    type Item: OptionEntry;

    fn items(&self) -> &Vec<Loc<Self::Item>>;

    fn lookup(&self, name: &str) -> Vec<Loc<&Self::Item>> {
        self.items()
            .iter()
            .filter(move |o| o.name() == name)
            .map(|option| Loc::as_ref(&option))
            .collect()
    }

    /// Find all strings matching the given name.
    ///
    /// This enforces that all found values are strings, otherwise the lookup will cause an error.
    fn find_all_strings(&self, name: &str) -> Result<Vec<Loc<String>>> {
        let mut out = Vec::new();

        for s in self.lookup(name) {
            let (value, span) = Loc::take_pair(s);
            let string = value.as_string().with_span(&span)?;
            out.push(Loc::new(string, span));
        }

        Ok(out)
    }

    fn find_all_u32(&self, name: &str) -> Result<Vec<Loc<RpNumber>>> {
        let mut out = Vec::new();

        for s in self.lookup(name) {
            let (value, span) = Loc::take_pair(s);
            let number = value.as_number().with_span(&span)?;
            out.push(Loc::new(number, span));
        }

        Ok(out)
    }

    /// Find all identifiers matching the given name.
    ///
    /// This enforces that all found values are identifiers, otherwise the lookup will cause an
    /// error.
    fn find_all_identifiers(&self, name: &str) -> Result<Vec<Loc<String>>> {
        let mut out = Vec::new();

        for s in self.lookup(name) {
            let (value, span) = Loc::take_pair(s);
            let identifier = value.as_identifier().with_span(&span)?;
            out.push(Loc::new(identifier, span));
        }

        Ok(out)
    }

    /// Optionally find exactly one identifier matching the given name.
    ///
    /// This enforces that all found values are identifiers, otherwise the lookup will cause an
    /// error.
    fn find_one_identifier(&self, name: &str) -> Result<Option<Loc<String>>> {
        Ok(self.find_all_identifiers(name)?.into_iter().next())
    }

    fn find_one_string(&self, name: &str) -> Result<Option<Loc<String>>> {
        Ok(self.find_all_strings(name)?.into_iter().next())
    }

    fn find_one_u32(&self, name: &str) -> Result<Option<Loc<RpNumber>>> {
        Ok(self.find_all_u32(name)?.into_iter().next())
    }
}

impl<T> Options for Vec<Loc<T>>
where
    T: OptionEntry,
{
    type Item = T;

    fn items(&self) -> &Vec<Loc<Self::Item>> {
        self
    }
}