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
use std::fmt;
use liquid_error::Result;
use liquid_value::Scalar;
use liquid_value::Value;
use liquid_value::ValueCow;
use liquid_value::ValueView;
use super::Runtime;
use crate::variable::Variable;
#[derive(Debug, Clone, PartialEq)]
pub enum Expression {
Variable(Variable),
Literal(Value),
}
impl Expression {
pub fn with_literal<S: Into<Scalar>>(literal: S) -> Self {
Expression::Literal(Value::scalar(literal))
}
pub fn into_literal(self) -> Option<Value> {
match self {
Expression::Literal(x) => Some(x),
Expression::Variable(_) => None,
}
}
pub fn into_variable(self) -> Option<Variable> {
match self {
Expression::Literal(_) => None,
Expression::Variable(x) => Some(x),
}
}
pub fn try_evaluate<'c>(&'c self, runtime: &'c Runtime<'_>) -> Option<ValueCow<'c>> {
match self {
Expression::Literal(ref x) => Some(ValueCow::Borrowed(x)),
Expression::Variable(ref x) => {
let path = x.try_evaluate(runtime)?;
runtime.stack().try_get(&path)
}
}
}
pub fn evaluate<'c>(&'c self, runtime: &'c Runtime<'_>) -> Result<ValueCow<'c>> {
let val = match self {
Expression::Literal(ref x) => ValueCow::Borrowed(x),
Expression::Variable(ref x) => {
let path = x.evaluate(runtime)?;
runtime.stack().get(&path)?
}
};
Ok(val)
}
}
impl fmt::Display for Expression {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Expression::Literal(ref x) => write!(f, "{}", x.source()),
Expression::Variable(ref x) => write!(f, "{}", x),
}
}
}