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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
#[cfg(feature = "arrayvec")]
mod arrayvec;
mod float;
mod std_impls;
#[cfg(feature = "uuid")]
mod uuid;

use float::WellBehavedF64;
use std::fmt;
use std::iter;
use std::rc::Rc;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum Error {
    #[error("Expected value")]
    ExpectedValue,
    #[error("Expected node")]
    ExpectedNode,
    // TODO include names of actual and expected types
    #[error("Type error")]
    TypeError,
    #[error("Expected integer")]
    ExpectedInt,
    #[error("Variable not found")]
    VarNotFound,
    #[error("Function not found")]
    FnNotFound,
    #[error("Cannot execute a path on a value")]
    PathOnValue,
    #[error("Input is empty in {0}")]
    Empty(&'static str),
    #[error("Conversion failed: {0}")]
    Conversion(#[from] Box<dyn std::error::Error>),
}

pub type Result<T> = std::result::Result<T, Error>;

pub type Node<'a, 'q> = &'a (dyn Queryable<'q> + 'a);

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum Value {
    String(String),
    Int(i64),
    Float(WellBehavedF64),
    Bool(bool),
    Array(Array),
}

pub struct ValueIter<'a>(pub Box<dyn Iterator<Item = Value> + 'a>);

impl<'a> ValueIter<'a> {
    pub fn empty() -> Self {
        ValueIter(Box::new(iter::empty()))
    }

    pub fn once<V: Into<Value>>(val: V) -> Self {
        ValueIter(Box::new(iter::once(val.into())))
    }

    pub fn from_values<T: 'a>(values: impl IntoIterator<Item = T> + 'a) -> Self
    where
        T: Into<Value>,
    {
        ValueIter(Box::from(values.into_iter().map(|v| v.into())))
    }
}

impl<'a> Iterator for ValueIter<'a> {
    type Item = Value;
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

pub struct NodeIter<'a, 'q>(pub Box<dyn Iterator<Item = Node<'a, 'q>> + 'a>);

impl<'a, 'q> NodeIter<'a, 'q> {
    pub fn empty() -> NodeIter<'a, 'q> {
        NodeIter(Box::new(iter::empty()))
    }

    pub fn from_queryables<Q>(queryables: impl IntoIterator<Item = &'a Q> + 'a) -> Self
    where
        Q: Queryable<'q> + 'a,
    {
        NodeIter(Box::from(queryables.into_iter().map(|q| q as _)))
    }
}

impl<'a, 'q> Iterator for NodeIter<'a, 'q> {
    type Item = Node<'a, 'q>;
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

#[derive(Debug)]
pub enum NodeOrValue<'a, 'q> {
    Node(Node<'a, 'q>),
    Value(Value),
}

impl<'a, 'q> NodeOrValue<'a, 'q> {
    pub fn try_into_int(self) -> Result<i64> {
        self.try_into_value()
            .map_err(|_| Error::ExpectedInt)
            .and_then(Value::try_into_int)
    }

    pub fn try_into_value(self) -> Result<Value> {
        match self {
            NodeOrValue::Node(node) => {
                if let Some(data) = node.data() {
                    Ok(data)
                } else {
                    Err(Error::ExpectedValue)
                }
            }
            NodeOrValue::Value(v) => Ok(v),
        }
    }

    pub fn try_into_node(self) -> Result<Node<'a, 'q>> {
        match self {
            NodeOrValue::Node(n) => Ok(n),
            NodeOrValue::Value(_) => Err(Error::ExpectedNode),
        }
    }
}

impl<'a, 'q> From<Value> for NodeOrValue<'a, 'q> {
    fn from(v: Value) -> Self {
        NodeOrValue::Value(v)
    }
}

impl<'a, 'q> From<Node<'a, 'q>> for NodeOrValue<'a, 'q> {
    fn from(n: Node<'a, 'q>) -> Self {
        NodeOrValue::Node(n)
    }
}

impl<'a, 'q> fmt::Display for NodeOrValue<'a, 'q> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            NodeOrValue::Node(node) => write!(f, "{}", node),
            NodeOrValue::Value(value) => write!(f, "{}", value),
        }
    }
}

pub struct NodeOrValueIter<'a, 'q>(Box<dyn Iterator<Item = Result<NodeOrValue<'a, 'q>>> + 'a>);

impl<'a, 'q> NodeOrValueIter<'a, 'q> {
    pub fn empty() -> Self {
        NodeOrValueIter(Box::new(iter::empty()))
    }

    pub fn one(item: Result<NodeOrValue<'a, 'q>>) -> Self {
        NodeOrValueIter(Box::new(iter::once(item)))
    }

    pub fn one_node(node: Node<'a, 'q>) -> Self {
        Self::from_raw(iter::once(node).map(|n| Ok(n.into())))
    }

    pub fn one_value(value: Value) -> Self {
        Self::from_raw(iter::once(value).map(|v| Ok(v.into())))
    }

    pub fn from_queryables<I, Q>(nodes: I) -> Self
    where
        I: IntoIterator<Item = &'a Q> + 'a,
        Q: Queryable<'q> + 'a,
    {
        NodeOrValueIter(Box::new(
            nodes.into_iter().map(|node| Ok(NodeOrValue::Node(node))),
        ))
    }

    pub fn from_nodes<I>(nodes: I) -> Self
    where
        I: IntoIterator<Item = &'a dyn Queryable<'q>> + 'a,
    {
        NodeOrValueIter(Box::new(
            nodes.into_iter().map(|node| Ok(NodeOrValue::Node(node))),
        ))
    }

    pub fn from_values<I>(values: I) -> Self
    where
        I: IntoIterator + 'a,
        I::Item: Into<Value>,
    {
        NodeOrValueIter(Box::new(
            values
                .into_iter()
                .map(|value| Ok(NodeOrValue::Value(value.into()))),
        ))
    }

    pub fn from_raw<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = Result<NodeOrValue<'a, 'q>>> + 'a,
    {
        NodeOrValueIter(Box::new(iter.into_iter()))
    }
}

impl<'a, 'q> Iterator for NodeOrValueIter<'a, 'q> {
    type Item = Result<NodeOrValue<'a, 'q>>;
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

pub trait Queryable<'q> {
    fn keys(&self) -> ValueIter<'_> {
        ValueIter::empty()
    }
    fn member<'a, 'f>(&'a self, _: &'f Value) -> Option<Node<'a, 'q>> {
        None
    }
    fn all<'a>(&'a self) -> NodeOrValueIter<'a, 'q> {
        NodeOrValueIter::empty()
    }
    fn descendants<'a>(&'a self) -> NodeOrValueIter<'a, 'q> {
        if self.all().next().is_some() {
            NodeOrValueIter::from_raw(self.all().chain(self.all().flat_map(|node| {
                if let Ok(node) = node {
                    match node {
                        NodeOrValue::Node(node) => node.descendants(),
                        NodeOrValue::Value(value) => NodeOrValueIter::one_value(value),
                    }
                } else {
                    NodeOrValueIter::empty()
                }
            })))
        } else {
            self.all()
        }
    }
    fn name(&self) -> &'static str;
    fn data(&self) -> Option<Value> {
        None
    }
}

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct Array(pub Rc<[Value]>);

impl Array {
    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl IntoIterator for Array {
    type Item = Value;
    type IntoIter = ArrayIter;
    fn into_iter(self) -> ArrayIter {
        ArrayIter {
            current: 0,
            array: self,
        }
    }
}

pub struct ArrayIter {
    current: usize,
    array: Array,
}

impl Iterator for ArrayIter {
    type Item = Value;
    fn next(&mut self) -> Option<Value> {
        if self.current == self.array.len() {
            None
        } else {
            let index = self.current;
            self.current += 1;
            Some(self.array.0[index].clone())
        }
    }
}

impl fmt::Display for Array {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("{")?;
        let mut it = self.clone().into_iter().peekable();
        while let Some(val) = it.next() {
            let mut format = |args| {
                if it.peek().is_some() {
                    write!(f, "{}, ", args)
                } else {
                    write!(f, "{}", args)
                }
            };
            if let Value::String(s) = val {
                format(format_args!(r#""{}""#, s))
            } else {
                format(format_args!("{}", val))
            }?;
        }
        f.write_str("}")
    }
}

impl Value {
    pub fn try_into_int(self) -> Result<i64> {
        if let Value::Int(i) = self {
            Ok(i)
        } else {
            Err(Error::ExpectedInt)
        }
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Value::String(v) => write!(f, "{}", v),
            Value::Int(v) => write!(f, "{}", v),
            Value::Bool(v) => write!(f, "{}", v),
            Value::Array(v) => write!(f, "{}", v),
            Value::Float(v) => write!(f, "{}", v),
        }
    }
}

impl<'a, 'q> fmt::Display for Node<'a, 'q> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(data) = self.data() {
            write!(f, "{}", data)
        } else {
            write!(f, "[{}]", self.name())
        }
    }
}

impl<'a, 'q> fmt::Debug for &'a dyn Queryable<'q> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{} {:?}]", self.name(), self.data())
    }
}