anathema_value_resolver/
value.rs

1use std::borrow::Cow;
2use std::ops::{Deref, DerefMut};
3
4use anathema_state::{Color, Hex, PendingValue, SubTo, Subscriber, Type};
5use anathema_store::smallmap::SmallMap;
6use anathema_templates::Expression;
7
8use crate::attributes::ValueKey;
9use crate::expression::{ValueExpr, ValueResolutionContext, resolve_value};
10use crate::immediate::Resolver;
11use crate::{AttributeStorage, ResolverCtx};
12
13pub type Values<'bp> = SmallMap<ValueKey<'bp>, Value<'bp>>;
14
15pub fn resolve<'bp>(expr: &'bp Expression, ctx: &ResolverCtx<'_, 'bp>, sub: impl Into<Subscriber>) -> Value<'bp> {
16    let resolver = Resolver::new(ctx);
17    let value_expr = resolver.resolve(expr);
18    Value::new(value_expr, sub.into(), ctx.attribute_storage)
19}
20
21pub fn resolve_collection<'bp>(
22    expr: &'bp Expression,
23    ctx: &ResolverCtx<'_, 'bp>,
24    sub: impl Into<Subscriber>,
25) -> Collection<'bp> {
26    let value = resolve(expr, ctx, sub);
27    Collection(value)
28}
29
30#[derive(Debug)]
31pub struct Collection<'bp>(pub(crate) Value<'bp>);
32
33impl<'bp> Collection<'bp> {
34    pub fn reload(&mut self, attributes: &AttributeStorage<'bp>) {
35        self.0.reload(attributes)
36    }
37
38    pub fn len(&self) -> usize {
39        match &self.0.kind {
40            ValueKind::List(vec) => vec.len(),
41            ValueKind::DynList(value) => {
42                let Some(state) = value.as_state() else { return 0 };
43                let Some(list) = state.as_any_list() else { return 0 };
44                list.len()
45            }
46            ValueKind::Int(_)
47            | ValueKind::Float(_)
48            | ValueKind::Bool(_)
49            | ValueKind::Char(_)
50            | ValueKind::Hex(_)
51            | ValueKind::Color(_)
52            | ValueKind::Str(_)
53            | ValueKind::DynMap(_)
54            | ValueKind::Map
55            | ValueKind::Composite(_)
56            | ValueKind::Attributes
57            | ValueKind::Null => 0,
58        }
59    }
60}
61
62/// This is the final value for a node attribute / value.
63/// This should be evaluated fully for the `ValueKind`
64#[derive(Debug)]
65pub struct Value<'bp> {
66    pub(crate) expr: ValueExpr<'bp>,
67    pub(crate) sub: Subscriber,
68    pub(crate) kind: ValueKind<'bp>,
69    pub(crate) sub_to: SubTo,
70}
71
72impl<'bp> Value<'bp> {
73    pub fn new(expr: ValueExpr<'bp>, sub: Subscriber, attribute_storage: &AttributeStorage<'bp>) -> Self {
74        let mut sub_to = SubTo::Zero;
75        let mut ctx = ValueResolutionContext::new(attribute_storage, sub, &mut sub_to);
76        let kind = resolve_value(&expr, &mut ctx);
77
78        // NOTE
79        // This is a special edge case where the map or state is used
80        // as a final value `Option<ValueKind>`.
81        //
82        // This would only hold value in an if-statement:
83        // ```
84        // if state.opt_map
85        //     text "show this if there is a map"
86        // ```
87        match kind {
88            ValueKind::DynMap(pending) | ValueKind::Composite(pending) => {
89                pending.subscribe(ctx.sub);
90                ctx.sub_to.push(pending.sub_key());
91            }
92            _ => {}
93        }
94        Self {
95            expr,
96            sub,
97            kind,
98            sub_to,
99        }
100    }
101
102    pub fn truthiness(&self) -> bool {
103        // None         = false
104        // 0            = false
105        // Some("")     = false
106        // Some(0)      = false
107        // []           = false
108        // {}           = false
109        // Some(bool)   = bool
110        // _            = true
111
112        self.kind.truthiness()
113    }
114
115    #[doc(hidden)]
116    pub fn kind(&self) -> &ValueKind<'_> {
117        &self.kind
118    }
119
120    pub fn reload(&mut self, attribute_storage: &AttributeStorage<'bp>) {
121        self.sub_to.unsubscribe(self.sub);
122        let mut ctx = ValueResolutionContext::new(attribute_storage, self.sub, &mut self.sub_to);
123        self.kind = resolve_value(&self.expr, &mut ctx);
124    }
125
126    pub fn try_as<T>(&self) -> Option<T>
127    where
128        T: for<'a> TryFrom<&'a ValueKind<'a>>,
129    {
130        (&self.kind).try_into().ok()
131    }
132
133    pub fn strings<F>(&self, mut f: F)
134    where
135        F: FnMut(&str) -> bool,
136    {
137        self.kind.strings(&mut f);
138    }
139}
140
141impl Drop for Value<'_> {
142    fn drop(&mut self) {
143        self.sub_to.unsubscribe(self.sub);
144    }
145}
146
147impl<'a> Deref for Value<'a> {
148    type Target = ValueKind<'a>;
149
150    fn deref(&self) -> &Self::Target {
151        &self.kind
152    }
153}
154
155impl<'a> DerefMut for Value<'a> {
156    fn deref_mut(&mut self) -> &mut Self::Target {
157        &mut self.kind
158    }
159}
160
161/// This value can never be part of an evaluation chain, only the return value.
162/// It should only ever be the final type that is held by a `Value`, at
163/// the end of an evaluation
164#[derive(Debug, PartialEq, PartialOrd, Clone)]
165pub enum ValueKind<'bp> {
166    Int(i64),
167    Float(f64),
168    Bool(bool),
169    Char(char),
170    Hex(Hex),
171    Color(Color),
172    Str(Cow<'bp, str>),
173    Null,
174
175    // NOTE
176    // The map is the final value, and is never used as part
177    // of an index, for that reason the map doesn't hold any values.
178    Map,
179    // NOTE
180    // The attributes is the final value, and is never used as part
181    // of an index, for that reason the attributes doesn't hold any values.
182    Attributes,
183    List(Box<[ValueKind<'bp>]>),
184    DynList(PendingValue),
185    DynMap(PendingValue),
186    Composite(PendingValue),
187}
188
189impl ValueKind<'_> {
190    pub fn to_int(&self) -> Option<i64> {
191        match self.as_int() {
192            Some(val) => Some(val),
193            None => Some(self.as_float()? as i64),
194        }
195    }
196
197    pub fn as_int(&self) -> Option<i64> {
198        let ValueKind::Int(i) = self else { return None };
199        Some(*i)
200    }
201
202    pub fn as_float(&self) -> Option<f64> {
203        let ValueKind::Float(i) = self else { return None };
204        Some(*i)
205    }
206
207    pub fn as_bool(&self) -> Option<bool> {
208        let ValueKind::Bool(b) = self else { return None };
209        Some(*b)
210    }
211
212    pub fn as_char(&self) -> Option<char> {
213        let ValueKind::Char(i) = self else { return None };
214        Some(*i)
215    }
216
217    pub fn as_hex(&self) -> Option<Hex> {
218        let ValueKind::Hex(i) = self else { return None };
219        Some(*i)
220    }
221
222    pub fn as_color(&self) -> Option<Color> {
223        let ValueKind::Color(i) = self else { return None };
224        Some(*i)
225    }
226
227    pub fn as_str(&self) -> Option<&str> {
228        let ValueKind::Str(i) = &self else { return None };
229        Some(i)
230    }
231
232    pub fn strings<F>(&self, mut f: F)
233    where
234        F: FnMut(&str) -> bool,
235    {
236        self.internal_strings(&mut f);
237    }
238
239    fn internal_strings<F>(&self, f: &mut F) -> bool
240    where
241        F: FnMut(&str) -> bool,
242    {
243        match self {
244            ValueKind::Int(n) => f(&n.to_string()),
245            ValueKind::Float(n) => f(&n.to_string()),
246            ValueKind::Bool(b) => f(&b.to_string()),
247            ValueKind::Char(c) => f(&c.to_string()),
248            ValueKind::Hex(x) => f(&x.to_string()),
249            ValueKind::Color(col) => f(&col.to_string()),
250            ValueKind::Str(cow) => f(cow.as_ref()),
251            ValueKind::List(vec) => vec.iter().take_while(|val| val.internal_strings(f)).count() == vec.len(),
252            ValueKind::DynList(value) => dyn_string(*value, f),
253            ValueKind::DynMap(_) => f("<dyn map>"),
254            ValueKind::Map => f("<map>"),
255            ValueKind::Composite(_) => f("<composite>"),
256            ValueKind::Attributes => f("<attributes>"),
257            ValueKind::Null => true,
258        }
259    }
260
261    pub(crate) fn truthiness(&self) -> bool {
262        match self {
263            ValueKind::Int(0) | ValueKind::Float(0.0) | ValueKind::Bool(false) => false,
264            ValueKind::Str(cow) if cow.is_empty() => false,
265            ValueKind::Null => false,
266            ValueKind::List(list) if list.is_empty() => false,
267            ValueKind::DynList(list) => {
268                let Some(state) = list.as_state() else { return false };
269                let Some(state) = state.as_any_list() else { return false };
270                !state.is_empty()
271            }
272            ValueKind::DynMap(map) => {
273                let Some(state) = map.as_state() else { return false };
274                let Some(state) = state.as_any_map() else { return false };
275                !state.is_empty()
276            }
277            // ValueKind::Map => ??,
278            _ => true,
279        }
280    }
281}
282
283fn dyn_string<F>(value: PendingValue, f: &mut F) -> bool
284where
285    F: FnMut(&str) -> bool,
286{
287    let Some(state) = value.as_state() else { return true };
288    let Some(list) = state.as_any_list() else { return true };
289    for i in 0..list.len() {
290        let value = list.lookup(i).expect("the value exists");
291        let Some(state) = value.as_state() else { continue };
292        let should_continue = match value.type_info() {
293            Type::Int => f(&state.as_int().expect("type info dictates this").to_string()),
294            Type::Float => f(&state.as_float().expect("type info dictates this").to_string()),
295            Type::Char => f(&state.as_char().expect("type info dictates this").to_string()),
296            Type::String => f(state.as_str().expect("type info dictates this")),
297            Type::Bool => f(&state.as_bool().expect("type info dictates this").to_string()),
298            Type::Hex => f(&state.as_hex().expect("type info dictates this").to_string()),
299            Type::Map => f("<map>"),
300            Type::List => dyn_string(value, f),
301            Type::Composite => f(&state.as_hex().expect("type info dictates this").to_string()),
302            Type::Unit => f(""),
303            Type::Color => f(&state.as_color().expect("type info dictates this").to_string()),
304            Type::Maybe => panic!(),
305        };
306
307        if !should_continue {
308            return false;
309        }
310    }
311    true
312}
313
314// -----------------------------------------------------------------------------
315//   - From impls -
316// -----------------------------------------------------------------------------
317macro_rules! from_int {
318    ($int:ty) => {
319        impl From<$int> for ValueKind<'_> {
320            fn from(value: $int) -> Self {
321                ValueKind::Int(value as i64)
322            }
323        }
324    };
325}
326
327from_int!(i64);
328from_int!(i32);
329from_int!(i16);
330from_int!(i8);
331from_int!(u64);
332from_int!(u32);
333from_int!(u16);
334from_int!(u8);
335
336impl From<f64> for ValueKind<'_> {
337    fn from(value: f64) -> Self {
338        ValueKind::Float(value)
339    }
340}
341
342impl From<f32> for ValueKind<'_> {
343    fn from(value: f32) -> Self {
344        ValueKind::Float(value as f64)
345    }
346}
347
348impl From<bool> for ValueKind<'_> {
349    fn from(value: bool) -> Self {
350        ValueKind::Bool(value)
351    }
352}
353
354impl From<char> for ValueKind<'_> {
355    fn from(value: char) -> Self {
356        ValueKind::Char(value)
357    }
358}
359
360impl From<Hex> for ValueKind<'_> {
361    fn from(value: Hex) -> Self {
362        ValueKind::Hex(value)
363    }
364}
365
366impl From<Color> for ValueKind<'_> {
367    fn from(value: Color) -> Self {
368        ValueKind::Color(value)
369    }
370}
371
372impl<'bp, T> From<Vec<T>> for ValueKind<'bp>
373where
374    T: Into<ValueKind<'bp>>,
375{
376    fn from(value: Vec<T>) -> Self {
377        let list = value.into_iter().map(T::into).collect();
378        ValueKind::List(list)
379    }
380}
381
382impl<'a> From<&'a str> for ValueKind<'a> {
383    fn from(value: &'a str) -> Self {
384        ValueKind::Str(Cow::Borrowed(value))
385    }
386}
387
388impl From<String> for ValueKind<'_> {
389    fn from(value: String) -> Self {
390        ValueKind::Str(value.into())
391    }
392}
393
394// -----------------------------------------------------------------------------
395//   - Try From -
396// -----------------------------------------------------------------------------
397macro_rules! try_from_valuekind {
398    ($t:ty, $kind:ident) => {
399        impl TryFrom<&ValueKind<'_>> for $t {
400            type Error = ();
401
402            fn try_from(value: &ValueKind<'_>) -> Result<Self, Self::Error> {
403                match value {
404                    ValueKind::$kind(val) => Ok(*val),
405                    _ => Err(()),
406                }
407            }
408        }
409    };
410}
411
412macro_rules! try_from_valuekind_int {
413    ($t:ty, $kind:ident) => {
414        impl TryFrom<&ValueKind<'_>> for $t {
415            type Error = ();
416
417            fn try_from(value: &ValueKind<'_>) -> Result<Self, Self::Error> {
418                match value {
419                    ValueKind::$kind(val) => Ok(*val as $t),
420                    _ => Err(()),
421                }
422            }
423        }
424    };
425}
426
427try_from_valuekind!(i64, Int);
428try_from_valuekind!(f64, Float);
429try_from_valuekind!(bool, Bool);
430try_from_valuekind!(char, Char);
431try_from_valuekind!(Hex, Hex);
432try_from_valuekind!(Color, Color);
433
434try_from_valuekind_int!(usize, Int);
435try_from_valuekind_int!(isize, Int);
436try_from_valuekind_int!(i32, Int);
437try_from_valuekind_int!(f32, Float);
438try_from_valuekind_int!(i16, Int);
439try_from_valuekind_int!(i8, Int);
440try_from_valuekind_int!(u32, Int);
441try_from_valuekind_int!(u64, Int);
442try_from_valuekind_int!(u16, Int);
443try_from_valuekind_int!(u8, Int);
444
445impl<'a, 'bp> TryFrom<&'a ValueKind<'bp>> for &'a str {
446    type Error = ();
447
448    fn try_from(value: &'a ValueKind<'bp>) -> Result<Self, Self::Error> {
449        match value {
450            ValueKind::Str(Cow::Borrowed(val)) => Ok(val),
451            ValueKind::Str(Cow::Owned(val)) => Ok(val.as_str()),
452            _ => Err(()),
453        }
454    }
455}
456
457#[cfg(test)]
458pub(crate) mod test {
459    use anathema_state::{Hex, Map, Maybe, States};
460    use anathema_templates::Variables;
461    use anathema_templates::expressions::{
462        add, and, boolean, chr, div, either, eq, float, greater_than, greater_than_equal, hex, ident, index, less_than,
463        less_than_equal, list, map, modulo, mul, neg, not, num, or, strlit, sub, text_segments,
464    };
465
466    use crate::ValueKind;
467    use crate::testing::setup;
468
469    #[test]
470    fn attribute_lookup() {
471        let expr = index(ident("attributes"), strlit("a"));
472        let int = num(123);
473
474        let mut states = States::new();
475        setup(&mut states, Default::default(), |test| {
476            test.set_attribute("a", &int);
477            let value = test.eval(&expr);
478            assert_eq!(123, value.as_int().unwrap());
479        });
480    }
481
482    #[test]
483    fn expr_list_dyn_index() {
484        let expr = index(list([1, 2, 3]), add(ident("index"), num(1)));
485
486        let mut states = States::new();
487        let mut globals = Variables::new();
488        globals.declare("index", 0);
489
490        setup(&mut states, globals, |test| {
491            let value = test.eval(&expr);
492            assert_eq!(2, value.as_int().unwrap());
493        });
494    }
495
496    #[test]
497    fn expr_list() {
498        let expr = index(list([1, 2, 3]), num(0));
499
500        let mut states = States::new();
501        setup(&mut states, Default::default(), |test| {
502            let value = test.eval(&expr);
503            assert_eq!(1, value.as_int().unwrap());
504        });
505    }
506
507    #[test]
508    fn either_index() {
509        // state[0] ? attributes[0]
510        let expr = either(
511            index(index(ident("state"), strlit("list")), num(0)),
512            index(index(ident("attributes"), strlit("list")), num(0)),
513        );
514
515        let list = list([strlit("from attribute")]);
516
517        let mut states = States::new();
518        setup(&mut states, Default::default(), |test| {
519            // Set list for attributes
520            test.set_attribute("list", &list);
521
522            // Evaluate the value.
523            // The state is not yet set so it will fall back to attributes
524            let mut value = test.eval(&expr);
525            assert_eq!("from attribute", value.as_str().unwrap());
526
527            // Set the state value
528            test.with_state(|state| state.list.push("from state"));
529
530            // The value now comes from the state
531            value.reload(&test.attributes);
532            assert_eq!("from state", value.as_str().unwrap());
533        });
534    }
535
536    #[test]
537    fn either_then_index() {
538        // (state ? attributes)[0]
539
540        let list = list([num(123)]);
541        let mut states = States::new();
542        setup(&mut states, Default::default(), |test| {
543            let expr = index(
544                either(
545                    index(ident("attributes"), strlit("list")),
546                    index(ident("state"), strlit("list")),
547                ),
548                num(0),
549            );
550
551            test.with_state(|state| state.list.push("a string"));
552            let value = test.eval(&expr);
553            assert_eq!("a string", value.as_str().unwrap());
554
555            test.set_attribute("list", &list);
556            let value = test.eval(&expr);
557            assert_eq!(123, value.as_int().unwrap());
558        });
559    }
560
561    #[test]
562    fn either_or() {
563        let mut states = States::new();
564        setup(&mut states, Default::default(), |test| {
565            test.with_state(|state| state.num.set(1));
566            test.with_state(|state| state.num_2.set(2));
567
568            // There is no c, so use b
569            let expr = either(
570                index(ident("state"), strlit("num_3")),
571                index(ident("state"), strlit("num_2")),
572            );
573            let value = test.eval(&expr);
574            assert_eq!(2, value.as_int().unwrap());
575
576            // There is a, so don't use b
577            let expr = either(
578                index(ident("state"), strlit("num")),
579                index(ident("state"), strlit("num_2")),
580            );
581            let value = test.eval(&expr);
582            assert_eq!(1, value.as_int().unwrap());
583        });
584    }
585
586    #[test]
587    fn mods() {
588        let mut states = States::new();
589        setup(&mut states, Default::default(), |test| {
590            test.with_state(|state| state.num.set(5));
591            let lookup = index(ident("state"), strlit("num"));
592            let expr = modulo(lookup, num(3));
593            let value = test.eval(&expr);
594            assert_eq!(2, value.as_int().unwrap());
595        });
596    }
597
598    #[test]
599    fn division() {
600        let mut states = States::new();
601        setup(&mut states, Default::default(), |test| {
602            test.with_state(|state| state.num.set(6));
603            let lookup = index(ident("state"), strlit("num"));
604            let expr = div(lookup, num(2));
605            let value = test.eval(&expr);
606            assert_eq!(3, value.as_int().unwrap());
607        });
608    }
609
610    #[test]
611    fn multiplication() {
612        let mut states = States::new();
613        setup(&mut states, Default::default(), |test| {
614            test.with_state(|state| state.num.set(2));
615            let lookup = index(ident("state"), strlit("num"));
616            let expr = mul(lookup, num(2));
617            let value = test.eval(&expr);
618            assert_eq!(4, value.as_int().unwrap());
619        });
620    }
621
622    #[test]
623    fn subtraction() {
624        let mut states = States::new();
625        setup(&mut states, Default::default(), |test| {
626            test.with_state(|state| state.num.set(1));
627            let lookup = index(ident("state"), strlit("num"));
628            let expr = sub(lookup, num(2));
629            let value = test.eval(&expr);
630            assert_eq!(-1, value.as_int().unwrap());
631        });
632    }
633
634    #[test]
635    fn addition() {
636        let mut states = States::new();
637        setup(&mut states, Default::default(), |test| {
638            test.with_state(|state| state.num.set(1));
639            let lookup = index(ident("state"), strlit("num"));
640            let expr = add(lookup, num(2));
641            let value = test.eval(&expr);
642            assert_eq!(3, value.as_int().unwrap());
643        });
644    }
645
646    #[test]
647    fn test_or() {
648        let mut states = States::new();
649        setup(&mut states, Default::default(), |test| {
650            let is_true = or(boolean(false), boolean(true));
651            let is_true = test.eval(&is_true);
652            assert!(is_true.as_bool().unwrap());
653        });
654    }
655
656    #[test]
657    fn test_and() {
658        let mut states = States::new();
659        setup(&mut states, Default::default(), |test| {
660            let is_true = and(boolean(true), boolean(true));
661            let is_true = test.eval(&is_true);
662            assert!(is_true.as_bool().unwrap());
663        });
664    }
665
666    #[test]
667    fn lte() {
668        let mut states = States::new();
669        setup(&mut states, Default::default(), |test| {
670            let is_true = less_than_equal(num(1), num(2));
671            let is_also_true = less_than_equal(num(1), num(1));
672            let is_true = test.eval(&is_true);
673            let is_also_true = test.eval(&is_also_true);
674            assert!(is_true.as_bool().unwrap());
675            assert!(is_also_true.as_bool().unwrap());
676        });
677    }
678
679    #[test]
680    fn lt() {
681        let mut states = States::new();
682        setup(&mut states, Default::default(), |test| {
683            let is_true = less_than(num(1), num(2));
684            let is_false = less_than(num(1), num(1));
685            let is_true = test.eval(&is_true);
686            let is_false = test.eval(&is_false);
687            assert!(is_true.as_bool().unwrap());
688            assert!(!is_false.as_bool().unwrap());
689        });
690    }
691
692    #[test]
693    fn gte() {
694        let mut states = States::new();
695        setup(&mut states, Default::default(), |test| {
696            let is_true = greater_than_equal(num(2), num(1));
697            let is_also_true = greater_than_equal(num(2), num(2));
698            let is_true = test.eval(&is_true);
699            let is_also_true = test.eval(&is_also_true);
700            assert!(is_true.as_bool().unwrap());
701            assert!(is_also_true.as_bool().unwrap());
702        });
703    }
704
705    #[test]
706    fn gt() {
707        let mut states = States::new();
708        setup(&mut states, Default::default(), |test| {
709            let is_true = greater_than(num(2), num(1));
710            let is_false = greater_than(num(2), num(2));
711            let is_true = test.eval(&is_true);
712            let is_false = test.eval(&is_false);
713            assert!(is_true.as_bool().unwrap());
714            assert!(!is_false.as_bool().unwrap());
715        });
716    }
717
718    #[test]
719    fn equality() {
720        let mut states = States::new();
721        setup(&mut states, Default::default(), |test| {
722            let is_true = eq(num(1), num(1));
723            let is_true = test.eval(&is_true);
724            let is_false = &not(eq(num(1), num(1)));
725            let is_false = test.eval(is_false);
726            assert!(is_true.as_bool().unwrap());
727            assert!(!is_false.as_bool().unwrap());
728        });
729    }
730
731    #[test]
732    fn neg_float() {
733        let mut states = States::new();
734        setup(&mut states, Default::default(), |test| {
735            let expr = neg(float(123.1));
736            let value = test.eval(&expr);
737            assert_eq!(-123.1, value.as_float().unwrap());
738        });
739    }
740
741    #[test]
742    fn neg_num() {
743        let mut states = States::new();
744        setup(&mut states, Default::default(), |test| {
745            let expr = neg(num(123));
746            let value = test.eval(&expr);
747            assert_eq!(-123, value.as_int().unwrap());
748        });
749    }
750
751    #[test]
752    fn not_true() {
753        let mut states = States::new();
754        setup(&mut states, Default::default(), |test| {
755            let expr = not(boolean(false));
756            let value = test.eval(&expr);
757            assert!(value.as_bool().unwrap());
758        });
759    }
760
761    #[test]
762    fn map_resolve() {
763        let mut states = States::new();
764        setup(&mut states, Default::default(), |test| {
765            let expr = map([("a", 123), ("b", 456)]);
766            let value = test.eval(&expr);
767            assert_eq!(ValueKind::Map, value.kind);
768        });
769    }
770
771    #[test]
772    fn optional_map_resolve() {
773        let mut states = States::new();
774        setup(&mut states, Default::default(), |test| {
775            // At first there is no map...
776            let expr = index(ident("state"), strlit("opt_map"));
777            let mut value = test.eval(&expr);
778            assert!(matches!(value.kind, ValueKind::Null));
779
780            // ... then we insert a map
781            test.with_state(|state| {
782                let map = Map::empty();
783                state.opt_map.set(Maybe::some(map));
784            });
785
786            value.reload(&test.attributes);
787            assert!(matches!(value.kind, ValueKind::DynMap(_)));
788        });
789    }
790
791    #[test]
792    fn str_resolve() {
793        // state[empty|full]
794        let mut states = States::new();
795        let mut globals = Variables::new();
796        globals.declare("full", "string");
797        setup(&mut states, globals, |test| {
798            let expr = index(ident("state"), either(ident("empty"), ident("full")));
799            test.with_state(|state| state.string.set("a string"));
800            let value = test.eval(&expr);
801            assert_eq!("a string", value.as_str().unwrap());
802        });
803    }
804
805    #[test]
806    fn state_string() {
807        let mut states = States::new();
808        setup(&mut states, Default::default(), |test| {
809            test.with_state(|state| state.string.set("a string"));
810            let expr = index(ident("state"), strlit("string"));
811            let value = test.eval(&expr);
812            assert_eq!("a string", value.as_str().unwrap());
813        });
814    }
815
816    #[test]
817    fn state_float() {
818        let mut states = States::new();
819        setup(&mut states, Default::default(), |test| {
820            let expr = index(ident("state"), strlit("float"));
821            test.with_state(|state| state.float.set(1.2));
822            let value = test.eval(&expr);
823            assert_eq!(1.2, value.as_float().unwrap());
824        });
825    }
826
827    #[test]
828    fn test_either() {
829        let mut states = States::new();
830        let mut globals = Variables::new();
831        globals.declare("missing", 111);
832        setup(&mut states, globals, |test| {
833            let expr = either(ident("missings"), num(2));
834            let value = test.eval(&expr);
835            assert_eq!(2, value.as_int().unwrap());
836        });
837    }
838
839    #[test]
840    fn test_hex() {
841        let mut states = States::new();
842        setup(&mut states, Default::default(), |test| {
843            let expr = hex((1, 2, 3));
844            let value = test.eval(&expr);
845            assert_eq!(Hex::from((1, 2, 3)), value.as_hex().unwrap());
846        });
847    }
848
849    #[test]
850    fn test_char() {
851        let mut states = States::new();
852        setup(&mut states, Default::default(), |test| {
853            let expr = chr('x');
854            let value = test.eval(&expr);
855            assert_eq!('x', value.as_char().unwrap());
856        });
857    }
858
859    #[test]
860    fn test_float() {
861        let mut states = States::new();
862        setup(&mut states, Default::default(), |test| {
863            let expr = float(123.123);
864            let value = test.eval(&expr);
865            assert_eq!(123.123, value.as_float().unwrap());
866        });
867    }
868
869    #[test]
870    fn test_int() {
871        let mut states = States::new();
872        setup(&mut states, Default::default(), |test| {
873            let expr = num(123);
874            let value = test.eval(&expr);
875            assert_eq!(123, value.as_int().unwrap());
876        });
877    }
878
879    #[test]
880    fn test_bool() {
881        let mut states = States::new();
882        setup(&mut states, Default::default(), |test| {
883            let expr = boolean(true);
884            let value = test.eval(&expr);
885            assert!(value.as_bool().unwrap());
886        });
887    }
888
889    #[test]
890    fn test_dyn_list() {
891        let mut states = States::new();
892        setup(&mut states, Default::default(), |test| {
893            test.with_state(|state| {
894                state.list.push("abc");
895                state.list.push("def");
896            });
897            let expr = index(index(ident("state"), strlit("list")), num(1));
898            let value = test.eval(&expr);
899            assert_eq!("def", value.as_str().unwrap());
900        });
901    }
902
903    #[test]
904    fn test_expression_map_state_key() {
905        let mut states = States::new();
906        setup(&mut states, Default::default(), |test| {
907            let expr = index(map([("value", 123)]), index(ident("state"), strlit("string")));
908            test.with_state(|state| state.string.set("value"));
909            let value = test.eval(&expr);
910            assert_eq!(123, value.as_int().unwrap());
911        });
912    }
913
914    #[test]
915    fn test_expression_map() {
916        let mut states = States::new();
917        setup(&mut states, Default::default(), |test| {
918            let expr = index(map([("value", 123)]), strlit("value"));
919            let value = test.eval(&expr);
920            assert_eq!(123, value.as_int().unwrap());
921        });
922    }
923
924    #[test]
925    fn test_state_lookup() {
926        let mut states = States::new();
927        setup(&mut states, Default::default(), |test| {
928            let expr = index(ident("state"), strlit("num"));
929            let value = test.eval(&expr);
930            assert_eq!(0, value.as_int().unwrap());
931        });
932    }
933
934    #[test]
935    fn test_nested_map() {
936        let mut states = States::new();
937        setup(&mut states, Default::default(), |test| {
938            let expr = index(index(ident("state"), strlit("map")), strlit("value"));
939            test.with_state(|state| state.map.to_mut().insert("value", 123));
940            let value = test.eval(&expr);
941            assert_eq!(123, value.as_int().unwrap());
942        });
943    }
944
945    // #[test]
946    // fn test_nested_maps() {
947    //     let mut states = States::new();
948    //     setup(&mut states, Default::default(), |test| {
949    //         let expr = index(
950    //             index(index(ident("state"), strlit("value")), strlit("value")),
951    //             strlit("value"),
952    //         );
953    //         let mut inner_map = Value::new(Map::empty());
954    //         let mut inner_inner_map = Value::new(Map::empty());
955    //         inner_inner_map.insert("value", 123);
956    //         inner_map.insert("value", inner_inner_map);
957
958    //         test.set_state("value", inner_map);
959    //         let value = test.eval(&*expr);
960    //         assert_eq!(123, value.as_int().unwrap());
961    //     });
962    // }
963
964    #[test]
965    fn stringify() {
966        let mut states = States::new();
967        setup(&mut states, Default::default(), |test| {
968            let expr = text_segments([strlit("hello"), strlit(" "), strlit("world")]);
969            let value = test.eval(&expr);
970            let mut actual = String::new();
971            value.strings(|st| {
972                actual.push_str(st);
973                true
974            });
975            assert_eq!("hello world", &actual);
976        });
977    }
978}