1use std::borrow::Cow;
11use std::fmt;
12use std::hash::{Hash, Hasher};
13use std::mem::discriminant;
14use std::sync::Arc;
15
16use crate::color::Color;
17use crate::expression::forms::assertion::Assertion;
18use crate::expression::forms::at::At;
19use crate::expression::forms::case::Case;
20use crate::expression::forms::coalesce::Coalesce;
21use crate::expression::forms::coercion::Coercion;
22use crate::expression::forms::collator::CollatorExpression;
23use crate::expression::forms::comparison::Comparison;
24use crate::expression::forms::compound::CompoundExpression;
25use crate::expression::forms::distance::Distance;
26use crate::expression::forms::format::FormatExpression;
27use crate::expression::forms::format_section_override::FormatSectionOverride;
28use crate::expression::forms::image::ImageExpression;
29use crate::expression::forms::in_::In;
30use crate::expression::forms::index_of::IndexOf;
31use crate::expression::forms::interpolate::Interpolate;
32use crate::expression::forms::let_::{Let, Var};
33use crate::expression::forms::literal::Literal;
34use crate::expression::forms::match_::Match;
35use crate::expression::forms::number_format::NumberFormat;
36use crate::expression::forms::semiliteral::Semiliteral;
37use crate::expression::forms::slice::Slice;
38use crate::expression::forms::step::Step;
39use crate::expression::forms::within::Within;
40use crate::expression::type_::Type;
41use crate::expression::value::{Value, hash_value, type_of};
42use crate::expression::{Dependency, EvalResult, EvaluationContext, EvaluationError, EvaluationResult};
43use crate::feature::Value as FeatureValue;
44
45#[derive(Clone, PartialEq, mln_wire::Wire)]
47pub(crate) enum Node {
48 Literal(Box<Literal>),
49 Compound(Box<CompoundExpression>),
50 Assertion(Box<Assertion>),
51 Coercion(Box<Coercion>),
52 Comparison(Box<Comparison>),
53 All(Box<[Expr]>),
54 Any(Box<[Expr]>),
55 At(Box<At>),
56 In(Box<In>),
57 IndexOf(Box<IndexOf>),
58 Slice(Box<Slice>),
59 Length(Box<Expr>),
60 Case(Box<Case>),
61 Coalesce(Box<Coalesce>),
62 Match(Box<Match>),
63 Step(Box<Step>),
64 Interpolate(Box<Interpolate>),
65 Let(Box<Let>),
66 Var(Box<Var>),
67 Collator(Box<CollatorExpression>),
68 Format(Box<FormatExpression>),
69 Image(Box<ImageExpression>),
70 NumberFormat(Box<NumberFormat>),
71 Within(Box<Within>),
72 Distance(Box<Distance>),
73 Semiliteral(Box<Semiliteral>),
74 FormatSectionOverride(Box<FormatSectionOverride>),
75}
76
77#[derive(Clone)]
79pub struct Expr {
80 node: Node,
81 deps: Dependency,
83}
84
85impl mln_wire::Wire for Expr {
87 fn write(&self, w: &mut mln_wire::Writer) {
88 self.node.write(w);
89 }
90
91 fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
92 Node::read(r).map(Expr::new)
93 }
94}
95
96impl PartialEq for Expr {
97 fn eq(&self, other: &Self) -> bool {
98 self.node == other.node
99 }
100}
101
102impl fmt::Debug for Expr {
103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 write!(f, "Expression({:?})", self.serialize())
105 }
106}
107
108pub(crate) trait Output<'e>: Sized {
112 fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self>;
114
115 fn from_value(value: Value) -> EvalResult<Self>;
117}
118
119fn wrong_type(expected: &str, value: &Value) -> EvaluationError {
120 EvaluationError::new(format!(
121 "Expected value to be of type {expected}, but found {} instead.",
122 crate::expression::type_::to_string(&type_of(value))
123 ))
124}
125
126impl<'e> Output<'e> for f64 {
127 fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
128 e.eval_num(cx)
129 }
130 fn from_value(value: Value) -> EvalResult<Self> {
131 match value {
132 Value::Number(n) => Ok(n),
133 other => Err(wrong_type("number", &other)),
134 }
135 }
136}
137
138impl<'e> Output<'e> for bool {
139 fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
140 e.eval_bool(cx)
141 }
142 fn from_value(value: Value) -> EvalResult<Self> {
143 match value {
144 Value::Bool(b) => Ok(b),
145 other => Err(wrong_type("boolean", &other)),
146 }
147 }
148}
149
150impl<'e> Output<'e> for Cow<'e, str> {
151 fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
152 e.eval_str(cx)
153 }
154 fn from_value(value: Value) -> EvalResult<Self> {
155 match value {
156 Value::String(s) => Ok(Cow::Owned(s)),
157 other => Err(wrong_type("string", &other)),
158 }
159 }
160}
161
162impl<'e> Output<'e> for Color {
163 fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
164 e.eval_color(cx)
165 }
166 fn from_value(value: Value) -> EvalResult<Self> {
167 match value {
168 Value::Color(c) => Ok(c),
169 other => Err(wrong_type("color", &other)),
170 }
171 }
172}
173
174impl<'e> Output<'e> for Value {
175 fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
176 e.evaluate(cx)
177 }
178 fn from_value(value: Value) -> EvalResult<Self> {
179 Ok(value)
180 }
181}
182
183fn via_value<'e, T: Output<'e>>(e: &Expr, cx: &EvaluationContext<'_>) -> EvalResult<T> {
186 T::from_value(e.evaluate(cx)?)
187}
188
189impl Expr {
190 pub(crate) fn new(node: Node) -> Self {
191 let mut deps = node.own_dependencies();
192 node.each_child(&mut |child| deps |= child.deps);
193 Expr { node, deps }
194 }
195
196 pub(crate) fn node(&self) -> &Node {
197 &self.node
198 }
199
200 #[must_use]
202 pub fn literal(value: Value) -> Self {
203 Expr::new(Node::Literal(Box::new(Literal::new(value))))
204 }
205
206 #[must_use]
208 pub fn all(inputs: Vec<Expr>) -> Self {
209 Expr::new(Node::All(inputs.into()))
210 }
211
212 #[must_use]
214 pub fn any(inputs: Vec<Expr>) -> Self {
215 Expr::new(Node::Any(inputs.into()))
216 }
217
218 #[must_use]
220 pub fn type_(&self) -> Type {
221 match &self.node {
222 Node::Literal(l) => l.type_().clone(),
223 Node::Compound(c) => c.overload().result.clone(),
224 Node::Assertion(a) => a.type_().clone(),
225 Node::Coercion(c) => c.type_().clone(),
226 Node::Comparison(_) | Node::All(_) | Node::Any(_) | Node::In(_) | Node::Within(_) => Type::Boolean,
227 Node::At(a) => a.type_(),
228 Node::IndexOf(_) | Node::Length(_) | Node::Distance(_) => Type::Number,
229 Node::Slice(s) => s.type_(),
230 Node::Case(c) => c.type_().clone(),
231 Node::Coalesce(c) => c.type_().clone(),
232 Node::Match(m) => m.type_().clone(),
233 Node::Step(s) => s.type_().clone(),
234 Node::Interpolate(i) => i.type_().clone(),
235 Node::Let(l) => l.result().type_(),
236 Node::Var(v) => v.bound_expression().type_(),
237 Node::Collator(_) => Type::Collator,
238 Node::Format(_) => Type::Formatted,
239 Node::Image(_) => Type::Image,
240 Node::NumberFormat(_) => Type::String,
241 Node::Semiliteral(s) => s.type_(),
242 Node::FormatSectionOverride(_) => Type::Color,
243 }
244 }
245
246 #[must_use]
248 pub fn dependencies(&self) -> Dependency {
249 self.deps
250 }
251
252 #[must_use]
254 pub fn has(&self, dep: Dependency) -> bool {
255 self.deps.intersects(dep)
256 }
257
258 pub fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
261 self.node.each_child(visit);
262 }
263
264 #[must_use]
267 pub fn literal_value(&self) -> Option<&Value> {
268 match &self.node {
269 Node::Literal(l) => Some(l.value()),
270 _ => None,
271 }
272 }
273
274 #[must_use]
276 pub fn operator(&self) -> &str {
277 match &self.node {
278 Node::Literal(_) => "literal",
279 Node::Compound(c) => c.overload().name(),
280 Node::Assertion(a) => a.operator(),
281 Node::Coercion(c) => c.operator(),
282 Node::Comparison(c) => c.operator(),
283 Node::All(_) => "all",
284 Node::Any(_) => "any",
285 Node::At(_) => "at",
286 Node::In(_) => "in",
287 Node::IndexOf(_) => "index-of",
288 Node::Slice(_) => "slice",
289 Node::Length(_) => "length",
290 Node::Case(_) => "case",
291 Node::Coalesce(_) => "coalesce",
292 Node::Match(_) => "match",
293 Node::Step(_) => "step",
294 Node::Interpolate(i) => i.operator(),
295 Node::Let(_) => "let",
296 Node::Var(_) => "var",
297 Node::Collator(_) => "collator",
298 Node::Format(_) => "format",
299 Node::Image(_) => "image",
300 Node::NumberFormat(_) => "number-format",
301 Node::Within(_) => "within",
302 Node::Distance(_) => "distance",
303 Node::Semiliteral(_) => "semiliteral",
304 Node::FormatSectionOverride(_) => "format-section-override",
305 }
306 }
307
308 #[must_use]
311 pub fn serialize(&self) -> FeatureValue {
312 match &self.node {
313 Node::Literal(l) => l.serialize(),
314 Node::Compound(c) => c.serialize(),
315 Node::Assertion(a) => a.serialize(),
316 Node::Coercion(c) => c.serialize(),
317 Node::Comparison(c) => c.serialize(),
318 Node::Interpolate(i) => i.serialize(),
319 Node::Step(s) => s.serialize(),
320 Node::Match(m) => m.serialize(),
321 Node::Let(l) => l.serialize(),
322 Node::Var(v) => v.serialize(),
323 Node::Collator(c) => c.serialize(),
324 Node::Format(f) => f.serialize(),
325 Node::Image(i) => i.serialize(),
326 Node::NumberFormat(n) => n.serialize(),
327 Node::Within(w) => w.serialize(),
328 Node::Distance(d) => d.serialize(),
329 Node::Semiliteral(s) => s.serialize(),
330 Node::FormatSectionOverride(o) => o.serialize(),
331 Node::All(_)
332 | Node::Any(_)
333 | Node::At(_)
334 | Node::In(_)
335 | Node::Length(_)
336 | Node::Case(_)
337 | Node::Coalesce(_)
338 | Node::IndexOf(_)
339 | Node::Slice(_) => self.default_serialize(),
340 }
341 }
342
343 pub(crate) fn default_serialize(&self) -> FeatureValue {
345 let mut serialized = vec![FeatureValue::String(self.operator().to_owned())];
346 self.each_child(&mut |child| serialized.push(child.serialize()));
347 FeatureValue::Array(serialized)
348 }
349
350 #[must_use]
353 pub fn possible_outputs(&self) -> Vec<Option<Value>> {
354 match &self.node {
355 Node::Literal(l) => vec![Some(l.value().clone())],
356 Node::Compound(c) => {
357 if c.overload().result == Type::Error {
358 Vec::new()
359 } else {
360 vec![None]
361 }
362 }
363 Node::All(_) | Node::Any(_) | Node::In(_) | Node::Comparison(_) | Node::Within(_) => {
364 vec![Some(Value::Bool(true)), Some(Value::Bool(false))]
365 }
366 Node::Assertion(_)
367 | Node::Coercion(_)
368 | Node::Case(_)
369 | Node::Coalesce(_)
370 | Node::Match(_)
371 | Node::Step(_) => {
372 let mut result = Vec::new();
373 match &self.node {
374 Node::Case(c) => c.each_output(&mut |e| result.extend(e.possible_outputs())),
375 Node::Match(m) => m.each_output(&mut |e| result.extend(e.possible_outputs())),
376 Node::Step(s) => s.each_output(&mut |e| result.extend(e.possible_outputs())),
377 _ => self.each_child(&mut |e| result.extend(e.possible_outputs())),
378 }
379 result
380 }
381 Node::Let(l) => l.result().possible_outputs(),
382 _ => vec![None],
383 }
384 }
385
386 pub fn hash_structure(&self, state: &mut dyn Hasher) {
389 let mut state = state;
390 discriminant(&self.node).hash(&mut state);
391 match &self.node {
392 Node::Literal(l) => hash_value(l.value(), state),
393 Node::Compound(c) => c.overload().name().hash(&mut state),
394 Node::Comparison(c) => c.operator().hash(&mut state),
395 Node::Assertion(_) | Node::Coercion(_) => self.type_().hash(&mut state),
396 Node::Var(v) => v.name().hash(&mut state),
397 _ => {}
398 }
399 self.each_child(&mut |child| child.hash_structure(state));
400 }
401
402 pub(crate) fn as_compound(&self) -> Option<&CompoundExpression> {
404 match &self.node {
405 Node::Compound(c) => Some(c),
406 _ => None,
407 }
408 }
409
410 #[must_use]
415 pub fn as_equality(&self) -> Option<(&Expr, &Value)> {
416 match &self.node {
417 Node::Comparison(c) => c.as_equality(),
418 _ => None,
419 }
420 }
421
422 #[must_use]
424 pub fn as_interpolate(&self) -> Option<&Interpolate> {
425 match &self.node {
426 Node::Interpolate(i) => Some(i),
427 _ => None,
428 }
429 }
430
431 #[must_use]
433 pub fn as_format(&self) -> Option<&FormatExpression> {
434 match &self.node {
435 Node::Format(f) => Some(f),
436 _ => None,
437 }
438 }
439
440 #[must_use]
442 pub fn as_format_section_override(&self) -> Option<&FormatSectionOverride> {
443 match &self.node {
444 Node::FormatSectionOverride(o) => Some(o),
445 _ => None,
446 }
447 }
448
449 pub fn evaluate(&self, cx: &EvaluationContext<'_>) -> EvaluationResult {
451 match &self.node {
452 Node::Literal(l) => Ok(l.value().clone()),
453 Node::Compound(c) => c.evaluate(cx),
454 Node::Assertion(a) => a.evaluate(cx),
455 Node::Coercion(c) => c.evaluate(cx),
456 Node::Comparison(c) => c.eval_bool(cx).map(Value::Bool),
457 Node::All(_) | Node::Any(_) | Node::In(_) | Node::Within(_) => self.eval_bool(cx).map(Value::Bool),
458 Node::IndexOf(_) | Node::Length(_) | Node::Distance(_) => self.eval_num(cx).map(Value::Number),
459 Node::NumberFormat(_) => self.eval_str(cx).map(|s| Value::String(s.into_owned())),
460 Node::FormatSectionOverride(_) => self.eval_color(cx).map(Value::Color),
461 Node::At(a) => a.evaluate(cx),
462 Node::Slice(s) => s.evaluate(cx),
463 Node::Case(c) => c.eval::<Value>(cx),
464 Node::Coalesce(c) => c.evaluate(cx),
465 Node::Match(m) => m.eval::<Value>(cx),
466 Node::Step(s) => s.eval::<Value>(cx),
467 Node::Interpolate(i) => i.evaluate(cx),
468 Node::Let(l) => l.result().evaluate(cx),
469 Node::Var(v) => v.bound_expression().evaluate(cx),
470 Node::Collator(c) => c.evaluate(cx),
471 Node::Format(f) => f.evaluate(cx),
472 Node::Image(i) => i.evaluate(cx),
473 Node::Semiliteral(s) => s.evaluate(cx),
474 }
475 }
476
477 pub fn evaluate_typed(&self, cx: &EvaluationContext<'_>) -> EvaluationResult {
483 match self.type_() {
484 Type::Number => self.eval_num(cx).map(Value::Number),
485 Type::Boolean => self.eval_bool(cx).map(Value::Bool),
486 Type::String => self.eval_str(cx).map(|s| Value::String(s.into_owned())),
487 Type::Color => self.eval_color(cx).map(Value::Color),
488 _ => self.evaluate(cx),
489 }
490 }
491
492 pub(crate) fn evaluate_ref<'e>(&'e self, cx: &EvaluationContext<'_>) -> EvalResult<Cow<'e, Value>> {
495 match &self.node {
496 Node::Literal(l) => Ok(Cow::Borrowed(l.value())),
497 _ => self.evaluate(cx).map(Cow::Owned),
498 }
499 }
500
501 pub fn eval_num(&self, cx: &EvaluationContext<'_>) -> EvalResult<f64> {
503 match &self.node {
504 Node::Literal(l) => match l.value() {
505 Value::Number(n) => Ok(*n),
506 other => f64::from_value(other.clone()),
507 },
508 Node::Compound(c) => c.eval_num(cx),
509 Node::Assertion(a) => a.eval_num(cx),
510 Node::Coercion(c) => c.eval_num(cx),
511 Node::Case(c) => c.eval(cx),
512 Node::Match(m) => m.eval(cx),
513 Node::Step(s) => s.eval(cx),
514 Node::Coalesce(c) => c.eval_typed(cx, &Type::Number),
515 Node::Interpolate(i) => i.eval_num(cx),
516 Node::Let(l) => l.result().eval_num(cx),
517 Node::Var(v) => v.bound_expression().eval_num(cx),
518 Node::Length(input) => crate::expression::forms::length::evaluate(input, cx),
519 Node::IndexOf(i) => i.eval_num(cx),
520 Node::Distance(d) => d.eval_num(cx),
521 _ => via_value(self, cx),
522 }
523 }
524
525 pub fn eval_bool(&self, cx: &EvaluationContext<'_>) -> EvalResult<bool> {
527 match &self.node {
528 Node::Literal(l) => match l.value() {
529 Value::Bool(b) => Ok(*b),
530 other => bool::from_value(other.clone()),
531 },
532 Node::Compound(c) => c.eval_bool(cx),
533 Node::Comparison(c) => c.eval_bool(cx),
534 Node::All(inputs) => {
535 for input in inputs {
536 if !input.eval_bool(cx)? {
537 return Ok(false);
538 }
539 }
540 Ok(true)
541 }
542 Node::Any(inputs) => {
543 for input in inputs {
544 if input.eval_bool(cx)? {
545 return Ok(true);
546 }
547 }
548 Ok(false)
549 }
550 Node::Assertion(a) => a.eval_bool(cx),
551 Node::Coercion(c) => c.eval_bool(cx),
552 Node::Case(c) => c.eval(cx),
553 Node::Match(m) => m.eval(cx),
554 Node::Step(s) => s.eval(cx),
555 Node::Coalesce(c) => c.eval_typed(cx, &Type::Boolean),
556 Node::Let(l) => l.result().eval_bool(cx),
557 Node::Var(v) => v.bound_expression().eval_bool(cx),
558 Node::In(i) => i.eval_bool(cx),
559 Node::Within(w) => Ok(w.eval_bool(cx)),
560 _ => via_value(self, cx),
561 }
562 }
563
564 pub fn eval_str<'e>(&'e self, cx: &EvaluationContext<'_>) -> EvalResult<Cow<'e, str>> {
566 match &self.node {
567 Node::Literal(l) => match l.value() {
568 Value::String(s) => Ok(Cow::Borrowed(s)),
569 other => Cow::from_value(other.clone()),
570 },
571 Node::Compound(c) => c.eval_str(cx),
572 Node::Assertion(a) => a.eval_str(cx),
573 Node::Coercion(c) => c.eval_str(cx),
574 Node::Case(c) => c.eval(cx),
575 Node::Match(m) => m.eval(cx),
576 Node::Step(s) => s.eval(cx),
577 Node::Coalesce(c) => c.eval_typed(cx, &Type::String),
578 Node::Let(l) => l.result().eval_str(cx),
579 Node::Var(v) => v.bound_expression().eval_str(cx),
580 Node::NumberFormat(n) => n.eval_str(cx).map(Cow::Owned),
581 _ => via_value(self, cx),
582 }
583 }
584
585 pub fn eval_color(&self, cx: &EvaluationContext<'_>) -> EvalResult<Color> {
587 match &self.node {
588 Node::Literal(l) => match l.value() {
589 Value::Color(c) => Ok(*c),
590 other => Color::from_value(other.clone()),
591 },
592 Node::Compound(c) => c.eval_color(cx),
593 Node::Coercion(c) => c.eval_color(cx),
594 Node::Case(c) => c.eval(cx),
595 Node::Match(m) => m.eval(cx),
596 Node::Step(s) => s.eval(cx),
597 Node::Coalesce(c) => c.eval_typed(cx, &Type::Color),
598 Node::Interpolate(i) => i.eval_color(cx),
599 Node::Let(l) => l.result().eval_color(cx),
600 Node::Var(v) => v.bound_expression().eval_color(cx),
601 Node::FormatSectionOverride(o) => o.eval_color(cx),
602 _ => via_value(self, cx),
603 }
604 }
605}
606
607impl Node {
608 fn own_dependencies(&self) -> Dependency {
610 match self {
611 Node::Compound(c) => c.overload().dependencies,
612 Node::Let(_) => Dependency::BIND,
613 Node::Var(v) => Dependency::VAR | v.bound_expression().deps,
614 Node::Collator(_) | Node::Within(_) | Node::Distance(_) => Dependency::FEATURE,
615 Node::Image(_) => Dependency::IMAGE,
616 Node::FormatSectionOverride(_) => Dependency::OVERRIDE | Dependency::FEATURE,
617 _ => Dependency::NONE,
618 }
619 }
620
621 fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
622 match self {
623 Node::Literal(_) | Node::Var(_) | Node::Within(_) | Node::Distance(_) => {}
624 Node::FormatSectionOverride(o) => o.each_child(visit),
625 Node::Compound(c) => c.args().iter().for_each(visit),
626 Node::Assertion(a) => a.inputs().iter().for_each(visit),
627 Node::Coercion(c) => c.inputs().iter().for_each(visit),
628 Node::Comparison(c) => c.each_child(visit),
629 Node::All(inputs) | Node::Any(inputs) => inputs.iter().for_each(visit),
630 Node::At(a) => a.each_child(visit),
631 Node::In(i) => i.each_child(visit),
632 Node::IndexOf(i) => i.each_child(visit),
633 Node::Slice(s) => s.each_child(visit),
634 Node::Length(input) => visit(input),
635 Node::Case(c) => c.each_child(visit),
636 Node::Coalesce(c) => c.args().iter().for_each(visit),
637 Node::Match(m) => m.each_child(visit),
638 Node::Step(s) => s.each_child(visit),
639 Node::Interpolate(i) => i.each_child(visit),
640 Node::Let(l) => l.each_child(visit),
641 Node::Collator(c) => c.each_child(visit),
642 Node::Format(f) => f.each_child(visit),
643 Node::Image(i) => visit(i.image_id()),
644 Node::NumberFormat(n) => n.each_child(visit),
645 Node::Semiliteral(s) => s.elements().iter().for_each(visit),
646 }
647 }
648}
649
650pub(crate) type SharedExpr = Arc<Expr>;