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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
use crate::css::{is_function_name, CssString, InvalidCss, Value};
use crate::value::{ListSeparator, Numeric};
use std::fmt;
/// An operator that can be used in a sass value.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Operator {
/// The boolean (value propagating) `and` operator.
And,
/// The boolean (value propagating) `or` operator.
Or,
/// The `==` operator.
Equal,
/// The `=` operator. Used insted of Equal in media queries.
EqualSingle,
/// The `!=` operator.
NotEqual,
/// The `>` operator.
Greater,
/// The `>=` operator.
GreaterE,
/// The `<` operator.
Lesser,
/// The `<=` operator.
LesserE,
/// The `+` operator. Also unary positive.
Plus,
/// The `-` operator. Also unary negative.
Minus,
/// The `*` operator.
Multiply,
/// The `/` operator.
Div,
/// The `%` operator.
Modulo,
/// The unary `not` operator.
Not,
}
impl Operator {
/// Evaluate this operator with two operands.
///
/// Some operations are known to be invalid, and for those an
/// error is returned.
/// Other operations cannot be evaluated but may be valid as is
/// e.g. in a `calc(...)` value. In that case, eval returns
/// Ok(None).
pub fn eval(&self, a: Value, b: Value) -> Result<Option<Value>, BadOp> {
fn cmp(
a: Value,
b: Value,
op: &dyn Fn(Value, Value) -> bool,
) -> Option<Value> {
match (&a, &b) {
(Value::Numeric(..), Value::Numeric(..))
| (Value::Literal(_), Value::Literal(..)) => {
Some(Value::from(op(a, b)))
}
_ => None,
}
}
Ok(match *self {
Self::And => Some(if a.is_true() { b } else { a }),
Self::Or => Some(if a.is_true() { a } else { b }),
Self::Equal => Some(Value::from(a == b)),
Self::EqualSingle => cmp(a, b, &|a, b| a == b),
Self::NotEqual => Some(Value::from(a != b)),
Self::Greater => cmp(a, b, &|a, b| a > b),
Self::GreaterE => cmp(a, b, &|a, b| a >= b),
Self::Lesser => cmp(a, b, &|a, b| a < b),
Self::LesserE => cmp(a, b, &|a, b| a <= b),
Self::Plus => match (a, b) {
(Value::Numeric(a, _), Value::Numeric(b, _)) => {
if a.unit == b.unit || b.is_no_unit() {
Some(Numeric::new(a.value + b.value, a.unit).into())
} else if a.is_no_unit() {
Some(Numeric::new(a.value + b.value, b.unit).into())
} else if let Some(scaled) = b.as_unitset(&a.unit) {
Some(Numeric::new(a.value + scaled, a.unit).into())
} else {
None
}
}
(Value::Literal(a), Value::Literal(b)) => {
let val = format!("{}{}", a.value(), b.value());
Some(CssString::new(val, a.quotes()).into())
}
(Value::Literal(a), b) if !a.is_css_fn() => {
let join = format!(
"{}{}",
a.value(),
b.format(Default::default())
);
Some(CssString::new(join, a.quotes()).into())
}
(a, Value::Literal(b)) if !b.is_css_fn() => {
let join = format!(
"{}{}",
a.format(Default::default()),
b.value()
);
Some(CssString::new(join, b.quotes()).into())
}
(a, b) => {
if (add_as_join(&a) || add_as_join(&b))
|| (valid_operand(&a) && valid_operand(&b))
{
None
} else {
a.valid_css()?;
b.valid_css()?;
return Err(BadOp::UndefinedOperation);
}
}
},
Self::Minus => match (a, b) {
(Value::Numeric(a, _), Value::Numeric(b, _)) => {
if a.unit == b.unit || b.is_no_unit() {
Some(Numeric::new(&a.value - &b.value, a.unit).into())
} else if a.is_no_unit() {
Some(Numeric::new(&a.value - &b.value, b.unit).into())
} else if let Some(scaled) = b.as_unitset(&a.unit) {
Some(Numeric::new(&a.value - &scaled, a.unit).into())
} else {
None
}
}
// Note: This very special case should probably be much
// more general.
(a @ Value::UnicodeRange(..), b @ Value::Literal(..)) => {
Some(Value::List(
vec![a, Value::UnaryOp(Self::Minus, Box::new(b))],
Some(ListSeparator::Space),
false,
))
}
(Value::UnicodeRange(..), Value::Numeric(..)) => None,
(a, b) => {
if (add_as_join(&a) || add_as_join(&b))
|| (valid_operand(&a) && valid_operand(&b))
{
None
} else {
a.valid_css()?;
b.valid_css()?;
return Err(BadOp::UndefinedOperation);
}
}
},
Self::Multiply => match (a, b) {
(Value::Numeric(ref a, _), Value::Numeric(ref b, _)) => {
Some((a * b).into())
}
(a, b) if valid_operand(&a) && valid_operand(&b) => None,
_ => return Err(BadOp::UndefinedOperation),
},
Self::Div => match (a, b) {
(Value::Color(..), Value::Numeric(..)) => {
return Err(BadOp::UndefinedOperation)
}
(Value::Color(..), Value::Color(..)) => {
return Err(BadOp::UndefinedOperation)
}
(Value::Numeric(ref a, a_c), Value::Numeric(ref b, b_c))
if a_c || b_c =>
{
Some((a / b).into())
}
_ => None,
},
Self::Modulo => match (a, b) {
(Value::Numeric(a, _), Value::Numeric(b, _)) => {
if a.unit == b.unit || b.is_no_unit() {
Some(Numeric::new(&a.value % &b.value, a.unit).into())
} else {
None
}
}
(a, b) if valid_operand(&a) && valid_operand(&b) => None,
_ => return Err(BadOp::UndefinedOperation),
},
Self::Not => return Err(BadOp::UndefinedOperation),
})
}
pub(crate) fn is_cmp(self) -> bool {
matches!(
self,
Self::Equal
| Self::EqualSingle
| Self::NotEqual
| Self::Greater
| Self::GreaterE
| Self::Lesser
| Self::LesserE
)
}
}
fn valid_operand(v: &Value) -> bool {
match v {
Value::Numeric(..)
| Value::Call(..)
| Value::BinOp(_)
| Value::Literal(_) => true,
Value::Paren(v) => valid_operand(v),
_ => false,
}
}
fn add_as_join(v: &Value) -> bool {
match v {
Value::List(..) | Value::True | Value::False => true,
Value::Literal(ref s) => !s.is_css_fn(),
Value::Call(ref name, _) => !is_function_name(name),
Value::BinOp(op) => op.add_as_join(),
_ => false,
}
}
impl fmt::Display for Operator {
fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
out.write_str(match *self {
Self::And => "and",
Self::Or => "or",
Self::Equal => "==",
Self::EqualSingle => "=",
Self::NotEqual => "!=",
Self::Greater => ">",
Self::GreaterE => ">=",
Self::Lesser => "<",
Self::LesserE => "<=",
Self::Plus => "+",
Self::Minus => "-",
Self::Multiply => "*",
Self::Modulo => "%",
Self::Div => "/",
Self::Not => "not",
})
}
}
/// Something went wrong when evaluating an operator.
pub enum BadOp {
/// An undefined operation (e.g. adding incompatible units) were attempted.
UndefinedOperation,
/// A potentially valid operation, but with invalid operands.
Invalid(InvalidCss),
}
impl From<InvalidCss> for BadOp {
fn from(value: InvalidCss) -> Self {
Self::Invalid(value)
}
}