Skip to main content

bast3st_eval/spec/runtime/
collections.rs

1use std::{
2    borrow::Cow,
3    collections::{BTreeMap, VecDeque},
4    fmt::Debug,
5    iter::Sum,
6    sync::Arc,
7};
8
9use derive_more::From;
10use either::Either;
11use scratch_test_value::{SList, SNumber};
12use serde::{Deserialize, Serialize};
13
14use crate::{
15    catchable::cerr,
16    spec::{MapKey, Numeric, PrimitiveValue, RuntimeValue},
17};
18
19#[derive(Debug, Clone, PartialEq, PartialOrd, Default, From, Serialize, Deserialize)]
20pub struct Array(Arc<[Result<RuntimeValue, cerr>]>);
21
22#[derive(derive_more::Debug, Clone, PartialEq, PartialOrd, From, Serialize, Deserialize)]
23#[serde(untagged)]
24pub enum MappingOrArray {
25    #[debug("{_0:?}")]
26    Array(Array),
27    #[debug("{_0:?}")]
28    Mapping(RealMapping),
29}
30impl MappingOrArray {
31    pub fn len(&self) -> usize {
32        match self {
33            Self::Array(a) => a.len(),
34            Self::Mapping(a) => a.len(),
35        }
36    }
37    pub fn is_empty(&self) -> bool {
38        self.len() == 0
39    }
40    pub fn keys<'a>(&'a self) -> impl Iterator<Item = Cow<'a, MapKey>> {
41        match self {
42            Self::Array(a) => Either::Left(a.keys().map(Cow::Owned)),
43            Self::Mapping(m) => Either::Right(m.keys().map(Cow::Borrowed)),
44        }
45    }
46    pub fn sum(&self) -> Result<Numeric, cerr> {
47        match self {
48            Self::Array(a) => a.sum(),
49            Self::Mapping(m) => m.sum_values(),
50        }
51    }
52    pub fn value_array(&self) -> Array {
53        match self {
54            Self::Array(a) => a.clone(),
55            Self::Mapping(m) => m.values().cloned().collect(),
56        }
57    }
58    pub fn get(&self, key: &MapKey) -> Result<&RuntimeValue, cerr> {
59        match (self, key) {
60            (Self::Array(array), MapKey::Int(key)) => array.get(*key),
61            (Self::Mapping(mapping), key) => mapping.get(key),
62            (Self::Array(_), MapKey::Str(_)) => Err(cerr::collection_keyInvalidForArray),
63        }
64    }
65    pub fn to_btreemap(&self) -> BTreeMap<MapKey, Result<RuntimeValue, cerr>> {
66        match self {
67            Self::Mapping(x) => x.mapping.as_ref().clone(),
68            Self::Array(x) => x.clone().into(),
69        }
70    }
71}
72
73#[derive(Clone, PartialEq, PartialOrd, From, Serialize, Deserialize)]
74#[serde(
75    from = "Arc<BTreeMap<MapKey, Result<RuntimeValue, cerr>>>",
76    into = "Arc<BTreeMap<MapKey, Result<RuntimeValue, cerr>>>"
77)]
78pub struct RealMapping {
79    #[from]
80    mapping: Arc<BTreeMap<MapKey, Result<RuntimeValue, cerr>>>,
81    #[from(skip)]
82    #[serde(skip)]
83    default: Result<Box<RuntimeValue>, cerr>,
84}
85
86impl Debug for RealMapping {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        match self.default.as_ref() {
89            Err(&cerr::collection_valueNotFound) => f.write_fmt(format_args!(
90                "RealMapping {{ mapping: {:?} }}",
91                self.mapping
92            )),
93            _ => f.write_fmt(format_args!(
94                "RealMapping {{ mapping: {:?}, default: {:?} }}",
95                self.mapping, self.default
96            )),
97        }
98    }
99}
100
101impl Default for RealMapping {
102    fn default() -> Self {
103        Self {
104            mapping: Default::default(),
105            default: Err(cerr::collection_valueNotFound),
106        }
107    }
108}
109
110impl From<Arc<BTreeMap<MapKey, Result<RuntimeValue, cerr>>>> for RealMapping {
111    fn from(value: Arc<BTreeMap<MapKey, Result<RuntimeValue, cerr>>>) -> Self {
112        Self {
113            mapping: value,
114            default: Err(cerr::collection_valueNotFound),
115        }
116    }
117}
118
119impl From<RealMapping> for Arc<BTreeMap<MapKey, Result<RuntimeValue, cerr>>> {
120    fn from(value: RealMapping) -> Self {
121        value.mapping
122    }
123}
124
125impl AsRef<BTreeMap<MapKey, Result<RuntimeValue, cerr>>> for RealMapping {
126    fn as_ref(&self) -> &BTreeMap<MapKey, Result<RuntimeValue, cerr>> {
127        &self.mapping
128    }
129}
130
131impl RealMapping {
132    pub fn new_with_default(
133        mapping: Arc<BTreeMap<MapKey, Result<RuntimeValue, cerr>>>,
134        default: Option<Result<Box<RuntimeValue>, cerr>>,
135    ) -> Self {
136        Self {
137            mapping,
138            default: default.unwrap_or(Err(cerr::collection_valueNotFound)),
139        }
140    }
141    pub fn with_default(&self, default: Result<RuntimeValue, cerr>) -> Self {
142        Self {
143            mapping: self.mapping.clone(),
144            default: default.map(Box::from),
145        }
146    }
147    pub fn keys(
148        &self,
149    ) -> std::collections::btree_map::Keys<'_, MapKey, Result<RuntimeValue, cerr>> {
150        self.mapping.keys()
151    }
152    pub fn values(
153        &self,
154    ) -> std::collections::btree_map::Values<'_, MapKey, Result<RuntimeValue, cerr>> {
155        self.mapping.values()
156    }
157    pub fn len(&self) -> usize {
158        self.mapping.len()
159    }
160    pub fn get(&self, key: &MapKey) -> Result<&RuntimeValue, cerr> {
161        if let Some(item) = self.mapping.get(key) {
162            item.as_ref()
163        } else {
164            self.default.as_deref()
165        }
166        .map_err(|x| *x)
167    }
168    /// Ok(None) means self (empty key)
169    pub fn get_by_seq<'a, 'k>(
170        &'a self,
171        key: impl IntoIterator<Item = &'k MapKey>,
172    ) -> Result<Option<&'a RuntimeValue>, cerr> {
173        let mut key = key.into_iter();
174        if let Some(first) = key.next() {
175            let mut curr = self.get(first)?;
176            for k in key {
177                if let RuntimeValue::Comp(coll) = curr {
178                    curr = coll.get(k)?;
179                } else {
180                    return Err(cerr::typing_notCollection);
181                }
182            }
183            Ok(Some(curr))
184        } else {
185            Ok(None)
186        }
187    }
188    pub fn is_empty(&self) -> bool {
189        self.len() == 0
190    }
191    pub fn iter(&self) -> impl Iterator<Item = (&MapKey, &Result<RuntimeValue, cerr>)> {
192        self.mapping.iter()
193    }
194
195    pub fn with_merged(
196        &self,
197        other: &BTreeMap<MapKey, Result<RuntimeValue, cerr>>,
198    ) -> Result<Self, cerr> {
199        let merged = self.with_new_keys(
200            other
201                .iter()
202                .map(|(key, val)| (vec![key.clone()].into(), val.clone())),
203        );
204        log::trace!("merge of {self:?} with {other:?} resulted in {merged:?}");
205        merged
206    }
207
208    pub fn with_new_keys<K: Into<MapKey>, V: Into<Result<RuntimeValue, cerr>>>(
209        &self,
210        other: impl IntoIterator<Item = (VecDeque<K>, V)>,
211    ) -> Result<RealMapping, cerr> {
212        let mut extendable = DeepExtendable::from(self.mapping.as_ref().clone());
213        extendable.ensure_inner();
214
215        for (keys, value) in other {
216            let value = value.into();
217            extendable.insert_path(keys.into_iter().map(|k| k.into()).collect(), value.into());
218        }
219
220        let extendable = match extendable.into() {
221            Ok(RuntimeValue::Comp(MappingOrArray::Mapping(m))) => m,
222            Err(err) => Err(err)?,
223            _ => Default::default(),
224        };
225
226        Ok(RealMapping {
227            mapping: extendable.mapping,
228            default: self.default.clone(),
229        })
230    }
231    fn sum_values(&self) -> Result<SNumber, cerr> {
232        let mut out = Numeric::Int(0);
233        for v in self.values() {
234            match v.as_ref().map_err(|x| *x)? {
235                RuntimeValue::Prim(PrimitiveValue::Number(v)) => {
236                    out = out.q_add_numbers(v, &mut ())
237                }
238                RuntimeValue::Prim(PrimitiveValue::Str(t)) => {
239                    if let Ok(t) = t.parse() {
240                        out = out.q_add_numbers(&Numeric::Int(t), &mut ())
241                    } else if let Ok(t) = t.parse() {
242                        out = out.q_add_numbers(&Numeric::Float(t), &mut ())
243                    }
244                }
245                RuntimeValue::Comp(_) => (),
246            }
247        }
248        Ok(out)
249    }
250}
251
252// TODO: vulnerable to stack overflow
253impl From<Result<RuntimeValue, cerr>> for DeepExtendable {
254    fn from(value: Result<RuntimeValue, cerr>) -> Self {
255        match value {
256            Ok(RuntimeValue::Prim(x)) => Self::Leaf(Ok(x)),
257            Ok(RuntimeValue::Comp(c)) => Self::from(c.to_btreemap()),
258            Err(err) => Self::Leaf(Err(err)),
259        }
260    }
261}
262
263// TODO: vulnerable to stack overflow
264impl From<DeepExtendable> for Result<RuntimeValue, cerr> {
265    fn from(value: DeepExtendable) -> Self {
266        match value {
267            DeepExtendable::Leaf(Ok(l)) => Ok(RuntimeValue::Prim(l)),
268            DeepExtendable::Leaf(Err(err)) => Err(err),
269            DeepExtendable::Inner(i) => Ok(RealMapping::from(
270                i.into_iter()
271                    .map(|(k, v)| (k, Result::from(v)))
272                    .collect::<BTreeMap<_, _>>(),
273            )
274            .into()),
275        }
276    }
277}
278
279impl FromIterator<(MapKey, RuntimeValue)> for RealMapping {
280    fn from_iter<T: IntoIterator<Item = (MapKey, RuntimeValue)>>(iter: T) -> Self {
281        Self {
282            mapping: BTreeMap::from_iter(iter.into_iter().map(|(x, y)| (x, Ok(y)))).into(),
283            default: Err(cerr::collection_valueNotFound),
284        }
285    }
286}
287
288impl FromIterator<(MapKey, Result<RuntimeValue, cerr>)> for RealMapping {
289    fn from_iter<T: IntoIterator<Item = (MapKey, Result<RuntimeValue, cerr>)>>(iter: T) -> Self {
290        Self {
291            mapping: BTreeMap::from_iter(iter).into(),
292            default: Err(cerr::collection_valueNotFound),
293        }
294    }
295}
296
297// TODO: vulnerable to stack overflow
298impl From<BTreeMap<MapKey, Result<RuntimeValue, cerr>>> for DeepExtendable {
299    fn from(value: BTreeMap<MapKey, Result<RuntimeValue, cerr>>) -> Self {
300        Self::Inner(
301            value
302                .into_iter()
303                .map(|(key, val)| {
304                    (
305                        key,
306                        match val {
307                            Ok(RuntimeValue::Prim(x)) => DeepExtendable::Leaf(Ok(x)),
308                            Ok(RuntimeValue::Comp(x)) => DeepExtendable::from(x.to_btreemap()),
309                            Err(err) => DeepExtendable::Leaf(Err(err)),
310                        },
311                    )
312                })
313                .collect(),
314        )
315    }
316}
317
318#[derive(Debug, From, Clone)]
319enum DeepExtendable {
320    Inner(BTreeMap<MapKey, DeepExtendable>),
321    Leaf(Result<PrimitiveValue, cerr>),
322}
323impl DeepExtendable {
324    // TODO: vulnerable to stack overflow
325    fn insert_path(&mut self, mut keys: VecDeque<MapKey>, value: DeepExtendable) {
326        if let Some(first_key) = keys.pop_front() {
327            let inner = self.ensure_inner().entry(first_key).or_default();
328            if keys.is_empty() {
329                inner.merge_with(value);
330            } else {
331                inner.insert_path(keys, value);
332            }
333        }
334    }
335    // TODO: vulnerable to stack overflow
336    fn merge_with(&mut self, value: DeepExtendable) {
337        match value {
338            DeepExtendable::Leaf(leaf) => *self = DeepExtendable::Leaf(leaf),
339            DeepExtendable::Inner(map) => {
340                for (key, val) in map.into_iter() {
341                    self.insert_path(vec![key].into(), val);
342                }
343            }
344        }
345    }
346
347    #[allow(unused)]
348    fn insert_single(&mut self, key: MapKey, value: Result<PrimitiveValue, cerr>) {
349        self.ensure_inner().insert(key, value.into());
350    }
351    fn ensure_inner(&mut self) -> &mut BTreeMap<MapKey, DeepExtendable> {
352        match self {
353            Self::Inner(_) => (),
354            Self::Leaf(l) => {
355                let l = std::mem::replace(l, Ok(PrimitiveValue::Number(SNumber::Int(0))));
356                *self = Self::Inner(
357                    vec![(MapKey::Str("".into()), DeepExtendable::Leaf(l))]
358                        .into_iter()
359                        .collect(),
360                )
361            }
362        }
363        if let Self::Inner(x) = self {
364            x
365        } else {
366            unreachable!()
367        }
368    }
369}
370
371impl Default for DeepExtendable {
372    fn default() -> Self {
373        Self::Inner(Default::default())
374    }
375}
376
377impl Array {
378    pub fn new(array: Arc<[Result<RuntimeValue, cerr>]>) -> Self {
379        Self(array)
380    }
381    pub fn keys(&self) -> impl Iterator<Item = MapKey> {
382        std::iter::successors(Some(0), |x| Some(x + 1))
383            .map(MapKey::Int)
384            .take(self.len())
385    }
386    pub fn value_array(&self) -> Array {
387        self.clone()
388    }
389    pub fn len(&self) -> usize {
390        self.0.len()
391    }
392    pub fn sum(&self) -> Result<SNumber, cerr> {
393        let mut out = Numeric::Int(0);
394        for v in self.iter() {
395            match v.as_ref().map_err(|x| *x)? {
396                RuntimeValue::Prim(PrimitiveValue::Number(v)) => {
397                    out = out.q_add_numbers(v, &mut ())
398                }
399                RuntimeValue::Prim(PrimitiveValue::Str(t)) => {
400                    if let Ok(t) = t.parse() {
401                        out = out.q_add_numbers(&Numeric::Int(t), &mut ())
402                    } else if let Ok(t) = t.parse() {
403                        out = out.q_add_numbers(&Numeric::Float(t), &mut ())
404                    }
405                }
406                RuntimeValue::Comp(_) => (),
407            }
408        }
409        Ok(out)
410    }
411
412    pub fn get(&self, mut key: i64) -> Result<&RuntimeValue, cerr> {
413        let len: Result<i64, _> = self.len().try_into();
414        if let Ok(len) = len
415            && key < 0
416        {
417            key += len;
418        }
419
420        let key: usize = key
421            .try_into()
422            .map_err(|_| cerr::collection_keyInvalidForArray)?;
423        match self.0.get(key) {
424            Some(Ok(t)) => Ok(t),
425            Some(Err(t)) => Err(*t),
426            None => Err(cerr::collection_valueNotFound),
427        }
428    }
429    pub fn is_empty(&self) -> bool {
430        self.len() == 0
431    }
432    pub fn iter(&self) -> impl Iterator<Item = &Result<RuntimeValue, cerr>> {
433        self.0.iter()
434    }
435}
436
437impl<'a> Sum<&'a RuntimeValue> for Numeric {
438    fn sum<I: Iterator<Item = &'a RuntimeValue>>(iter: I) -> Self {
439        let mut out = Numeric::Int(0);
440        for v in iter {
441            match v {
442                RuntimeValue::Prim(PrimitiveValue::Number(v)) => {
443                    out = out.q_add_numbers(v, &mut ())
444                }
445                RuntimeValue::Prim(PrimitiveValue::Str(t)) => {
446                    if let Ok(t) = t.parse() {
447                        out = out.q_add_numbers(&Numeric::Int(t), &mut ())
448                    } else if let Ok(t) = t.parse() {
449                        out = out.q_add_numbers(&Numeric::Float(t), &mut ())
450                    }
451                }
452                RuntimeValue::Comp(_) => (),
453            }
454        }
455        out
456    }
457}
458
459impl<P: Into<RuntimeValue>> FromIterator<P> for Array {
460    fn from_iter<T: IntoIterator<Item = P>>(iter: T) -> Self {
461        Self(iter.into_iter().map(|x| Ok(x.into())).collect())
462    }
463}
464
465impl<P: Into<RuntimeValue>> FromIterator<Result<P, cerr>> for Array {
466    fn from_iter<T: IntoIterator<Item = Result<P, cerr>>>(iter: T) -> Self {
467        Self(iter.into_iter().map(|x| x.map(|x| x.into())).collect())
468    }
469}
470impl From<BTreeMap<MapKey, Result<RuntimeValue, cerr>>> for RealMapping {
471    fn from(value: BTreeMap<MapKey, Result<RuntimeValue, cerr>>) -> Self {
472        Self {
473            mapping: value.into(),
474            ..Default::default()
475        }
476    }
477}
478impl From<Vec<Result<RuntimeValue, cerr>>> for Array {
479    fn from(value: Vec<Result<RuntimeValue, cerr>>) -> Self {
480        Self(value.into())
481    }
482}
483
484impl From<SList> for Array {
485    fn from(value: SList) -> Self {
486        value.into_iter().map(RuntimeValue::from).collect()
487    }
488}
489
490impl From<Array> for BTreeMap<MapKey, Result<RuntimeValue, cerr>> {
491    fn from(value: Array) -> Self {
492        value
493            .keys()
494            .zip(value.iter().cloned())
495            .collect::<BTreeMap<_, _>>()
496    }
497}