1
//! CSS `calc()` expression evaluator.
2
//!
3
//! This module implements a two-pass stack-machine evaluator for `calc()` expressions.
4
//! It resolves `CalcAstItem` slices (flat, parenthesised AST) into a single `f32` pixel value.
5
//!
6
//! **Resolution context**: Em/rem units are resolved using per-node font sizes that are
7
//! captured lazily during style translation and stored alongside the AST pointer passed
8
//! to taffy. Percentages use the `basis` value provided by taffy (container width/height).
9

            
10
use azul_css::props::{
11
    basic::{pixel::PT_TO_PX, PixelValue, SizeMetric},
12
    layout::dimensions::{CalcAstItem, CalcAstItemVec},
13
};
14

            
15
/// CSS reference pixels per inch (96 px/in per CSS spec).
16
pub(super) const PX_PER_INCH: f32 = 96.0;
17
/// Centimetres per inch.
18
pub(super) const CM_PER_INCH: f32 = 2.54;
19
/// Millimetres per inch.
20
pub(super) const MM_PER_INCH: f32 = 25.4;
21

            
22
/// Font-size context captured at style-translation time and stored alongside the calc AST.
23
///
24
/// Taffy's `resolve_calc_value` callback only receives `(*const (), f32)` — no node id.
25
/// We therefore bundle the per-node font sizes into the heap-pinned data that the opaque
26
/// pointer references, so the evaluator can resolve `em` / `rem` correctly.
27
#[derive(Debug, Clone)]
28
#[repr(C)]
29
pub struct CalcResolveContext {
30
    /// The calc AST items (flat stack-machine representation).
31
    pub items: CalcAstItemVec,
32
    /// Element's computed `font-size` in px — used for `em` resolution.
33
    pub em_size: f32,
34
    /// Root element's computed `font-size` in px — used for `rem` resolution.
35
    pub rem_size: f32,
36
}
37
// Tiny enum (Num(f32) = 4B vs Op(CalcOp) = 1B); the "large" variant is a bare
38
// f32, so boxing it would add a pointer + heap allocation — strictly worse than
39
// the few bytes of size disparity. Accepted.
40
#[allow(variant_size_differences)]
41
/// Internal intermediate representation: a number or an operator (after value resolution).
42
#[derive(Clone, Debug)]
43
enum CalcFlatItem {
44
    Num(f32),
45
    Op(CalcOp),
46
}
47

            
48
/// Arithmetic operators.
49
#[derive(Clone, Copy, Debug, PartialEq)]
50
enum CalcOp {
51
    Add,
52
    Sub,
53
    Mul,
54
    Div,
55
}
56

            
57
/// Evaluate a `CalcResolveContext` using the given `basis` (the "100 %" reference value,
58
/// e.g. containing-block width for `width: calc(…)`).
59
#[inline(never)]
60
// M12.7: keep out of calc_used_size — its loop/jump-table inlined into the huge fn forces a remill
61
// PC-dispatch loop that mis-delivers auto_w
62
#[must_use]
63
322
pub fn evaluate_calc(ctx: &CalcResolveContext, basis: f32) -> f32 {
64
322
    evaluate_calc_ast(ctx.items.as_slice(), basis, ctx.em_size, ctx.rem_size)
65
322
}
66

            
67
/// Stack-machine evaluator for a flat `CalcAstItem` slice.
68
///
69
/// `basis`    — the "100 %" reference value (e.g. containing-block width).
70
/// `em_size`  — element's computed font-size (for `em`).
71
/// `rem_size` — root element's computed font-size (for `rem`).
72
///
73
/// Two-pass approach with correct operator precedence:
74
///   Pass 1: evaluate `*` and `/`
75
///   Pass 2: evaluate `+` and `-`
76
/// Parenthesised sub-expressions are resolved recursively.
77
#[inline(never)] // M12.7: keep out of calc_used_size — its loop/jump-table inlined into the huge fn
78
                 // forces a remill PC-dispatch loop that mis-delivers auto_w
79
933
fn evaluate_calc_ast(items: &[CalcAstItem], basis: f32, em_size: f32, rem_size: f32) -> f32 {
80
    // Convert into a working vec of resolved numbers and operators.
81
933
    let mut flat: Vec<CalcFlatItem> = Vec::with_capacity(items.len());
82
933
    let mut i = 0;
83
4551
    while i < items.len() {
84
3618
        match &items[i] {
85
1685
            CalcAstItem::Value(pv) => {
86
1685
                flat.push(CalcFlatItem::Num(resolve_pixel_value(
87
1685
                    pv, basis, em_size, rem_size,
88
1685
                )));
89
1685
            }
90
1145
            CalcAstItem::Add => flat.push(CalcFlatItem::Op(CalcOp::Add)),
91
83
            CalcAstItem::Sub => flat.push(CalcFlatItem::Op(CalcOp::Sub)),
92
85
            CalcAstItem::Mul => flat.push(CalcFlatItem::Op(CalcOp::Mul)),
93
53
            CalcAstItem::Div => flat.push(CalcFlatItem::Op(CalcOp::Div)),
94
            CalcAstItem::BraceOpen => {
95
                // Find matching BraceClose and recurse
96
565
                let start = i + 1;
97
565
                let mut depth = 1u32;
98
565
                let mut j = start;
99
99241
                while j < items.len() && depth > 0 {
100
98676
                    match &items[j] {
101
65292
                        CalcAstItem::BraceOpen => depth += 1,
102
32958
                        CalcAstItem::BraceClose => depth -= 1,
103
426
                        _ => {}
104
                    }
105
98676
                    if depth > 0 {
106
98370
                        j += 1;
107
98370
                    }
108
                }
109
                // items[start..j] is the inner sub-expression (excl. braces)
110
565
                let sub_val = evaluate_calc_ast(&items[start..j], basis, em_size, rem_size);
111
565
                flat.push(CalcFlatItem::Num(sub_val));
112
565
                i = j; // skip past the closing brace
113
            }
114
2
            CalcAstItem::BraceClose => { /* shouldn't happen at top level */ }
115
        }
116
3618
        i += 1;
117
    }
118

            
119
    // Pass 1: resolve * and /
120
933
    let mut pass2: Vec<CalcFlatItem> = Vec::with_capacity(flat.len());
121
933
    let mut k = 0;
122
4418
    while k < flat.len() {
123
3485
        if let CalcFlatItem::Op(op @ (CalcOp::Mul | CalcOp::Div)) = &flat[k] {
124
            // Apply to previous Num in pass2 and next Num in flat
125
131
            if let (Some(CalcFlatItem::Num(lhs)), Some(CalcFlatItem::Num(rhs))) =
126
138
                (pass2.last(), flat.get(k + 1))
127
            {
128
131
                let result = match op {
129
81
                    CalcOp::Mul => lhs * rhs,
130
                    CalcOp::Div => {
131
50
                        if *rhs == 0.0 {
132
14
                            0.0
133
                        } else {
134
36
                            lhs / rhs
135
                        }
136
                    }
137
                    _ => unreachable!(),
138
                };
139
131
                *pass2.last_mut().unwrap() = CalcFlatItem::Num(result);
140
131
                k += 2; // skip operator + rhs
141
131
                continue;
142
7
            }
143
3347
        }
144
3354
        pass2.push(flat[k].clone());
145
3354
        k += 1;
146
    }
147

            
148
    // Pass 2: resolve + and -
149
933
    let mut result = match pass2.first() {
150
902
        Some(CalcFlatItem::Num(v)) => *v,
151
31
        _ => return 0.0,
152
    };
153
902
    let mut m = 1;
154
2121
    while m < pass2.len() {
155
1219
        if let (CalcFlatItem::Op(op), Some(CalcFlatItem::Num(rhs))) = (&pass2[m], pass2.get(m + 1))
156
        {
157
1213
            match op {
158
1131
                CalcOp::Add => result += rhs,
159
81
                CalcOp::Sub => result -= rhs,
160
1
                _ => {} // already handled in pass 1
161
            }
162
1213
            m += 2;
163
6
        } else {
164
6
            m += 1;
165
6
        }
166
    }
167

            
168
902
    result
169
933
}
170

            
171
/// Resolve a single `PixelValue` to `f32` pixels inside a `calc()` expression.
172
///
173
/// - `basis`    — the "100 %" reference (containing-block width or height)
174
/// - `em_size`  — element's computed font-size (for `em` units)
175
/// - `rem_size` — root element's computed font-size (for `rem` units)
176
///
177
/// NOTE: this variant has no viewport context, so viewport units (`vw`/`vh`/
178
/// `vmin`/`vmax`) fall back to their raw number (i.e. `50vw` → `50px`). Callers
179
/// that may see viewport units must use [`resolve_pixel_value_with_viewport`]
180
/// (or [`resolve_pixel_value_no_percent_with_viewport`]) instead.
181
#[must_use]
182
327971
pub fn resolve_pixel_value(pv: &PixelValue, basis: f32, em_size: f32, rem_size: f32) -> f32 {
183
327971
    match pv.metric {
184
327282
        SizeMetric::Px => pv.number.get(),
185
54
        SizeMetric::Pt => pv.number.get() * PT_TO_PX,
186
54
        SizeMetric::In => pv.number.get() * PX_PER_INCH,
187
54
        SizeMetric::Cm => pv.number.get() * PX_PER_INCH / CM_PER_INCH,
188
54
        SizeMetric::Mm => pv.number.get() * PX_PER_INCH / MM_PER_INCH,
189
107
        SizeMetric::Em => pv.number.get() * em_size,
190
90
        SizeMetric::Rem => pv.number.get() * rem_size,
191
139
        SizeMetric::Percent => basis * (pv.number.get() / 100.0),
192
        SizeMetric::Vw | SizeMetric::Vh | SizeMetric::Vmin | SizeMetric::Vmax => {
193
            // Viewport units: fallback — proper resolution requires viewport context
194
137
            pv.number.get()
195
        }
196
    }
197
327971
}
198

            
199
/// Like `resolve_pixel_value`, but with proper viewport unit resolution.
200
#[inline(never)]
201
// M12.7: keep out of calc_used_size — its loop/jump-table inlined into the huge fn forces a remill
202
// PC-dispatch loop that mis-delivers auto_w
203
#[must_use]
204
325788
pub fn resolve_pixel_value_with_viewport(
205
325788
    pv: &PixelValue,
206
325788
    basis: f32,
207
325788
    em_size: f32,
208
325788
    rem_size: f32,
209
325788
    viewport_width: f32,
210
325788
    viewport_height: f32,
211
325788
) -> f32 {
212
325788
    match pv.metric {
213
7
        SizeMetric::Vw => pv.number.get() / 100.0 * viewport_width,
214
3
        SizeMetric::Vh => pv.number.get() / 100.0 * viewport_height,
215
6
        SizeMetric::Vmin => pv.number.get() / 100.0 * viewport_width.min(viewport_height),
216
5
        SizeMetric::Vmax => pv.number.get() / 100.0 * viewport_width.max(viewport_height),
217
325767
        _ => resolve_pixel_value(pv, basis, em_size, rem_size),
218
    }
219
325788
}
220

            
221
/// Resolve a `PixelValue` to pixels, returning `None` for percentage and viewport units.
222
#[must_use]
223
93049
pub fn resolve_pixel_value_no_percent(pv: &PixelValue, em_size: f32, rem_size: f32) -> Option<f32> {
224
93049
    match pv.metric {
225
87564
        SizeMetric::Px => Some(pv.number.get()),
226
9
        SizeMetric::Pt => Some(pv.number.get() * PT_TO_PX),
227
9
        SizeMetric::In => Some(pv.number.get() * PX_PER_INCH),
228
9
        SizeMetric::Cm => Some(pv.number.get() * PX_PER_INCH / CM_PER_INCH),
229
9
        SizeMetric::Mm => Some(pv.number.get() * PX_PER_INCH / MM_PER_INCH),
230
13
        SizeMetric::Em => Some(pv.number.get() * em_size),
231
10
        SizeMetric::Rem => Some(pv.number.get() * rem_size),
232
        SizeMetric::Percent
233
        | SizeMetric::Vw
234
        | SizeMetric::Vh
235
        | SizeMetric::Vmin
236
5426
        | SizeMetric::Vmax => None,
237
    }
238
93049
}
239

            
240
/// Like `resolve_pixel_value_no_percent`, but resolves viewport units using
241
/// the provided viewport dimensions. Returns `None` only for percentages.
242
#[must_use]
243
25717
pub fn resolve_pixel_value_no_percent_with_viewport(
244
25717
    pv: &PixelValue,
245
25717
    em_size: f32,
246
25717
    rem_size: f32,
247
25717
    viewport_width: f32,
248
25717
    viewport_height: f32,
249
25717
) -> Option<f32> {
250
25717
    match pv.metric {
251
3
        SizeMetric::Vw => Some(pv.number.get() / 100.0 * viewport_width),
252
3
        SizeMetric::Vh => Some(pv.number.get() / 100.0 * viewport_height),
253
3
        SizeMetric::Vmin => Some(pv.number.get() / 100.0 * viewport_width.min(viewport_height)),
254
3
        SizeMetric::Vmax => Some(pv.number.get() / 100.0 * viewport_width.max(viewport_height)),
255
25705
        _ => resolve_pixel_value_no_percent(pv, em_size, rem_size),
256
    }
257
25717
}
258

            
259
#[cfg(test)]
260
#[allow(
261
    clippy::float_cmp,
262
    clippy::cast_precision_loss,
263
    clippy::unreadable_literal
264
)]
265
mod autotest_generated {
266
    use azul_css::props::basic::FP_PRECISION_MULTIPLIER;
267

            
268
    use super::*;
269

            
270
    // ------------------------------------------------------------------
271
    // Fixtures
272
    // ------------------------------------------------------------------
273

            
274
    /// Every `SizeMetric` variant, so "for all metrics" invariants stay honest
275
    /// if a new unit is added to the enum (the array length breaks the build).
276
    const ALL_METRICS: [SizeMetric; 12] = [
277
        SizeMetric::Px,
278
        SizeMetric::Pt,
279
        SizeMetric::Em,
280
        SizeMetric::Rem,
281
        SizeMetric::In,
282
        SizeMetric::Cm,
283
        SizeMetric::Mm,
284
        SizeMetric::Percent,
285
        SizeMetric::Vw,
286
        SizeMetric::Vh,
287
        SizeMetric::Vmin,
288
        SizeMetric::Vmax,
289
    ];
290

            
291
    /// Metrics that resolve to an absolute length without any layout context.
292
    const ABSOLUTE_METRICS: [SizeMetric; 7] = [
293
        SizeMetric::Px,
294
        SizeMetric::Pt,
295
        SizeMetric::Em,
296
        SizeMetric::Rem,
297
        SizeMetric::In,
298
        SizeMetric::Cm,
299
        SizeMetric::Mm,
300
    ];
301

            
302
    const VIEWPORT_METRICS: [SizeMetric; 4] = [
303
        SizeMetric::Vw,
304
        SizeMetric::Vh,
305
        SizeMetric::Vmin,
306
        SizeMetric::Vmax,
307
    ];
308

            
309
    /// `FloatValue` is fixed-point (`isize` scaled by `FP_PRECISION_MULTIPLIER`),
310
    /// so any `f32` too large to fit saturates to this magnitude on `get()`.
311
    fn saturated_magnitude() -> f32 {
312
        (isize::MAX as f32) / FP_PRECISION_MULTIPLIER
313
    }
314

            
315
    fn assert_close(actual: f32, expected: f32) {
316
        let tolerance = 1e-3 * expected.abs().max(1.0);
317
        assert!(
318
            (actual - expected).abs() <= tolerance,
319
            "expected ~{expected}, got {actual}",
320
        );
321
    }
322

            
323
    fn val(metric: SizeMetric, n: f32) -> CalcAstItem {
324
        CalcAstItem::Value(PixelValue::from_metric(metric, n))
325
    }
326

            
327
    fn px(n: f32) -> CalcAstItem {
328
        val(SizeMetric::Px, n)
329
    }
330

            
331
    const EM: f32 = 16.0;
332
    const REM: f32 = 10.0;
333

            
334
    fn eval(items: &[CalcAstItem], basis: f32) -> f32 {
335
        evaluate_calc_ast(items, basis, EM, REM)
336
    }
337

            
338
    fn ctx(items: Vec<CalcAstItem>, em_size: f32, rem_size: f32) -> CalcResolveContext {
339
        CalcResolveContext {
340
            items: CalcAstItemVec::from(items),
341
            em_size,
342
            rem_size,
343
        }
344
    }
345

            
346
    // ==================================================================
347
    // PixelValue encoding invariants
348
    //
349
    // These underpin every resolver below: because `FloatValue` stores an
350
    // `isize` and `f32 as isize` saturates (NaN -> 0, +/-inf -> MIN/MAX),
351
    // a `PixelValue` can never *carry* a NaN or an infinity. Any non-finite
352
    // result therefore has to come from `basis` / `em_size` / `viewport_*`.
353
    // ==================================================================
354

            
355
    #[test]
356
    fn pixel_value_number_is_always_finite_even_for_nan_and_inf() {
357
        for metric in ALL_METRICS {
358
            for hostile in [
359
                f32::NAN,
360
                f32::INFINITY,
361
                f32::NEG_INFINITY,
362
                f32::MAX,
363
                f32::MIN,
364
                f32::MIN_POSITIVE,
365
                -0.0,
366
            ] {
367
                let n = PixelValue::from_metric(metric, hostile).number.get();
368
                assert!(
369
                    n.is_finite(),
370
                    "PixelValue::from_metric({metric:?}, {hostile}) produced non-finite {n}",
371
                );
372
            }
373
        }
374
    }
375

            
376
    #[test]
377
    fn pixel_value_nan_encodes_as_zero() {
378
        assert_eq!(PixelValue::px(f32::NAN).number.get(), 0.0);
379
    }
380

            
381
    #[test]
382
    fn pixel_value_infinities_saturate_to_fixed_point_bounds() {
383
        let sat = saturated_magnitude();
384
        assert_close(PixelValue::px(f32::INFINITY).number.get(), sat);
385
        assert_close(PixelValue::px(f32::NEG_INFINITY).number.get(), -sat);
386
        // f32::MAX * 1000.0 already overflows to inf before the cast, so it
387
        // lands on the same saturation point rather than on f32::MAX.
388
        assert_close(PixelValue::px(f32::MAX).number.get(), sat);
389
        assert_close(PixelValue::px(f32::MIN).number.get(), -sat);
390
    }
391

            
392
    // ==================================================================
393
    // resolve_pixel_value
394
    // ==================================================================
395

            
396
    #[test]
397
    fn resolve_pixel_value_zero_is_zero_for_every_metric() {
398
        for metric in ALL_METRICS {
399
            let pv = PixelValue::from_metric(metric, 0.0);
400
            let got = resolve_pixel_value(&pv, 500.0, EM, REM);
401
            assert_eq!(got, 0.0, "0 {metric:?} should resolve to 0px, got {got}");
402
        }
403
    }
404

            
405
    #[test]
406
    fn resolve_pixel_value_absolute_unit_conversions() {
407
        assert_eq!(
408
            resolve_pixel_value(&PixelValue::px(10.0), 0.0, EM, REM),
409
            10.0
410
        );
411
        assert_close(
412
            resolve_pixel_value(&PixelValue::pt(12.0), 0.0, EM, REM),
413
            12.0 * PT_TO_PX,
414
        );
415
        // 1in == 96px, 2.54cm == 1in, 25.4mm == 1in.
416
        assert_close(
417
            resolve_pixel_value(&PixelValue::inch(1.0), 0.0, EM, REM),
418
            96.0,
419
        );
420
        assert_close(
421
            resolve_pixel_value(&PixelValue::cm(2.54), 0.0, EM, REM),
422
            96.0,
423
        );
424
        assert_close(
425
            resolve_pixel_value(&PixelValue::mm(25.4), 0.0, EM, REM),
426
            96.0,
427
        );
428
    }
429

            
430
    #[test]
431
    fn resolve_pixel_value_em_and_rem_use_their_own_font_size() {
432
        assert_eq!(
433
            resolve_pixel_value(&PixelValue::em(2.0), 0.0, 16.0, 10.0),
434
            32.0
435
        );
436
        assert_eq!(
437
            resolve_pixel_value(&PixelValue::rem(2.0), 0.0, 16.0, 10.0),
438
            20.0
439
        );
440
    }
441

            
442
    #[test]
443
    fn resolve_pixel_value_percent_uses_basis() {
444
        assert_eq!(
445
            resolve_pixel_value(&PixelValue::percent(50.0), 200.0, EM, REM),
446
            100.0
447
        );
448
        assert_eq!(
449
            resolve_pixel_value(&PixelValue::percent(0.0), 200.0, EM, REM),
450
            0.0
451
        );
452
        assert_eq!(
453
            resolve_pixel_value(&PixelValue::percent(100.0), 0.0, EM, REM),
454
            0.0
455
        );
456
    }
457

            
458
    #[test]
459
    fn resolve_pixel_value_handles_negative_inputs_deterministically() {
460
        assert_eq!(
461
            resolve_pixel_value(&PixelValue::px(-10.0), 0.0, EM, REM),
462
            -10.0
463
        );
464
        assert_eq!(
465
            resolve_pixel_value(&PixelValue::em(-2.0), 0.0, 16.0, REM),
466
            -32.0
467
        );
468
        // Negative percentage of a positive basis, and positive percentage of a
469
        // negative basis, both yield a negative length (no clamping here).
470
        assert_eq!(
471
            resolve_pixel_value(&PixelValue::percent(-50.0), 200.0, EM, REM),
472
            -100.0
473
        );
474
        assert_eq!(
475
            resolve_pixel_value(&PixelValue::percent(50.0), -200.0, EM, REM),
476
            -100.0
477
        );
478
    }
479

            
480
    #[test]
481
    fn resolve_pixel_value_viewport_units_fall_back_to_raw_number() {
482
        // Documented fallback: with no viewport context, `50vw` degrades to `50px`.
483
        for metric in VIEWPORT_METRICS {
484
            let pv = PixelValue::from_metric(metric, 50.0);
485
            assert_eq!(
486
                resolve_pixel_value(&pv, 1000.0, EM, REM),
487
                50.0,
488
                "{metric:?} should fall back to its raw number",
489
            );
490
        }
491
    }
492

            
493
    #[test]
494
    fn resolve_pixel_value_is_finite_for_any_pixel_value_in_a_sane_context() {
495
        // The core safety property: because a PixelValue can never *carry* a NaN
496
        // or an infinity, no value — not even one built from f32::MAX — can turn
497
        // a realistic basis/em/rem into a non-finite length. (An absurd basis
498
        // *can* still overflow; that is pinned separately below.)
499
        for metric in ALL_METRICS {
500
            for n in [
501
                0.0,
502
                -0.0,
503
                1.0,
504
                -1.0,
505
                f32::MAX,
506
                f32::MIN,
507
                f32::NAN,
508
                f32::INFINITY,
509
            ] {
510
                let pv = PixelValue::from_metric(metric, n);
511
                for basis in [0.0_f32, -1000.0, 1920.0, 1_000_000.0] {
512
                    let got = resolve_pixel_value(&pv, basis, EM, REM);
513
                    assert!(
514
                        got.is_finite(),
515
                        "{metric:?} {n} @ basis {basis} produced non-finite {got}",
516
                    );
517
                }
518
            }
519
        }
520
    }
521

            
522
    #[test]
523
    fn resolve_pixel_value_saturated_percent_of_huge_basis_overflows_to_inf_not_panic() {
524
        // 100% of f32::MAX stays finite; 200% of it overflows.
525
        let hundred = resolve_pixel_value(&PixelValue::percent(100.0), f32::MAX, EM, REM);
526
        assert_eq!(hundred, f32::MAX);
527

            
528
        let two_hundred = resolve_pixel_value(&PixelValue::percent(200.0), f32::MAX, EM, REM);
529
        assert!(
530
            two_hundred.is_infinite() && two_hundred.is_sign_positive(),
531
            "expected +inf on overflow, got {two_hundred}",
532
        );
533
    }
534

            
535
    #[test]
536
    fn resolve_pixel_value_nan_basis_only_pollutes_percentages() {
537
        // A NaN basis must not leak into units that never read it.
538
        assert_eq!(
539
            resolve_pixel_value(&PixelValue::px(10.0), f32::NAN, EM, REM),
540
            10.0
541
        );
542
        assert_eq!(
543
            resolve_pixel_value(&PixelValue::em(1.0), f32::NAN, 16.0, REM),
544
            16.0
545
        );
546
        assert!(resolve_pixel_value(&PixelValue::percent(50.0), f32::NAN, EM, REM).is_nan());
547
    }
548

            
549
    #[test]
550
    fn resolve_pixel_value_zero_times_infinite_context_is_nan_not_zero() {
551
        // IEEE-754 quirk worth pinning: `0em` against an infinite font-size (and
552
        // `0%` against an infinite basis) is 0 * inf == NaN, NOT 0. Callers that
553
        // treat "zero length" as always-safe do not get a zero here.
554
        assert!(resolve_pixel_value(&PixelValue::em(0.0), 0.0, f32::INFINITY, REM).is_nan());
555
        assert!(resolve_pixel_value(&PixelValue::percent(0.0), f32::INFINITY, EM, REM).is_nan());
556
        // ...whereas a non-zero multiplier gives a plain infinity.
557
        let inf = resolve_pixel_value(&PixelValue::em(1.0), 0.0, f32::INFINITY, REM);
558
        assert!(inf.is_infinite() && inf.is_sign_positive());
559
    }
560

            
561
    // ==================================================================
562
    // resolve_pixel_value_with_viewport
563
    // ==================================================================
564

            
565
    #[test]
566
    fn resolve_with_viewport_resolves_viewport_units() {
567
        let (vw, vh) = (1000.0_f32, 800.0_f32);
568
        let r = |m: SizeMetric, n: f32| {
569
            resolve_pixel_value_with_viewport(&PixelValue::from_metric(m, n), 0.0, EM, REM, vw, vh)
570
        };
571
        assert_eq!(r(SizeMetric::Vw, 50.0), 500.0);
572
        assert_eq!(r(SizeMetric::Vh, 50.0), 400.0);
573
        assert_eq!(r(SizeMetric::Vmin, 100.0), 800.0);
574
        assert_eq!(r(SizeMetric::Vmax, 100.0), 1000.0);
575
    }
576

            
577
    #[test]
578
    fn resolve_with_viewport_delegates_non_viewport_metrics_verbatim() {
579
        for metric in ALL_METRICS {
580
            if VIEWPORT_METRICS.contains(&metric) {
581
                continue;
582
            }
583
            let pv = PixelValue::from_metric(metric, 33.75);
584
            assert_eq!(
585
                resolve_pixel_value_with_viewport(&pv, 500.0, EM, REM, 1920.0, 1080.0),
586
                resolve_pixel_value(&pv, 500.0, EM, REM),
587
                "{metric:?} must not be affected by viewport context",
588
            );
589
        }
590
    }
591

            
592
    #[test]
593
    fn resolve_with_viewport_zero_and_negative_viewport() {
594
        for metric in VIEWPORT_METRICS {
595
            let pv = PixelValue::from_metric(metric, 50.0);
596
            assert_eq!(
597
                resolve_pixel_value_with_viewport(&pv, 0.0, EM, REM, 0.0, 0.0),
598
                0.0,
599
                "{metric:?} against a 0x0 viewport should be 0px",
600
            );
601
        }
602
        // A negative viewport is nonsense but must stay deterministic, not panic.
603
        let vw50 = PixelValue::from_metric(SizeMetric::Vw, 50.0);
604
        assert_eq!(
605
            resolve_pixel_value_with_viewport(&vw50, 0.0, EM, REM, -100.0, -100.0),
606
            -50.0,
607
        );
608
        // min/max still order correctly with negatives: min(-100, -50) == -100.
609
        let vmin100 = PixelValue::from_metric(SizeMetric::Vmin, 100.0);
610
        let vmax100 = PixelValue::from_metric(SizeMetric::Vmax, 100.0);
611
        assert_eq!(
612
            resolve_pixel_value_with_viewport(&vmin100, 0.0, EM, REM, -100.0, -50.0),
613
            -100.0,
614
        );
615
        assert_eq!(
616
            resolve_pixel_value_with_viewport(&vmax100, 0.0, EM, REM, -100.0, -50.0),
617
            -50.0,
618
        );
619
    }
620

            
621
    #[test]
622
    fn resolve_with_viewport_nan_viewport_is_swallowed_by_vmin_vmax_but_not_vw_vh() {
623
        // f32::min / f32::max return the *other* operand when one side is NaN,
624
        // so a half-NaN viewport silently produces a finite vmin/vmax...
625
        let vmin = PixelValue::from_metric(SizeMetric::Vmin, 100.0);
626
        let vmax = PixelValue::from_metric(SizeMetric::Vmax, 100.0);
627
        assert_eq!(
628
            resolve_pixel_value_with_viewport(&vmin, 0.0, EM, REM, f32::NAN, 800.0),
629
            800.0,
630
        );
631
        assert_eq!(
632
            resolve_pixel_value_with_viewport(&vmax, 0.0, EM, REM, f32::NAN, 800.0),
633
            800.0,
634
        );
635
        // ...while vw/vh propagate the NaN. Both are defined; neither panics.
636
        let vw = PixelValue::from_metric(SizeMetric::Vw, 50.0);
637
        assert!(resolve_pixel_value_with_viewport(&vw, 0.0, EM, REM, f32::NAN, 800.0).is_nan());
638

            
639
        // Fully-NaN viewport: vmin/vmax have no finite operand to fall back on.
640
        assert!(
641
            resolve_pixel_value_with_viewport(&vmin, 0.0, EM, REM, f32::NAN, f32::NAN).is_nan()
642
        );
643
    }
644

            
645
    #[test]
646
    fn resolve_with_viewport_infinite_viewport_does_not_panic() {
647
        let vw = PixelValue::from_metric(SizeMetric::Vw, 50.0);
648
        let got = resolve_pixel_value_with_viewport(&vw, 0.0, EM, REM, f32::INFINITY, 0.0);
649
        assert!(got.is_infinite() && got.is_sign_positive());
650

            
651
        // 0vw of an infinite viewport is 0 * inf == NaN, same quirk as `0em`.
652
        let vw0 = PixelValue::from_metric(SizeMetric::Vw, 0.0);
653
        assert!(resolve_pixel_value_with_viewport(&vw0, 0.0, EM, REM, f32::INFINITY, 0.0).is_nan());
654
    }
655

            
656
    // ==================================================================
657
    // resolve_pixel_value_no_percent (+ viewport variant)
658
    // ==================================================================
659

            
660
    #[test]
661
    fn no_percent_returns_none_for_percent_and_viewport_units() {
662
        for metric in [
663
            SizeMetric::Percent,
664
            SizeMetric::Vw,
665
            SizeMetric::Vh,
666
            SizeMetric::Vmin,
667
            SizeMetric::Vmax,
668
        ] {
669
            let pv = PixelValue::from_metric(metric, 50.0);
670
            assert_eq!(
671
                resolve_pixel_value_no_percent(&pv, EM, REM),
672
                None,
673
                "{metric:?} needs layout context, so it must be None",
674
            );
675
        }
676
    }
677

            
678
    #[test]
679
    fn no_percent_agrees_with_resolve_pixel_value_on_absolute_metrics() {
680
        // Invariant: where `no_percent` returns Some, the value must be exactly
681
        // what `resolve_pixel_value` computes — for *any* basis, since none of
682
        // these units read it.
683
        for metric in ABSOLUTE_METRICS {
684
            for n in [0.0, 1.0, -7.5, 1234.5, f32::MAX, f32::MIN, f32::NAN] {
685
                let pv = PixelValue::from_metric(metric, n);
686
                let some = resolve_pixel_value_no_percent(&pv, EM, REM);
687
                assert_eq!(
688
                    some,
689
                    Some(resolve_pixel_value(&pv, 999.0, EM, REM)),
690
                    "{metric:?} {n} disagrees between the two resolvers",
691
                );
692
                assert!(some.unwrap().is_finite());
693
            }
694
        }
695
    }
696

            
697
    #[test]
698
    fn no_percent_with_viewport_returns_none_only_for_percent() {
699
        for metric in ALL_METRICS {
700
            let pv = PixelValue::from_metric(metric, 50.0);
701
            let got = resolve_pixel_value_no_percent_with_viewport(&pv, EM, REM, 1000.0, 800.0);
702
            if metric == SizeMetric::Percent {
703
                assert_eq!(got, None, "% must stay None without a basis");
704
            } else {
705
                assert!(got.is_some(), "{metric:?} should resolve with a viewport");
706
                assert!(got.unwrap().is_finite());
707
            }
708
        }
709
    }
710

            
711
    #[test]
712
    fn no_percent_with_viewport_agrees_with_resolve_with_viewport() {
713
        for metric in ALL_METRICS {
714
            if metric == SizeMetric::Percent {
715
                continue;
716
            }
717
            let pv = PixelValue::from_metric(metric, 25.0);
718
            assert_eq!(
719
                resolve_pixel_value_no_percent_with_viewport(&pv, EM, REM, 1920.0, 1080.0),
720
                Some(resolve_pixel_value_with_viewport(
721
                    &pv, 0.0, EM, REM, 1920.0, 1080.0
722
                )),
723
                "{metric:?} disagrees between the viewport resolvers",
724
            );
725
        }
726
    }
727

            
728
    #[test]
729
    fn no_percent_with_viewport_zero_viewport_yields_some_zero_not_none() {
730
        for metric in VIEWPORT_METRICS {
731
            let pv = PixelValue::from_metric(metric, 100.0);
732
            assert_eq!(
733
                resolve_pixel_value_no_percent_with_viewport(&pv, EM, REM, 0.0, 0.0),
734
                Some(0.0),
735
                "{metric:?} against a 0x0 viewport is a defined 0px, not None",
736
            );
737
        }
738
    }
739

            
740
    // ==================================================================
741
    // evaluate_calc_ast — structure & precedence
742
    // ==================================================================
743

            
744
    #[test]
745
    fn eval_empty_ast_is_zero() {
746
        assert_eq!(eval(&[], 500.0), 0.0);
747
    }
748

            
749
    #[test]
750
    fn eval_single_value() {
751
        assert_eq!(eval(&[px(42.0)], 500.0), 42.0);
752
        assert_eq!(eval(&[val(SizeMetric::Percent, 10.0)], 500.0), 50.0);
753
    }
754

            
755
    #[test]
756
    fn eval_basic_addition_and_subtraction() {
757
        // calc(100% - 20px) with a 500px containing block
758
        let items = [val(SizeMetric::Percent, 100.0), CalcAstItem::Sub, px(20.0)];
759
        assert_eq!(eval(&items, 500.0), 480.0);
760
    }
761

            
762
    #[test]
763
    fn eval_add_and_sub_are_left_associative() {
764
        let items = [
765
            px(10.0),
766
            CalcAstItem::Sub,
767
            px(3.0),
768
            CalcAstItem::Sub,
769
            px(2.0),
770
        ];
771
        assert_eq!(eval(&items, 0.0), 5.0, "must be (10-3)-2, not 10-(3-2)");
772
    }
773

            
774
    #[test]
775
    fn eval_div_is_left_associative() {
776
        let items = [
777
            px(10.0),
778
            CalcAstItem::Div,
779
            px(4.0),
780
            CalcAstItem::Div,
781
            px(2.0),
782
        ];
783
        assert_eq!(eval(&items, 0.0), 1.25, "must be (10/4)/2, not 10/(4/2)");
784
    }
785

            
786
    #[test]
787
    fn eval_mul_binds_tighter_than_add() {
788
        // 1 + 2 * 3 == 7, not 9
789
        let items = [
790
            px(1.0),
791
            CalcAstItem::Add,
792
            px(2.0),
793
            CalcAstItem::Mul,
794
            px(3.0),
795
        ];
796
        assert_eq!(eval(&items, 0.0), 7.0);
797

            
798
        // 2 * 3 + 4 == 10 (operator on the left of the sum)
799
        let items = [
800
            px(2.0),
801
            CalcAstItem::Mul,
802
            px(3.0),
803
            CalcAstItem::Add,
804
            px(4.0),
805
        ];
806
        assert_eq!(eval(&items, 0.0), 10.0);
807
    }
808

            
809
    #[test]
810
    fn eval_div_binds_tighter_than_sub() {
811
        // 10 - 6 / 2 == 7, not 2
812
        let items = [
813
            px(10.0),
814
            CalcAstItem::Sub,
815
            px(6.0),
816
            CalcAstItem::Div,
817
            px(2.0),
818
        ];
819
        assert_eq!(eval(&items, 0.0), 7.0);
820
    }
821

            
822
    #[test]
823
    fn eval_braces_override_precedence() {
824
        // (1 + 2) * 3 == 9
825
        let items = [
826
            CalcAstItem::BraceOpen,
827
            px(1.0),
828
            CalcAstItem::Add,
829
            px(2.0),
830
            CalcAstItem::BraceClose,
831
            CalcAstItem::Mul,
832
            px(3.0),
833
        ];
834
        assert_eq!(eval(&items, 0.0), 9.0);
835
    }
836

            
837
    #[test]
838
    fn eval_nested_braces() {
839
        // ((2 + 3) * (4 - 2)) == 10
840
        let items = [
841
            CalcAstItem::BraceOpen,
842
            CalcAstItem::BraceOpen,
843
            px(2.0),
844
            CalcAstItem::Add,
845
            px(3.0),
846
            CalcAstItem::BraceClose,
847
            CalcAstItem::Mul,
848
            CalcAstItem::BraceOpen,
849
            px(4.0),
850
            CalcAstItem::Sub,
851
            px(2.0),
852
            CalcAstItem::BraceClose,
853
            CalcAstItem::BraceClose,
854
        ];
855
        assert_eq!(eval(&items, 0.0), 10.0);
856
    }
857

            
858
    #[test]
859
    fn eval_empty_braces_are_zero() {
860
        let items = [CalcAstItem::BraceOpen, CalcAstItem::BraceClose];
861
        assert_eq!(eval(&items, 500.0), 0.0);
862

            
863
        // ...and an empty brace still participates as a term: 10 + () == 10
864
        let items = [
865
            px(10.0),
866
            CalcAstItem::Add,
867
            CalcAstItem::BraceOpen,
868
            CalcAstItem::BraceClose,
869
        ];
870
        assert_eq!(eval(&items, 500.0), 10.0);
871
    }
872

            
873
    #[test]
874
    fn eval_percent_inside_braces_still_sees_the_basis() {
875
        // (100% - 20px) / 4  with basis 500 -> 120
876
        let items = [
877
            CalcAstItem::BraceOpen,
878
            val(SizeMetric::Percent, 100.0),
879
            CalcAstItem::Sub,
880
            px(20.0),
881
            CalcAstItem::BraceClose,
882
            CalcAstItem::Div,
883
            px(4.0),
884
        ];
885
        assert_eq!(eval(&items, 500.0), 120.0);
886
    }
887

            
888
    #[test]
889
    fn eval_em_and_rem_come_from_the_evaluator_args_not_the_basis() {
890
        // 2em + 1rem with em=10, rem=20 -> 40
891
        let items = [
892
            val(SizeMetric::Em, 2.0),
893
            CalcAstItem::Add,
894
            val(SizeMetric::Rem, 1.0),
895
        ];
896
        assert_eq!(evaluate_calc_ast(&items, 0.0, 10.0, 20.0), 40.0);
897
    }
898

            
899
    // ==================================================================
900
    // evaluate_calc_ast — malformed / adversarial ASTs
901
    //
902
    // The AST is only ever produced by the parser, but it also crosses an FFI
903
    // boundary (`CalcAstItemVec` is `repr(C)`), so a hand-built or corrupted
904
    // item list must degrade, never panic or hang.
905
    // ==================================================================
906

            
907
    #[test]
908
    fn eval_unmatched_brace_open_does_not_panic_or_hang() {
909
        // A lone `(` — the scan for the matching `)` runs off the end.
910
        assert_eq!(eval(&[CalcAstItem::BraceOpen], 500.0), 0.0);
911
        // `(5px` — the unterminated body is still evaluated.
912
        assert_eq!(eval(&[CalcAstItem::BraceOpen, px(5.0)], 500.0), 5.0);
913
        // `1px + (2px` -> 3
914
        let items = [px(1.0), CalcAstItem::Add, CalcAstItem::BraceOpen, px(2.0)];
915
        assert_eq!(eval(&items, 500.0), 3.0);
916
    }
917

            
918
    #[test]
919
    fn eval_stray_brace_close_is_ignored() {
920
        // `5px ) + 3px` -> the stray `)` is skipped at top level.
921
        let items = [px(5.0), CalcAstItem::BraceClose, CalcAstItem::Add, px(3.0)];
922
        assert_eq!(eval(&items, 0.0), 8.0);
923

            
924
        // A leading `)` is likewise ignored.
925
        assert_eq!(eval(&[CalcAstItem::BraceClose, px(7.0)], 0.0), 7.0);
926
    }
927

            
928
    #[test]
929
    fn eval_leading_operator_collapses_to_zero() {
930
        // Nothing to apply the operator to -> the whole expression is 0.
931
        assert_eq!(eval(&[CalcAstItem::Mul, px(5.0)], 0.0), 0.0);
932
        assert_eq!(eval(&[CalcAstItem::Add, px(5.0)], 0.0), 0.0);
933
        assert_eq!(eval(&[CalcAstItem::Div, px(5.0)], 0.0), 0.0);
934
    }
935

            
936
    #[test]
937
    fn eval_trailing_operator_keeps_the_left_hand_side() {
938
        for op in [
939
            CalcAstItem::Add,
940
            CalcAstItem::Sub,
941
            CalcAstItem::Mul,
942
            CalcAstItem::Div,
943
        ] {
944
            assert_eq!(
945
                eval(&[px(10.0), op], 0.0),
946
                10.0,
947
                "trailing {op:?} dropped the lhs"
948
            );
949
        }
950
    }
951

            
952
    #[test]
953
    fn eval_operator_only_ast_is_zero() {
954
        let items = [
955
            CalcAstItem::Add,
956
            CalcAstItem::Sub,
957
            CalcAstItem::Mul,
958
            CalcAstItem::Div,
959
        ];
960
        assert_eq!(eval(&items, 500.0), 0.0);
961
    }
962

            
963
    #[test]
964
    fn eval_adjacent_values_without_an_operator_keep_only_the_first() {
965
        // `10px 20px` is not valid calc(); the evaluator silently drops the tail
966
        // rather than panicking. Pinning the current behaviour.
967
        assert_eq!(eval(&[px(10.0), px(20.0)], 0.0), 10.0);
968
    }
969

            
970
    #[test]
971
    fn eval_adjacent_operators_do_not_panic() {
972
        // `1px + * 2px` — the orphaned `*` survives pass 1 and is skipped in pass 2.
973
        let items = [px(1.0), CalcAstItem::Add, CalcAstItem::Mul, px(2.0)];
974
        assert_eq!(eval(&items, 0.0), 1.0);
975
    }
976

            
977
    #[test]
978
    fn eval_deeply_nested_braces_do_not_overflow_the_stack() {
979
        // Brace handling recurses once per nesting level. 256 levels is far past
980
        // anything a real stylesheet produces and must still return cleanly.
981
        const DEPTH: usize = 256;
982
        let mut items: Vec<CalcAstItem> = vec![CalcAstItem::BraceOpen; DEPTH];
983
        items.push(px(1.0));
984
        items.resize(DEPTH * 2 + 1, CalcAstItem::BraceClose);
985
        assert_eq!(eval(&items, 0.0), 1.0);
986
    }
987

            
988
    #[test]
989
    fn eval_unbalanced_deep_braces_terminate() {
990
        // 256 `(` with no `)` at all: every level recurses on a strictly shorter
991
        // slice, so this must terminate rather than loop forever.
992
        let items = vec![CalcAstItem::BraceOpen; 256];
993
        assert_eq!(eval(&items, 0.0), 0.0);
994
    }
995

            
996
    #[test]
997
    fn eval_long_flat_ast_terminates_with_the_right_sum() {
998
        // 1000 terms of `1px + 1px + ...` — guards against a quadratic blow-up
999
        // or a non-advancing index in the two passes.
        const TERMS: usize = 1000;
        let mut items = Vec::with_capacity(TERMS * 2 - 1);
        for i in 0..TERMS {
            if i > 0 {
                items.push(CalcAstItem::Add);
            }
            items.push(px(1.0));
        }
        assert_eq!(eval(&items, 0.0), TERMS as f32);
    }
    // ==================================================================
    // evaluate_calc_ast — numeric edge cases
    // ==================================================================
    #[test]
    fn eval_division_by_zero_is_guarded_to_zero_not_infinity() {
        let items = [px(10.0), CalcAstItem::Div, px(0.0)];
        let got = eval(&items, 0.0);
        assert_eq!(got, 0.0);
        assert!(got.is_finite(), "10px / 0px must not be an infinity");
    }
    #[test]
    fn eval_division_by_a_zero_valued_percent_is_also_guarded() {
        // The divisor is only known after the basis is applied: 100% of a 0 basis.
        let items = [px(10.0), CalcAstItem::Div, val(SizeMetric::Percent, 100.0)];
        assert_eq!(eval(&items, 0.0), 0.0);
        // Negative zero compares equal to 0.0, so it takes the same guard and
        // yields +0.0 rather than -inf.
        let got = eval(&items, -0.0);
        assert_eq!(got, 0.0);
        assert!(got.is_finite(), "10px / (100% of -0) must not be -inf");
    }
    #[test]
    fn eval_division_by_nan_is_not_caught_by_the_zero_guard() {
        // The guard is `rhs == 0.0`, which NaN fails — so the NaN propagates.
        // Defined, not a panic, but worth pinning: NaN divisors are NOT sanitised.
        let items = [px(10.0), CalcAstItem::Div, val(SizeMetric::Percent, 100.0)];
        assert!(eval(&items, f32::NAN).is_nan());
    }
    #[test]
    fn eval_divisor_below_fixed_point_precision_truncates_into_the_zero_guard() {
        // `FloatValue` keeps 3 decimal places, so 0.0001 encodes to *exactly* 0 —
        // a divisor that is non-zero in the stylesheet but zero by the time the
        // evaluator sees it. `calc(10px / 0.0001)` is therefore 0px, not 100000px.
        assert_eq!(PixelValue::px(0.0001).number.get(), 0.0);
        let items = [px(10.0), CalcAstItem::Div, px(0.0001)];
        assert_eq!(eval(&items, 0.0), 0.0);
        // 0.001 is the smallest divisor that survives the encoding.
        assert_close(PixelValue::px(0.001).number.get(), 0.001);
        let items = [px(10.0), CalcAstItem::Div, px(0.001)];
        let got = eval(&items, 0.0);
        assert!(
            got.is_finite(),
            "10px / 0.001px should be finite, got {got}"
        );
        assert_close(got, 10_000.0);
    }
    #[test]
    fn eval_multiplication_overflow_saturates_to_infinity_without_panicking() {
        // Chain enough saturated values that the product overflows f32 on any
        // isize width (64-bit *and* 32-bit/wasm).
        let mut items = vec![px(f32::MAX)];
        for _ in 0..7 {
            items.push(CalcAstItem::Mul);
            items.push(px(f32::MAX));
        }
        let got = eval(&items, 0.0);
        assert!(
            got.is_infinite() && got.is_sign_positive(),
            "expected +inf on overflow, got {got}",
        );
    }
    #[test]
    fn eval_inf_minus_inf_is_nan_not_a_panic() {
        // An infinite basis makes both percentages infinite; inf - inf == NaN.
        let items = [
            val(SizeMetric::Percent, 100.0),
            CalcAstItem::Sub,
            val(SizeMetric::Percent, 100.0),
        ];
        assert!(eval(&items, f32::INFINITY).is_nan());
    }
    #[test]
    fn eval_nan_basis_does_not_leak_into_an_absolute_expression() {
        let items = [px(10.0), CalcAstItem::Add, px(5.0)];
        assert_eq!(eval(&items, f32::NAN), 15.0);
        assert_eq!(eval(&items, f32::INFINITY), 15.0);
    }
    #[test]
    fn eval_negative_results_are_not_clamped() {
        // calc(20px - 100%) with a 500px basis is legitimately negative here;
        // clamping is the caller's job, not the evaluator's.
        let items = [px(20.0), CalcAstItem::Sub, val(SizeMetric::Percent, 100.0)];
        assert_eq!(eval(&items, 500.0), -480.0);
    }
    #[test]
    fn eval_viewport_units_inside_calc_use_the_no_viewport_fallback() {
        // evaluate_calc_ast routes through `resolve_pixel_value`, which has no
        // viewport context — so `50vw` inside calc() degrades to `50px`.
        let items = [val(SizeMetric::Vw, 50.0), CalcAstItem::Add, px(0.0)];
        assert_eq!(eval(&items, 1000.0), 50.0);
    }
    // ==================================================================
    // evaluate_calc (public wrapper)
    // ==================================================================
    #[test]
    fn evaluate_calc_empty_context_is_zero() {
        let c = ctx(Vec::new(), 16.0, 10.0);
        assert_eq!(evaluate_calc(&c, 500.0), 0.0);
        assert_eq!(evaluate_calc(&c, f32::NAN), 0.0);
    }
    #[test]
    fn evaluate_calc_matches_the_ast_evaluator_it_wraps() {
        let items = vec![
            val(SizeMetric::Percent, 100.0),
            CalcAstItem::Sub,
            CalcAstItem::BraceOpen,
            val(SizeMetric::Em, 2.0),
            CalcAstItem::Add,
            val(SizeMetric::Rem, 1.0),
            CalcAstItem::BraceClose,
        ];
        let c = ctx(items.clone(), 12.0, 20.0);
        // 100% of 500 - (2*12 + 1*20) == 500 - 44 == 456
        assert_eq!(evaluate_calc(&c, 500.0), 456.0);
        assert_eq!(
            evaluate_calc(&c, 500.0),
            evaluate_calc_ast(&items, 500.0, 12.0, 20.0)
        );
    }
    #[test]
    fn evaluate_calc_forwards_its_own_em_and_rem_sizes_without_swapping_them() {
        // `2em + 1rem` is asymmetric on purpose: swapping em/rem must change the
        // answer, which a transposed-argument bug in the wrapper would not.
        let items = vec![
            val(SizeMetric::Em, 2.0),
            CalcAstItem::Add,
            val(SizeMetric::Rem, 1.0),
        ];
        assert_eq!(evaluate_calc(&ctx(items.clone(), 10.0, 20.0), 0.0), 40.0);
        assert_eq!(evaluate_calc(&ctx(items, 20.0, 10.0), 0.0), 50.0);
    }
    #[test]
    fn evaluate_calc_with_hostile_font_sizes_does_not_panic() {
        let items = vec![val(SizeMetric::Em, 2.0), CalcAstItem::Add, px(1.0)];
        assert!(evaluate_calc(&ctx(items.clone(), f32::NAN, 10.0), 0.0).is_nan());
        let inf = evaluate_calc(&ctx(items.clone(), f32::INFINITY, 10.0), 0.0);
        assert!(inf.is_infinite() && inf.is_sign_positive());
        // A zero font-size is legal CSS and must give a plain 1px, not NaN.
        assert_eq!(evaluate_calc(&ctx(items, 0.0, 10.0), 0.0), 1.0);
    }
    #[test]
    fn evaluate_calc_is_pure_and_repeatable() {
        // The context is borrowed, not consumed: evaluating twice with different
        // bases must not mutate or corrupt the AST.
        let c = ctx(
            vec![val(SizeMetric::Percent, 50.0), CalcAstItem::Add, px(10.0)],
            16.0,
            10.0,
        );
        assert_eq!(evaluate_calc(&c, 100.0), 60.0);
        assert_eq!(evaluate_calc(&c, 200.0), 110.0);
        assert_eq!(evaluate_calc(&c, 100.0), 60.0);
    }
}