summaryrefslogtreecommitdiff
path: root/src/syntax/expr.rs
blob: b4c0dfaa3801a8aae12abecc56bc36886780ee93 (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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
use std::fmt::{self, Display, Formatter};

use crate::error::Errors;
use crate::size::Size;
use super::func::{keys::Key, values::Value};
use super::span::{Span, Spanned};
use super::tokens::is_identifier;


/// An argument or return value.
#[derive(Clone, PartialEq)]
pub enum Expr {
    Ident(Ident),
    Str(String),
    Number(f64),
    Size(Size),
    Bool(bool),
    Tuple(Tuple),
    Object(Object),
}

impl Expr {
    pub fn name(&self) -> &'static str {
        use Expr::*;
        match self {
            Ident(_) => "identifier",
            Str(_) => "string",
            Number(_) => "number",
            Size(_) => "size",
            Bool(_) => "bool",
            Tuple(_) => "tuple",
            Object(_) => "object",
        }
    }
}

/// An identifier.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Ident(pub String);

impl Ident {
    pub fn new<S>(ident: S) -> Option<Ident> where S: AsRef<str> + Into<String> {
        if is_identifier(ident.as_ref()) {
            Some(Ident(ident.into()))
        } else {
            None
        }
    }

    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

/// A sequence of expressions.
#[derive(Clone, PartialEq)]
pub struct Tuple {
    pub items: Vec<Spanned<Expr>>,
}

impl Tuple {
    pub fn new() -> Tuple {
        Tuple { items: vec![] }
    }

    pub fn add(&mut self, item: Spanned<Expr>) {
        self.items.push(item);
    }

    pub fn get<V: Value>(&mut self, errors: &mut Errors) -> Option<V::Output> {
        while !self.items.is_empty() {
            let expr = self.items.remove(0);
            let span = expr.span;
            match V::parse(expr) {
                Ok(output) => return Some(output),
                Err(err) => errors.push(Spanned { v: err, span }),
            }
        }
        None
    }

    pub fn get_all<'a, V: Value>(&'a mut self, errors: &'a mut Errors)
    -> impl Iterator<Item=V::Output> + 'a {
        self.items.drain(..).filter_map(move |expr| {
            let span = expr.span;
            match V::parse(expr) {
                Ok(output) => Some(output),
                Err(err) => { errors.push(Spanned { v: err, span }); None }
            }
        })
    }
}

/// A key-value collection of identifiers and associated expressions.
#[derive(Clone, PartialEq)]
pub struct Object {
    pub pairs: Vec<Pair>,
}

/// A key-value pair in an object.
#[derive(Clone, PartialEq)]
pub struct Pair {
    pub key: Spanned<Ident>,
    pub value: Spanned<Expr>,
}

impl Object {
    pub fn new() -> Object {
        Object { pairs: vec![] }
    }

    pub fn add(&mut self, key: Spanned<Ident>, value: Spanned<Expr>) {
        self.pairs.push(Pair { key, value });
    }

    pub fn add_pair(&mut self, pair: Pair) {
        self.pairs.push(pair);
    }

    pub fn get<V: Value>(&mut self, errors: &mut Errors, key: &str) -> Option<V::Output> {
        let index = self.pairs.iter().position(|pair| pair.key.v.as_str() == key)?;
        self.get_index::<V>(errors, index)
    }

    pub fn get_with_key<K: Key, V: Value>(
        &mut self,
        errors: &mut Errors,
    ) -> Option<(K::Output, V::Output)> {
        for (index, pair) in self.pairs.iter().enumerate() {
            let key = Spanned { v: pair.key.v.as_str(), span: pair.key.span };
            if let Some(key) = K::parse(key) {
                return self.get_index::<V>(errors, index).map(|value| (key, value));
            }
        }
        None
    }

    pub fn get_all<'a, K: Key, V: Value>(
        &'a mut self,
        errors: &'a mut Errors,
    ) -> impl Iterator<Item=(K::Output, V::Output)> + 'a {
        let mut index = 0;
        std::iter::from_fn(move || {
            if index < self.pairs.len() {
                let key = &self.pairs[index].key;
                let key = Spanned { v: key.v.as_str(), span: key.span };

                Some(if let Some(key) = K::parse(key) {
                    self.get_index::<V>(errors, index).map(|v| (key, v))
                } else {
                    index += 1;
                    None
                })
            } else {
                None
            }
        }).filter_map(|x| x)
    }

    pub fn get_all_spanned<'a, K: Key + 'a, V: Value + 'a>(
        &'a mut self,
        errors: &'a mut Errors,
    ) -> impl Iterator<Item=Spanned<(K::Output, V::Output)>> + 'a {
        self.get_all::<Spanned<K>, Spanned<V>>(errors)
            .map(|(k, v)| Spanned::new((k.v, v.v), Span::merge(k.span, v.span)))
    }

    fn get_index<V: Value>(&mut self, errors: &mut Errors, index: usize) -> Option<V::Output> {
        let expr = self.pairs.remove(index).value;
        let span = expr.span;
        match V::parse(expr) {
            Ok(output) => Some(output),
            Err(err) => { errors.push(Spanned { v: err, span }); None }
        }
    }
}

impl Display for Expr {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        use Expr::*;
        match self {
            Ident(i) => write!(f, "{}", i),
            Str(s) => write!(f, "{:?}", s),
            Number(n) => write!(f, "{}", n),
            Size(s) => write!(f, "{}", s),
            Bool(b) => write!(f, "{}", b),
            Tuple(t) => write!(f, "{}", t),
            Object(o) => write!(f, "{}", o),
        }
    }
}

impl Display for Ident {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Display for Tuple {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "(")?;

        let mut first = true;
        for item in &self.items {
            if !first {
                write!(f, ", ")?;
            }
            write!(f, "{}", item.v)?;
            first = false;
        }

        write!(f, ")")
    }
}

impl Display for Object {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        if self.pairs.len() == 0 {
            return write!(f, "{{}}");
        }

        write!(f, "{{ ")?;

        let mut first = true;
        for pair in &self.pairs {
            if !first {
                write!(f, ", ")?;
            }
            write!(f, "{}", pair)?;
            first = false;
        }

        write!(f, " }}")
    }
}

impl Display for Pair {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{}: {}", self.key.v, self.value.v)
    }
}

debug_display!(Expr);
debug_display!(Ident);
debug_display!(Tuple);
debug_display!(Object);
debug_display!(Pair);