jaq_core/
path.rs

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
//! Paths and their parts.

use crate::box_iter::{box_once, flat_map_with, map_with, then, BoxIter};
use crate::val::{ValR, ValT, ValX, ValXs};
use alloc::{boxed::Box, vec::Vec};

/// Path such as `.[].a?[1:]`.
#[derive(Clone, Debug)]
pub struct Path<F>(pub Vec<(Part<F>, Opt)>);

/// Part of a path, such as `[]`, `a`, and `[1:]` in `.[].a?[1:]`.
#[derive(Clone, Debug)]
pub enum Part<I> {
    /// Access arrays with integer and objects with string indices
    Index(I),
    /// Iterate over arrays with optional range bounds and over objects without bounds
    /// If both are `None`, return iterator over whole array/object
    Range(Option<I>, Option<I>),
}

/// Optionality of a path part, i.e. whether `?` is present.
///
/// For example, `[] | .a` fails with an error, while `[] | .a?` returns nothing.
/// By default, path parts are *essential*, meaning that they fail.
/// Annotating them with `?` makes them *optional*.
#[derive(Copy, Clone, Debug)]
pub enum Opt {
    /// Return nothing if the input cannot be accessed with the path
    Optional,
    /// Fail if the input cannot be accessed with the path
    Essential,
}

impl<I> Default for Part<I> {
    fn default() -> Self {
        Self::Range(None, None)
    }
}

impl Opt {
    /// If `self` is optional, return `x`, else fail with `f(x)`.
    pub fn fail<T, E>(self, x: T, f: impl FnOnce(T) -> E) -> Result<T, E> {
        match self {
            Self::Optional => Ok(x),
            Self::Essential => Err(f(x)),
        }
    }
}

impl<'a, U: Clone + 'a, E: Clone + 'a, T: Clone + IntoIterator<Item = Result<U, E>> + 'a> Path<T> {
    pub(crate) fn explode(self) -> impl Iterator<Item = Result<Path<U>, E>> + 'a {
        Path(Vec::new())
            .combinations(self.0.into_iter())
            .map(Path::transpose)
    }
}

impl<'a, U: Clone + 'a> Path<U> {
    fn combinations<I, F>(self, mut iter: I) -> BoxIter<'a, Self>
    where
        I: Iterator<Item = (Part<F>, Opt)> + Clone + 'a,
        F: IntoIterator<Item = U> + Clone + 'a,
    {
        if let Some((part, opt)) = iter.next() {
            let parts = part.into_iter();
            flat_map_with(parts, (self, iter), move |part, (mut prev, iter)| {
                prev.0.push((part, opt));
                prev.combinations(iter)
            })
        } else {
            box_once(self)
        }
    }
}

impl<'a, V: ValT + 'a> Path<V> {
    pub(crate) fn run(self, v: V) -> BoxIter<'a, ValR<V>> {
        run(self.0.into_iter(), v)
    }

    pub(crate) fn update<F>(mut self, v: V, f: F) -> ValX<'a, V>
    where
        F: Fn(V) -> ValXs<'a, V>,
    {
        if let Some(last) = self.0.pop() {
            update(self.0.into_iter(), last, v, &f)
        } else {
            // should be unreachable
            Ok(v)
        }
    }
}

fn run<'a, V: ValT + 'a, I>(mut iter: I, val: V) -> BoxIter<'a, ValR<V>>
where
    I: Iterator<Item = (Part<V>, Opt)> + Clone + 'a,
{
    if let Some((part, opt)) = iter.next() {
        let essential = matches!(opt, Opt::Essential);
        let ys = part.run(val).filter(move |v| essential || v.is_ok());
        flat_map_with(ys, iter, move |v, iter| then(v, |v| run(iter, v)))
    } else {
        box_once(Ok(val))
    }
}

fn update<'a, V: ValT + 'a, P, F>(mut iter: P, last: (Part<V>, Opt), v: V, f: &F) -> ValX<'a, V>
where
    P: Iterator<Item = (Part<V>, Opt)> + Clone,
    F: Fn(V) -> ValXs<'a, V>,
{
    if let Some((part, opt)) = iter.next() {
        use core::iter::once;
        part.update(v, opt, |v| once(update(iter.clone(), last.clone(), v, f)))
    } else {
        last.0.update(v, last.1, f)
    }
}

impl<'a, V: ValT + 'a> Part<V> {
    fn run(&self, v: V) -> impl Iterator<Item = ValR<V>> + 'a {
        match self {
            Self::Index(idx) => box_once(v.index(idx)),
            Self::Range(None, None) => Box::new(v.values()),
            Self::Range(from, upto) => box_once(v.range(from.as_ref()..upto.as_ref())),
        }
    }

    fn update<F, I>(&self, v: V, opt: Opt, f: F) -> ValX<'a, V>
    where
        F: Fn(V) -> I,
        I: Iterator<Item = ValX<'a, V>>,
    {
        match self {
            Self::Index(idx) => v.map_index(idx, opt, f),
            Self::Range(None, None) => v.map_values(opt, f),
            Self::Range(from, upto) => v.map_range(from.as_ref()..upto.as_ref(), opt, f),
        }
    }
}

impl<'a, U: Clone + 'a, F: IntoIterator<Item = U> + Clone + 'a> Part<F> {
    fn into_iter(self) -> BoxIter<'a, Part<U>> {
        use Part::{Index, Range};
        match self {
            Index(i) => Box::new(i.into_iter().map(Index)),
            Range(None, None) => box_once(Range(None, None)),
            Range(Some(from), None) => {
                Box::new(from.into_iter().map(|from| Range(Some(from), None)))
            }
            Range(None, Some(upto)) => {
                Box::new(upto.into_iter().map(|upto| Range(None, Some(upto))))
            }
            Range(Some(from), Some(upto)) => {
                Box::new(flat_map_with(from.into_iter(), upto, move |from, upto| {
                    map_with(upto.into_iter(), from, move |upto, from| {
                        Range(Some(from), Some(upto))
                    })
                }))
            }
        }
    }
}

impl<T> Path<T> {
    pub(crate) fn map_ref<'a, U>(&'a self, mut f: impl FnMut(&'a T) -> U) -> Path<U> {
        let path = self.0.iter();
        let path = path.map(move |(part, opt)| (part.as_ref().map(&mut f), *opt));
        Path(path.collect())
    }
}

impl<T> Part<T> {
    /// Apply a function to the contained indices.
    pub(crate) fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> Part<U> {
        use Part::{Index, Range};
        match self {
            Index(i) => Index(f(i)),
            Range(from, upto) => Range(from.map(&mut f), upto.map(&mut f)),
        }
    }
}

impl<T, E> Path<Result<T, E>> {
    fn transpose(self) -> Result<Path<T>, E> {
        self.0
            .into_iter()
            .map(|(part, opt)| Ok((part.transpose()?, opt)))
            .collect::<Result<_, _>>()
            .map(Path)
    }
}

impl<T, E> Part<Result<T, E>> {
    fn transpose(self) -> Result<Part<T>, E> {
        match self {
            Self::Index(i) => Ok(Part::Index(i?)),
            Self::Range(from, upto) => Ok(Part::Range(from.transpose()?, upto.transpose()?)),
        }
    }
}

impl<F> Part<F> {
    fn as_ref(&self) -> Part<&F> {
        match self {
            Self::Index(i) => Part::Index(i),
            Self::Range(from, upto) => Part::Range(from.as_ref(), upto.as_ref()),
        }
    }
}

impl<F> From<Part<F>> for Path<F> {
    fn from(p: Part<F>) -> Self {
        Self(Vec::from([(p, Opt::Essential)]))
    }
}