mln-rs-style 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! A parsed, type-checked expression ([`Expr`]) and its evaluation.
//!
//! An `Expr` is a closed tree with a fixed set of node kinds. The parser
//! fixes every node's type, so evaluation is typed: a number-typed node
//! evaluates to an `f64` with [`Expr::eval_num`], a filter to a `bool` with
//! [`Expr::eval_bool`], and so on, without building a [`Value`] per node or
//! checking again what the parser proved. [`Expr::evaluate`] gives any node's
//! result as a `Value`, for callers whose type is only known at run time.

use std::borrow::Cow;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::mem::discriminant;
use std::sync::Arc;

use crate::color::Color;
use crate::expression::forms::assertion::Assertion;
use crate::expression::forms::at::At;
use crate::expression::forms::case::Case;
use crate::expression::forms::coalesce::Coalesce;
use crate::expression::forms::coercion::Coercion;
use crate::expression::forms::collator::CollatorExpression;
use crate::expression::forms::comparison::Comparison;
use crate::expression::forms::compound::CompoundExpression;
use crate::expression::forms::distance::Distance;
use crate::expression::forms::format::FormatExpression;
use crate::expression::forms::format_section_override::FormatSectionOverride;
use crate::expression::forms::image::ImageExpression;
use crate::expression::forms::in_::In;
use crate::expression::forms::index_of::IndexOf;
use crate::expression::forms::interpolate::Interpolate;
use crate::expression::forms::let_::{Let, Var};
use crate::expression::forms::literal::Literal;
use crate::expression::forms::match_::Match;
use crate::expression::forms::number_format::NumberFormat;
use crate::expression::forms::semiliteral::Semiliteral;
use crate::expression::forms::slice::Slice;
use crate::expression::forms::step::Step;
use crate::expression::forms::within::Within;
use crate::expression::type_::Type;
use crate::expression::value::{Value, hash_value, type_of};
use crate::expression::{Dependency, EvalResult, EvaluationContext, EvaluationError, EvaluationResult};
use crate::feature::Value as FeatureValue;

/// The kinds of expression node. Each holds its own operands.
#[derive(Clone, PartialEq, mln_wire::Wire)]
pub(crate) enum Node {
    Literal(Box<Literal>),
    Compound(Box<CompoundExpression>),
    Assertion(Box<Assertion>),
    Coercion(Box<Coercion>),
    Comparison(Box<Comparison>),
    All(Box<[Expr]>),
    Any(Box<[Expr]>),
    At(Box<At>),
    In(Box<In>),
    IndexOf(Box<IndexOf>),
    Slice(Box<Slice>),
    Length(Box<Expr>),
    Case(Box<Case>),
    Coalesce(Box<Coalesce>),
    Match(Box<Match>),
    Step(Box<Step>),
    Interpolate(Box<Interpolate>),
    Let(Box<Let>),
    Var(Box<Var>),
    Collator(Box<CollatorExpression>),
    Format(Box<FormatExpression>),
    Image(Box<ImageExpression>),
    NumberFormat(Box<NumberFormat>),
    Within(Box<Within>),
    Distance(Box<Distance>),
    Semiliteral(Box<Semiliteral>),
    FormatSectionOverride(Box<FormatSectionOverride>),
}

/// A parsed, type-checked expression.
#[derive(Clone)]
pub struct Expr {
    node: Node,
    /// The inputs of the node and its operands.
    deps: Dependency,
}

/// An expression crosses as its node tree; its dependencies follow from it.
impl mln_wire::Wire for Expr {
    fn write(&self, w: &mut mln_wire::Writer) {
        self.node.write(w);
    }

    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
        Node::read(r).map(Expr::new)
    }
}

impl PartialEq for Expr {
    fn eq(&self, other: &Self) -> bool {
        self.node == other.node
    }
}

impl fmt::Debug for Expr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Expression({:?})", self.serialize())
    }
}

/// A result type that typed evaluation produces, so that the nodes that
/// pass on an operand's result (`case`, `match`, `step`, `let`, ...) are
/// written once.
pub(crate) trait Output<'e>: Sized {
    /// Evaluates `e`, whose type is this output's.
    fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self>;

    /// Converts a value read at run time, from an array or a feature, say.
    fn from_value(value: Value) -> EvalResult<Self>;
}

fn wrong_type(expected: &str, value: &Value) -> EvaluationError {
    EvaluationError::new(format!(
        "Expected value to be of type {expected}, but found {} instead.",
        crate::expression::type_::to_string(&type_of(value))
    ))
}

impl<'e> Output<'e> for f64 {
    fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
        e.eval_num(cx)
    }
    fn from_value(value: Value) -> EvalResult<Self> {
        match value {
            Value::Number(n) => Ok(n),
            other => Err(wrong_type("number", &other)),
        }
    }
}

impl<'e> Output<'e> for bool {
    fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
        e.eval_bool(cx)
    }
    fn from_value(value: Value) -> EvalResult<Self> {
        match value {
            Value::Bool(b) => Ok(b),
            other => Err(wrong_type("boolean", &other)),
        }
    }
}

impl<'e> Output<'e> for Cow<'e, str> {
    fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
        e.eval_str(cx)
    }
    fn from_value(value: Value) -> EvalResult<Self> {
        match value {
            Value::String(s) => Ok(Cow::Owned(s)),
            other => Err(wrong_type("string", &other)),
        }
    }
}

impl<'e> Output<'e> for Color {
    fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
        e.eval_color(cx)
    }
    fn from_value(value: Value) -> EvalResult<Self> {
        match value {
            Value::Color(c) => Ok(c),
            other => Err(wrong_type("color", &other)),
        }
    }
}

impl<'e> Output<'e> for Value {
    fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
        e.evaluate(cx)
    }
    fn from_value(value: Value) -> EvalResult<Self> {
        Ok(value)
    }
}

/// Evaluates `e` for a typed caller whose node has no typed path of its own,
/// through its value.
fn via_value<'e, T: Output<'e>>(e: &Expr, cx: &EvaluationContext<'_>) -> EvalResult<T> {
    T::from_value(e.evaluate(cx)?)
}

impl Expr {
    pub(crate) fn new(node: Node) -> Self {
        let mut deps = node.own_dependencies();
        node.each_child(&mut |child| deps |= child.deps);
        Expr { node, deps }
    }

    pub(crate) fn node(&self) -> &Node {
        &self.node
    }

    /// A literal of `value`, typed as the value is.
    #[must_use]
    pub fn literal(value: Value) -> Self {
        Expr::new(Node::Literal(Box::new(Literal::new(value))))
    }

    /// `["all", ...]`.
    #[must_use]
    pub fn all(inputs: Vec<Expr>) -> Self {
        Expr::new(Node::All(inputs.into()))
    }

    /// `["any", ...]`.
    #[must_use]
    pub fn any(inputs: Vec<Expr>) -> Self {
        Expr::new(Node::Any(inputs.into()))
    }

    /// The node's static type.
    #[must_use]
    pub fn type_(&self) -> Type {
        match &self.node {
            Node::Literal(l) => l.type_().clone(),
            Node::Compound(c) => c.overload().result.clone(),
            Node::Assertion(a) => a.type_().clone(),
            Node::Coercion(c) => c.type_().clone(),
            Node::Comparison(_) | Node::All(_) | Node::Any(_) | Node::In(_) | Node::Within(_) => Type::Boolean,
            Node::At(a) => a.type_(),
            Node::IndexOf(_) | Node::Length(_) | Node::Distance(_) => Type::Number,
            Node::Slice(s) => s.type_(),
            Node::Case(c) => c.type_().clone(),
            Node::Coalesce(c) => c.type_().clone(),
            Node::Match(m) => m.type_().clone(),
            Node::Step(s) => s.type_().clone(),
            Node::Interpolate(i) => i.type_().clone(),
            Node::Let(l) => l.result().type_(),
            Node::Var(v) => v.bound_expression().type_(),
            Node::Collator(_) => Type::Collator,
            Node::Format(_) => Type::Formatted,
            Node::Image(_) => Type::Image,
            Node::NumberFormat(_) => Type::String,
            Node::Semiliteral(s) => s.type_(),
            Node::FormatSectionOverride(_) => Type::Color,
        }
    }

    /// The inputs the expression depends on.
    #[must_use]
    pub fn dependencies(&self) -> Dependency {
        self.deps
    }

    /// Whether the expression depends on any of the inputs in `dep`.
    #[must_use]
    pub fn has(&self, dep: Dependency) -> bool {
        self.deps.intersects(dep)
    }

    /// Visits the node's operands, in the order the style specification
    /// writes them.
    pub fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
        self.node.each_child(visit);
    }

    /// The value of a literal, which callers can borrow; `None` for any
    /// other node.
    #[must_use]
    pub fn literal_value(&self) -> Option<&Value> {
        match &self.node {
            Node::Literal(l) => Some(l.value()),
            _ => None,
        }
    }

    /// The expression's name in the style specification.
    #[must_use]
    pub fn operator(&self) -> &str {
        match &self.node {
            Node::Literal(_) => "literal",
            Node::Compound(c) => c.overload().name(),
            Node::Assertion(a) => a.operator(),
            Node::Coercion(c) => c.operator(),
            Node::Comparison(c) => c.operator(),
            Node::All(_) => "all",
            Node::Any(_) => "any",
            Node::At(_) => "at",
            Node::In(_) => "in",
            Node::IndexOf(_) => "index-of",
            Node::Slice(_) => "slice",
            Node::Length(_) => "length",
            Node::Case(_) => "case",
            Node::Coalesce(_) => "coalesce",
            Node::Match(_) => "match",
            Node::Step(_) => "step",
            Node::Interpolate(i) => i.operator(),
            Node::Let(_) => "let",
            Node::Var(_) => "var",
            Node::Collator(_) => "collator",
            Node::Format(_) => "format",
            Node::Image(_) => "image",
            Node::NumberFormat(_) => "number-format",
            Node::Within(_) => "within",
            Node::Distance(_) => "distance",
            Node::Semiliteral(_) => "semiliteral",
            Node::FormatSectionOverride(_) => "format-section-override",
        }
    }

    /// The expression as the style specification's JSON, which parses back
    /// to an expression that evaluates alike.
    #[must_use]
    pub fn serialize(&self) -> FeatureValue {
        match &self.node {
            Node::Literal(l) => l.serialize(),
            Node::Compound(c) => c.serialize(),
            Node::Assertion(a) => a.serialize(),
            Node::Coercion(c) => c.serialize(),
            Node::Comparison(c) => c.serialize(),
            Node::Interpolate(i) => i.serialize(),
            Node::Step(s) => s.serialize(),
            Node::Match(m) => m.serialize(),
            Node::Let(l) => l.serialize(),
            Node::Var(v) => v.serialize(),
            Node::Collator(c) => c.serialize(),
            Node::Format(f) => f.serialize(),
            Node::Image(i) => i.serialize(),
            Node::NumberFormat(n) => n.serialize(),
            Node::Within(w) => w.serialize(),
            Node::Distance(d) => d.serialize(),
            Node::Semiliteral(s) => s.serialize(),
            Node::FormatSectionOverride(o) => o.serialize(),
            Node::All(_)
            | Node::Any(_)
            | Node::At(_)
            | Node::In(_)
            | Node::Length(_)
            | Node::Case(_)
            | Node::Coalesce(_)
            | Node::IndexOf(_)
            | Node::Slice(_) => self.default_serialize(),
        }
    }

    /// The operator followed by each operand, serialized.
    pub(crate) fn default_serialize(&self) -> FeatureValue {
        let mut serialized = vec![FeatureValue::String(self.operator().to_owned())];
        self.each_child(&mut |child| serialized.push(child.serialize()));
        FeatureValue::Array(serialized)
    }

    /// Statically analyzes the expression, enumerating its possible outputs.
    /// A `None` entry means the complete set is statically undecidable.
    #[must_use]
    pub fn possible_outputs(&self) -> Vec<Option<Value>> {
        match &self.node {
            Node::Literal(l) => vec![Some(l.value().clone())],
            Node::Compound(c) => {
                if c.overload().result == Type::Error {
                    Vec::new()
                } else {
                    vec![None]
                }
            }
            Node::All(_) | Node::Any(_) | Node::In(_) | Node::Comparison(_) | Node::Within(_) => {
                vec![Some(Value::Bool(true)), Some(Value::Bool(false))]
            }
            Node::Assertion(_)
            | Node::Coercion(_)
            | Node::Case(_)
            | Node::Coalesce(_)
            | Node::Match(_)
            | Node::Step(_) => {
                let mut result = Vec::new();
                match &self.node {
                    Node::Case(c) => c.each_output(&mut |e| result.extend(e.possible_outputs())),
                    Node::Match(m) => m.each_output(&mut |e| result.extend(e.possible_outputs())),
                    Node::Step(s) => s.each_output(&mut |e| result.extend(e.possible_outputs())),
                    _ => self.each_child(&mut |e| result.extend(e.possible_outputs())),
                }
                result
            }
            Node::Let(l) => l.result().possible_outputs(),
            _ => vec![None],
        }
    }

    /// Feeds `state` the expression's structure, so that equal expressions
    /// hash alike.
    pub fn hash_structure(&self, state: &mut dyn Hasher) {
        let mut state = state;
        discriminant(&self.node).hash(&mut state);
        match &self.node {
            Node::Literal(l) => hash_value(l.value(), state),
            Node::Compound(c) => c.overload().name().hash(&mut state),
            Node::Comparison(c) => c.operator().hash(&mut state),
            Node::Assertion(_) | Node::Coercion(_) => self.type_().hash(&mut state),
            Node::Var(v) => v.name().hash(&mut state),
            _ => {}
        }
        self.each_child(&mut |child| child.hash_structure(state));
    }

    /// The node as a compound expression, if it is one.
    pub(crate) fn as_compound(&self) -> Option<&CompoundExpression> {
        match &self.node {
            Node::Compound(c) => Some(c),
            _ => None,
        }
    }

    /// The operand and the literal of `["==", operand, literal]` (or with
    /// the literal first), when the expression is such an equality: it holds
    /// for a feature exactly when the operand evaluates to a value equal to
    /// the literal.
    #[must_use]
    pub fn as_equality(&self) -> Option<(&Expr, &Value)> {
        match &self.node {
            Node::Comparison(c) => c.as_equality(),
            _ => None,
        }
    }

    /// The node as an `interpolate` expression, if it is one.
    #[must_use]
    pub fn as_interpolate(&self) -> Option<&Interpolate> {
        match &self.node {
            Node::Interpolate(i) => Some(i),
            _ => None,
        }
    }

    /// The node as a `format` expression, if it is one.
    #[must_use]
    pub fn as_format(&self) -> Option<&FormatExpression> {
        match &self.node {
            Node::Format(f) => Some(f),
            _ => None,
        }
    }

    /// The node as a `format-section-override`, if it is one.
    #[must_use]
    pub fn as_format_section_override(&self) -> Option<&FormatSectionOverride> {
        match &self.node {
            Node::FormatSectionOverride(o) => Some(o),
            _ => None,
        }
    }

    /// Evaluates the expression to a value of its type.
    pub fn evaluate(&self, cx: &EvaluationContext<'_>) -> EvaluationResult {
        match &self.node {
            Node::Literal(l) => Ok(l.value().clone()),
            Node::Compound(c) => c.evaluate(cx),
            Node::Assertion(a) => a.evaluate(cx),
            Node::Coercion(c) => c.evaluate(cx),
            Node::Comparison(c) => c.eval_bool(cx).map(Value::Bool),
            Node::All(_) | Node::Any(_) | Node::In(_) | Node::Within(_) => self.eval_bool(cx).map(Value::Bool),
            Node::IndexOf(_) | Node::Length(_) | Node::Distance(_) => self.eval_num(cx).map(Value::Number),
            Node::NumberFormat(_) => self.eval_str(cx).map(|s| Value::String(s.into_owned())),
            Node::FormatSectionOverride(_) => self.eval_color(cx).map(Value::Color),
            Node::At(a) => a.evaluate(cx),
            Node::Slice(s) => s.evaluate(cx),
            Node::Case(c) => c.eval::<Value>(cx),
            Node::Coalesce(c) => c.evaluate(cx),
            Node::Match(m) => m.eval::<Value>(cx),
            Node::Step(s) => s.eval::<Value>(cx),
            Node::Interpolate(i) => i.evaluate(cx),
            Node::Let(l) => l.result().evaluate(cx),
            Node::Var(v) => v.bound_expression().evaluate(cx),
            Node::Collator(c) => c.evaluate(cx),
            Node::Format(f) => f.evaluate(cx),
            Node::Image(i) => i.evaluate(cx),
            Node::Semiliteral(s) => s.evaluate(cx),
        }
    }

    /// Evaluates through the typed evaluation of the expression's type
    /// ([`eval_num`](Self::eval_num), [`eval_bool`](Self::eval_bool), ...),
    /// giving its result as a value, or through [`evaluate`](Self::evaluate)
    /// for the other types. Wherever `evaluate` gives a value of the type,
    /// this gives the same value.
    pub fn evaluate_typed(&self, cx: &EvaluationContext<'_>) -> EvaluationResult {
        match self.type_() {
            Type::Number => self.eval_num(cx).map(Value::Number),
            Type::Boolean => self.eval_bool(cx).map(Value::Bool),
            Type::String => self.eval_str(cx).map(|s| Value::String(s.into_owned())),
            Type::Color => self.eval_color(cx).map(Value::Color),
            _ => self.evaluate(cx),
        }
    }

    /// [`evaluate`](Self::evaluate), borrowing a literal's value instead of
    /// cloning it.
    pub(crate) fn evaluate_ref<'e>(&'e self, cx: &EvaluationContext<'_>) -> EvalResult<Cow<'e, Value>> {
        match &self.node {
            Node::Literal(l) => Ok(Cow::Borrowed(l.value())),
            _ => self.evaluate(cx).map(Cow::Owned),
        }
    }

    /// Evaluates a number-typed expression.
    pub fn eval_num(&self, cx: &EvaluationContext<'_>) -> EvalResult<f64> {
        match &self.node {
            Node::Literal(l) => match l.value() {
                Value::Number(n) => Ok(*n),
                other => f64::from_value(other.clone()),
            },
            Node::Compound(c) => c.eval_num(cx),
            Node::Assertion(a) => a.eval_num(cx),
            Node::Coercion(c) => c.eval_num(cx),
            Node::Case(c) => c.eval(cx),
            Node::Match(m) => m.eval(cx),
            Node::Step(s) => s.eval(cx),
            Node::Coalesce(c) => c.eval_typed(cx, &Type::Number),
            Node::Interpolate(i) => i.eval_num(cx),
            Node::Let(l) => l.result().eval_num(cx),
            Node::Var(v) => v.bound_expression().eval_num(cx),
            Node::Length(input) => crate::expression::forms::length::evaluate(input, cx),
            Node::IndexOf(i) => i.eval_num(cx),
            Node::Distance(d) => d.eval_num(cx),
            _ => via_value(self, cx),
        }
    }

    /// Evaluates a boolean-typed expression, such as a filter.
    pub fn eval_bool(&self, cx: &EvaluationContext<'_>) -> EvalResult<bool> {
        match &self.node {
            Node::Literal(l) => match l.value() {
                Value::Bool(b) => Ok(*b),
                other => bool::from_value(other.clone()),
            },
            Node::Compound(c) => c.eval_bool(cx),
            Node::Comparison(c) => c.eval_bool(cx),
            Node::All(inputs) => {
                for input in inputs {
                    if !input.eval_bool(cx)? {
                        return Ok(false);
                    }
                }
                Ok(true)
            }
            Node::Any(inputs) => {
                for input in inputs {
                    if input.eval_bool(cx)? {
                        return Ok(true);
                    }
                }
                Ok(false)
            }
            Node::Assertion(a) => a.eval_bool(cx),
            Node::Coercion(c) => c.eval_bool(cx),
            Node::Case(c) => c.eval(cx),
            Node::Match(m) => m.eval(cx),
            Node::Step(s) => s.eval(cx),
            Node::Coalesce(c) => c.eval_typed(cx, &Type::Boolean),
            Node::Let(l) => l.result().eval_bool(cx),
            Node::Var(v) => v.bound_expression().eval_bool(cx),
            Node::In(i) => i.eval_bool(cx),
            Node::Within(w) => Ok(w.eval_bool(cx)),
            _ => via_value(self, cx),
        }
    }

    /// Evaluates a string-typed expression, borrowing a literal's string.
    pub fn eval_str<'e>(&'e self, cx: &EvaluationContext<'_>) -> EvalResult<Cow<'e, str>> {
        match &self.node {
            Node::Literal(l) => match l.value() {
                Value::String(s) => Ok(Cow::Borrowed(s)),
                other => Cow::from_value(other.clone()),
            },
            Node::Compound(c) => c.eval_str(cx),
            Node::Assertion(a) => a.eval_str(cx),
            Node::Coercion(c) => c.eval_str(cx),
            Node::Case(c) => c.eval(cx),
            Node::Match(m) => m.eval(cx),
            Node::Step(s) => s.eval(cx),
            Node::Coalesce(c) => c.eval_typed(cx, &Type::String),
            Node::Let(l) => l.result().eval_str(cx),
            Node::Var(v) => v.bound_expression().eval_str(cx),
            Node::NumberFormat(n) => n.eval_str(cx).map(Cow::Owned),
            _ => via_value(self, cx),
        }
    }

    /// Evaluates a color-typed expression.
    pub fn eval_color(&self, cx: &EvaluationContext<'_>) -> EvalResult<Color> {
        match &self.node {
            Node::Literal(l) => match l.value() {
                Value::Color(c) => Ok(*c),
                other => Color::from_value(other.clone()),
            },
            Node::Compound(c) => c.eval_color(cx),
            Node::Coercion(c) => c.eval_color(cx),
            Node::Case(c) => c.eval(cx),
            Node::Match(m) => m.eval(cx),
            Node::Step(s) => s.eval(cx),
            Node::Coalesce(c) => c.eval_typed(cx, &Type::Color),
            Node::Interpolate(i) => i.eval_color(cx),
            Node::Let(l) => l.result().eval_color(cx),
            Node::Var(v) => v.bound_expression().eval_color(cx),
            Node::FormatSectionOverride(o) => o.eval_color(cx),
            _ => via_value(self, cx),
        }
    }
}

impl Node {
    /// The inputs the node itself reads, apart from its operands'.
    fn own_dependencies(&self) -> Dependency {
        match self {
            Node::Compound(c) => c.overload().dependencies,
            Node::Let(_) => Dependency::BIND,
            Node::Var(v) => Dependency::VAR | v.bound_expression().deps,
            Node::Collator(_) | Node::Within(_) | Node::Distance(_) => Dependency::FEATURE,
            Node::Image(_) => Dependency::IMAGE,
            Node::FormatSectionOverride(_) => Dependency::OVERRIDE | Dependency::FEATURE,
            _ => Dependency::NONE,
        }
    }

    fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
        match self {
            Node::Literal(_) | Node::Var(_) | Node::Within(_) | Node::Distance(_) => {}
            Node::FormatSectionOverride(o) => o.each_child(visit),
            Node::Compound(c) => c.args().iter().for_each(visit),
            Node::Assertion(a) => a.inputs().iter().for_each(visit),
            Node::Coercion(c) => c.inputs().iter().for_each(visit),
            Node::Comparison(c) => c.each_child(visit),
            Node::All(inputs) | Node::Any(inputs) => inputs.iter().for_each(visit),
            Node::At(a) => a.each_child(visit),
            Node::In(i) => i.each_child(visit),
            Node::IndexOf(i) => i.each_child(visit),
            Node::Slice(s) => s.each_child(visit),
            Node::Length(input) => visit(input),
            Node::Case(c) => c.each_child(visit),
            Node::Coalesce(c) => c.args().iter().for_each(visit),
            Node::Match(m) => m.each_child(visit),
            Node::Step(s) => s.each_child(visit),
            Node::Interpolate(i) => i.each_child(visit),
            Node::Let(l) => l.each_child(visit),
            Node::Collator(c) => c.each_child(visit),
            Node::Format(f) => f.each_child(visit),
            Node::Image(i) => visit(i.image_id()),
            Node::NumberFormat(n) => n.each_child(visit),
            Node::Semiliteral(s) => s.elements().iter().for_each(visit),
        }
    }
}

/// A bound expression shared by a `let`'s scope and its `var`s.
pub(crate) type SharedExpr = Arc<Expr>;