tytanic_filter/eval/
value.rs

1use super::{Error, Func, Set};
2use crate::ast::{Num, Str};
3
4/// The value of a test set expression.
5#[derive(Debug, Clone)]
6pub enum Value<T> {
7    /// A test.
8    Test(T),
9
10    /// A test set.
11    Set(Set<T>),
12
13    /// A function.
14    Func(Func<T>),
15
16    /// An unsigned integer.
17    Num(Num),
18
19    /// A string.
20    Str(Str),
21}
22
23impl<T> Value<T> {
24    /// The type of this expression.
25    pub fn as_type(&self) -> Type {
26        match self {
27            Value::Test(_) => Type::Test,
28            Value::Set(_) => Type::Set,
29            Value::Func(_) => Type::Func,
30            Value::Num(_) => Type::Num,
31            Value::Str(_) => Type::Str,
32        }
33    }
34
35    /// Convert this value into a `T` or return an error.
36    pub fn expect_type<V: TryFromValue<T>>(self) -> Result<V, Error>
37    where
38        T: Clone,
39    {
40        V::try_from_value(self)
41    }
42}
43
44impl<T> From<Set<T>> for Value<T> {
45    fn from(value: Set<T>) -> Self {
46        Self::Set(value)
47    }
48}
49
50impl<T> From<Func<T>> for Value<T> {
51    fn from(value: Func<T>) -> Self {
52        Self::Func(value)
53    }
54}
55
56impl<T> From<Num> for Value<T> {
57    fn from(value: Num) -> Self {
58        Self::Num(value)
59    }
60}
61
62impl<T> From<Str> for Value<T> {
63    fn from(value: Str) -> Self {
64        Self::Str(value)
65    }
66}
67
68/// A trait for types which can be unwrapped from a [`Value`].
69pub trait TryFromValue<T>: Sized {
70    fn try_from_value(value: Value<T>) -> Result<Self, Error>;
71}
72
73/// The type of a value.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
75pub enum Type {
76    /// A test.
77    Test,
78
79    /// A test set.
80    Set,
81
82    /// A function.
83    Func,
84
85    /// An unsigned integer.
86    Num,
87
88    /// A string.
89    Str,
90}
91
92impl Type {
93    /// The name of this type.
94    pub fn name(&self) -> &'static str {
95        match self {
96            Self::Test => "test",
97            Self::Set => "test set",
98            Self::Func => "function",
99            Self::Num => "number",
100            Self::Str => "string",
101        }
102    }
103}