pdf_oxide 0.3.38

The fastest Rust PDF library with text extraction: 0.8ms mean, 100% pass rate on 3,830 PDFs. 5× faster than pdf_extract, 17× faster than oxidize_pdf. Extract, create, and edit PDFs.
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
//! `calc()` / `min()` / `max()` / `clamp()` evaluator (CSS-6).
//!
//! Turns the body of a `calc(...)` (or sibling math function) — a
//! `Vec<ComponentValue>` produced by the parser (CSS-2) — into an
//! [`Expr`] tree, and evaluates it to a single resolved px length
//! given a [`Context`] that supplies em / rem / vw / vh / % bases.
//!
//! Property parsing (CSS-8) consumes this when a length-bearing
//! property has a `Function { name: "calc", body }` value:
//!
//! ```ignore
//! use pdf_oxide::html_css::css::calc::{evaluate_function, Context};
//! let ctx = Context { parent_px: 600.0, font_size_px: 16.0,
//!                     root_font_size_px: 16.0, viewport_w_px: 1024.0,
//!                     viewport_h_px: 768.0 };
//! let px = evaluate_function("calc", &body, &ctx)?;  // → 580.0
//! ```
//!
//! v0.3.35 supports the units listed in [`Unit`], the four basic
//! operators, parentheses, `min(a, b, ...)`, `max(a, b, ...)`, and
//! `clamp(min, val, max)`. Constants (`pi`, `e`, `infinity`) and
//! advanced math functions (`sin`, `mod`, `round`, …) are deferred —
//! they parse cleanly via the existing component-value tree but
//! evaluate to a `Err(EvalError::UnsupportedFunction)`.

use thiserror::Error;

use super::parser::ComponentValue;
use super::tokenizer::Token;

// ─────────────────────────────────────────────────────────────────────
// Public API
// ─────────────────────────────────────────────────────────────────────

/// Layout context required to resolve relative CSS lengths to px.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Context {
    /// Containing block's resolved width (or height — caller picks
    /// based on which axis the property lives on) in px. Drives `%`
    /// resolution.
    pub parent_px: f32,
    /// Element's own resolved `font-size` in px. Drives `em`.
    pub font_size_px: f32,
    /// Root element's resolved `font-size` in px. Drives `rem`.
    pub root_font_size_px: f32,
    /// Viewport width in px — drives `vw`/`vmin`/`vmax`.
    pub viewport_w_px: f32,
    /// Viewport height in px — drives `vh`/`vmin`/`vmax`.
    pub viewport_h_px: f32,
}

impl Default for Context {
    fn default() -> Self {
        // Sensible defaults for unit tests + cases where no DOM
        // context exists yet.
        Self {
            parent_px: 0.0,
            font_size_px: 16.0,
            root_font_size_px: 16.0,
            viewport_w_px: 1024.0,
            viewport_h_px: 768.0,
        }
    }
}

/// CSS length unit understood by the evaluator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unit {
    /// Already in px — no conversion needed.
    Px,
    /// `pt` = 4/3 px (CSS reference pixel @ 96 dpi).
    Pt,
    /// `pc` = 16 px.
    Pc,
    /// `in` = 96 px.
    In,
    /// `cm` = 96/2.54 px.
    Cm,
    /// `mm` = `cm`/10.
    Mm,
    /// `Q` = `mm`/4 (quarter-millimetre).
    Q,
    /// `em` = element's font-size.
    Em,
    /// `rem` = root font-size.
    Rem,
    /// `ex` ≈ 0.5em (DejaVu-style approximation; no per-font ex height
    /// here, refine in CSS-8 once the typed length supports per-font
    /// metrics).
    Ex,
    /// `ch` ≈ 0.5em (rough; same caveat as `ex`).
    Ch,
    /// `vw` = viewport width %.
    Vw,
    /// `vh` = viewport height %.
    Vh,
    /// `vmin` = min(vw, vh).
    Vmin,
    /// `vmax` = max(vw, vh).
    Vmax,
    /// Percentage of `parent_px`.
    Percent,
    /// Unitless number — only valid in multipliers/divisors and as
    /// `line-height`. The evaluator returns its raw value when used
    /// as a length, callers decide if that's an error.
    None,
}

impl Unit {
    /// Convert this unit to px given a context.
    pub fn to_px(self, value: f32, ctx: &Context) -> f32 {
        match self {
            Unit::Px => value,
            Unit::Pt => value * (4.0 / 3.0),
            Unit::Pc => value * 16.0,
            Unit::In => value * 96.0,
            Unit::Cm => value * (96.0 / 2.54),
            Unit::Mm => value * (96.0 / 25.4),
            Unit::Q => value * (96.0 / 25.4 / 4.0),
            Unit::Em => value * ctx.font_size_px,
            Unit::Rem => value * ctx.root_font_size_px,
            // Ex / Ch are font-relative; without font metrics, the spec
            // permits a 0.5em fallback for Ex and 0.5em for Ch.
            Unit::Ex | Unit::Ch => value * ctx.font_size_px * 0.5,
            Unit::Vw => value * ctx.viewport_w_px / 100.0,
            Unit::Vh => value * ctx.viewport_h_px / 100.0,
            Unit::Vmin => value * ctx.viewport_w_px.min(ctx.viewport_h_px) / 100.0,
            Unit::Vmax => value * ctx.viewport_w_px.max(ctx.viewport_h_px) / 100.0,
            Unit::Percent => value * ctx.parent_px / 100.0,
            Unit::None => value,
        }
    }

    /// Look up by lowercase unit string. Returns `None` for an
    /// unknown unit.
    pub fn parse(s: &str) -> Option<Self> {
        Some(match s.to_ascii_lowercase().as_str() {
            "px" => Self::Px,
            "pt" => Self::Pt,
            "pc" => Self::Pc,
            "in" => Self::In,
            "cm" => Self::Cm,
            "mm" => Self::Mm,
            "q" => Self::Q,
            "em" => Self::Em,
            "rem" => Self::Rem,
            "ex" => Self::Ex,
            "ch" => Self::Ch,
            "vw" => Self::Vw,
            "vh" => Self::Vh,
            "vmin" => Self::Vmin,
            "vmax" => Self::Vmax,
            _ => return None,
        })
    }
}

/// Calc expression tree.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    /// A numeric literal with a unit.
    Number(f32, Unit),
    /// `a + b`.
    Add(Box<Expr>, Box<Expr>),
    /// `a - b`.
    Sub(Box<Expr>, Box<Expr>),
    /// `a * b`.
    Mul(Box<Expr>, Box<Expr>),
    /// `a / b`.
    Div(Box<Expr>, Box<Expr>),
    /// `min(a, b, ...)`.
    Min(Vec<Expr>),
    /// `max(a, b, ...)`.
    Max(Vec<Expr>),
    /// `clamp(low, val, high)`.
    Clamp(Box<Expr>, Box<Expr>, Box<Expr>),
    /// `calc(...)` nested.
    Calc(Box<Expr>),
}

/// Errors from parse + evaluate phases.
#[derive(Debug, Error, PartialEq)]
pub enum EvalError {
    /// Empty expression body.
    #[error("empty calc() body")]
    Empty,
    /// Unrecognised token in a place we expected an operand or
    /// operator.
    #[error("unexpected token in calc()")]
    UnexpectedToken,
    /// Unknown unit (e.g. `12foo`).
    #[error("unknown unit: {0}")]
    UnknownUnit(String),
    /// Division by zero.
    #[error("division by zero in calc()")]
    DivByZero,
    /// `clamp(a, b, c)` requires exactly three arguments.
    #[error("clamp() requires three arguments, got {0}")]
    ClampArity(usize),
    /// Function name we know about but don't yet evaluate (e.g.
    /// `sin`, `mod`).
    #[error("unsupported math function: {0}")]
    UnsupportedFunction(String),
    /// Parser couldn't balance brackets / saw EOF mid-expression.
    #[error("malformed calc() expression")]
    Malformed,
}

/// Top-level: resolve a math-function call (`calc`, `min`, `max`,
/// `clamp`) given its body component-values and a context, returning
/// a final px value.
pub fn evaluate_function(
    name: &str,
    body: &[ComponentValue<'_>],
    ctx: &Context,
) -> Result<f32, EvalError> {
    let expr = match name.to_ascii_lowercase().as_str() {
        "calc" => parse_expr(body)?,
        "min" => Expr::Min(parse_arg_list(body)?),
        "max" => Expr::Max(parse_arg_list(body)?),
        "clamp" => {
            let mut args = parse_arg_list(body)?;
            if args.len() != 3 {
                return Err(EvalError::ClampArity(args.len()));
            }
            let high = args.pop().unwrap();
            let val = args.pop().unwrap();
            let low = args.pop().unwrap();
            Expr::Clamp(Box::new(low), Box::new(val), Box::new(high))
        },
        other => return Err(EvalError::UnsupportedFunction(other.to_string())),
    };
    evaluate(&expr, ctx)
}

/// Evaluate an [`Expr`] tree.
pub fn evaluate(expr: &Expr, ctx: &Context) -> Result<f32, EvalError> {
    match expr {
        Expr::Number(v, u) => Ok(u.to_px(*v, ctx)),
        Expr::Add(a, b) => Ok(evaluate(a, ctx)? + evaluate(b, ctx)?),
        Expr::Sub(a, b) => Ok(evaluate(a, ctx)? - evaluate(b, ctx)?),
        Expr::Mul(a, b) => Ok(evaluate(a, ctx)? * evaluate(b, ctx)?),
        Expr::Div(a, b) => {
            let denom = evaluate(b, ctx)?;
            if denom == 0.0 {
                Err(EvalError::DivByZero)
            } else {
                Ok(evaluate(a, ctx)? / denom)
            }
        },
        Expr::Min(items) => {
            let mut acc = f32::INFINITY;
            for it in items {
                let v = evaluate(it, ctx)?;
                if v < acc {
                    acc = v;
                }
            }
            Ok(acc)
        },
        Expr::Max(items) => {
            let mut acc = f32::NEG_INFINITY;
            for it in items {
                let v = evaluate(it, ctx)?;
                if v > acc {
                    acc = v;
                }
            }
            Ok(acc)
        },
        Expr::Clamp(low, val, high) => {
            let l = evaluate(low, ctx)?;
            let v = evaluate(val, ctx)?;
            let h = evaluate(high, ctx)?;
            Ok(v.clamp(l, h))
        },
        Expr::Calc(inner) => evaluate(inner, ctx),
    }
}

// ─────────────────────────────────────────────────────────────────────
// Parser — Pratt-style precedence climbing over component values
// ─────────────────────────────────────────────────────────────────────

/// Parse the body of a `calc(...)` into an expression tree.
pub fn parse_expr(body: &[ComponentValue<'_>]) -> Result<Expr, EvalError> {
    let mut p = ExprParser::new(body);
    let expr = p.parse_add_sub()?;
    p.expect_end()?;
    Ok(expr)
}

/// Parse a comma-separated list of expressions (for `min`/`max`/`clamp`).
fn parse_arg_list(body: &[ComponentValue<'_>]) -> Result<Vec<Expr>, EvalError> {
    if body.is_empty() {
        return Err(EvalError::Empty);
    }
    let mut args = Vec::new();
    for chunk in split_top_level_commas(body) {
        args.push(parse_expr(chunk)?);
    }
    Ok(args)
}

struct ExprParser<'a, 'i> {
    cvs: &'a [ComponentValue<'i>],
    pos: usize,
}

impl<'a, 'i> ExprParser<'a, 'i> {
    fn new(cvs: &'a [ComponentValue<'i>]) -> Self {
        Self { cvs, pos: 0 }
    }

    fn peek(&self) -> Option<&ComponentValue<'i>> {
        self.cvs.get(self.pos)
    }

    fn bump(&mut self) -> Option<&ComponentValue<'i>> {
        let r = self.cvs.get(self.pos);
        self.pos += 1;
        r
    }

    fn skip_ws(&mut self) {
        while matches!(self.peek(), Some(ComponentValue::Token(Token::Whitespace))) {
            self.pos += 1;
        }
    }

    fn expect_end(&mut self) -> Result<(), EvalError> {
        self.skip_ws();
        if self.pos < self.cvs.len() {
            Err(EvalError::Malformed)
        } else {
            Ok(())
        }
    }

    /// + / - precedence (lowest).
    fn parse_add_sub(&mut self) -> Result<Expr, EvalError> {
        self.skip_ws();
        let mut left = self.parse_mul_div()?;
        loop {
            self.skip_ws();
            let op = match self.peek() {
                Some(ComponentValue::Token(Token::Delim('+'))) => {
                    self.bump();
                    self.skip_ws();
                    Some(true)
                },
                Some(ComponentValue::Token(Token::Delim('-'))) => {
                    self.bump();
                    self.skip_ws();
                    Some(false)
                },
                _ => None,
            };
            let Some(is_add) = op else { break };
            let right = self.parse_mul_div()?;
            left = if is_add {
                Expr::Add(Box::new(left), Box::new(right))
            } else {
                Expr::Sub(Box::new(left), Box::new(right))
            };
        }
        Ok(left)
    }

    /// * / / precedence (higher).
    fn parse_mul_div(&mut self) -> Result<Expr, EvalError> {
        self.skip_ws();
        let mut left = self.parse_atom()?;
        loop {
            self.skip_ws();
            let op = match self.peek() {
                Some(ComponentValue::Token(Token::Delim('*'))) => {
                    self.bump();
                    self.skip_ws();
                    Some(true)
                },
                Some(ComponentValue::Token(Token::Delim('/'))) => {
                    self.bump();
                    self.skip_ws();
                    Some(false)
                },
                _ => None,
            };
            let Some(is_mul) = op else { break };
            let right = self.parse_atom()?;
            left = if is_mul {
                Expr::Mul(Box::new(left), Box::new(right))
            } else {
                Expr::Div(Box::new(left), Box::new(right))
            };
        }
        Ok(left)
    }

    /// Atom: number, dimension, percentage, parens, or nested
    /// calc/min/max/clamp.
    fn parse_atom(&mut self) -> Result<Expr, EvalError> {
        self.skip_ws();
        let cv = self.bump().ok_or(EvalError::Empty)?;
        match cv {
            ComponentValue::Token(Token::Number(n)) => Ok(Expr::Number(n.value as f32, Unit::None)),
            ComponentValue::Token(Token::Dimension { value, unit }) => {
                let u =
                    Unit::parse(unit).ok_or_else(|| EvalError::UnknownUnit(unit.to_string()))?;
                Ok(Expr::Number(value.value as f32, u))
            },
            ComponentValue::Token(Token::Percentage(n)) => {
                Ok(Expr::Number(n.value as f32, Unit::Percent))
            },
            ComponentValue::Parens(body) => parse_expr(body),
            ComponentValue::Function { name, body } => {
                let lower = name.to_ascii_lowercase();
                match lower.as_str() {
                    "calc" => {
                        let inner = parse_expr(body)?;
                        Ok(Expr::Calc(Box::new(inner)))
                    },
                    "min" => Ok(Expr::Min(parse_arg_list(body)?)),
                    "max" => Ok(Expr::Max(parse_arg_list(body)?)),
                    "clamp" => {
                        let mut args = parse_arg_list(body)?;
                        if args.len() != 3 {
                            return Err(EvalError::ClampArity(args.len()));
                        }
                        let high = args.pop().unwrap();
                        let val = args.pop().unwrap();
                        let low = args.pop().unwrap();
                        Ok(Expr::Clamp(Box::new(low), Box::new(val), Box::new(high)))
                    },
                    _ => Err(EvalError::UnsupportedFunction(lower)),
                }
            },
            // Unary +/- on the next atom.
            ComponentValue::Token(Token::Delim('+')) => self.parse_atom(),
            ComponentValue::Token(Token::Delim('-')) => {
                let inner = self.parse_atom()?;
                Ok(Expr::Sub(Box::new(Expr::Number(0.0, Unit::None)), Box::new(inner)))
            },
            _ => Err(EvalError::UnexpectedToken),
        }
    }
}

fn split_top_level_commas<'a, 'i>(cvs: &'a [ComponentValue<'i>]) -> Vec<&'a [ComponentValue<'i>]> {
    let mut out = Vec::new();
    let mut start = 0;
    for (i, cv) in cvs.iter().enumerate() {
        if matches!(cv, ComponentValue::Token(Token::Comma)) {
            out.push(&cvs[start..i]);
            start = i + 1;
        }
    }
    out.push(&cvs[start..]);
    out
}

// ─────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::html_css::css::parser::{parse_stylesheet, Rule};

    /// Helper: pull the body of `calc(...)` (or any function) out of
    /// the first declaration of the first rule in `css`.
    fn func_body<'a>(css: &'a str, name: &str) -> Vec<ComponentValue<'a>> {
        let ss = Box::leak(Box::new(parse_stylesheet(css).unwrap()));
        let r = match &ss.rules[0] {
            Rule::Qualified(q) => q,
            _ => unreachable!(),
        };
        let val = &r.declarations[0].value;
        for cv in val {
            if let ComponentValue::Function { name: n, body } = cv {
                if n.eq_ignore_ascii_case(name) {
                    return body.clone();
                }
            }
        }
        panic!("no {name}() found in: {val:?}");
    }

    fn ctx() -> Context {
        Context {
            parent_px: 600.0,
            font_size_px: 16.0,
            root_font_size_px: 16.0,
            viewport_w_px: 1024.0,
            viewport_h_px: 768.0,
        }
    }

    #[test]
    fn unit_conversions() {
        let c = ctx();
        assert!((Unit::Pt.to_px(12.0, &c) - 16.0).abs() < 1e-3); // 12pt = 16px
        assert!((Unit::In.to_px(1.0, &c) - 96.0).abs() < 1e-3);
        assert!((Unit::Cm.to_px(2.54, &c) - 96.0).abs() < 1e-3);
        assert_eq!(Unit::Em.to_px(2.0, &c), 32.0);
        assert_eq!(Unit::Rem.to_px(1.5, &c), 24.0);
        assert_eq!(Unit::Vw.to_px(50.0, &c), 512.0);
        assert_eq!(Unit::Percent.to_px(25.0, &c), 150.0);
    }

    #[test]
    fn calc_simple_subtract() {
        let body = func_body("p { width: calc(100% - 20px); }", "calc");
        let v = evaluate_function("calc", &body, &ctx()).unwrap();
        // 100% of 600 = 600, - 20 = 580
        assert!((v - 580.0).abs() < 1e-3);
    }

    #[test]
    fn calc_nested_parens_with_precedence() {
        // calc(2 * (10px + 5px)) = 30px
        let body = func_body("p { width: calc(2 * (10px + 5px)); }", "calc");
        let v = evaluate_function("calc", &body, &ctx()).unwrap();
        assert!((v - 30.0).abs() < 1e-3);
    }

    #[test]
    fn calc_mul_div_precedence_over_add() {
        // calc(10 + 2 * 3px) = 10 + 6 = 16
        let body = func_body("p { width: calc(10 + 2 * 3px); }", "calc");
        let v = evaluate_function("calc", &body, &ctx()).unwrap();
        assert!((v - 16.0).abs() < 1e-3);
    }

    #[test]
    fn calc_em_resolves_against_font_size() {
        // calc(2em + 4px) = 32 + 4 = 36
        let body = func_body("p { width: calc(2em + 4px); }", "calc");
        let v = evaluate_function("calc", &body, &ctx()).unwrap();
        assert!((v - 36.0).abs() < 1e-3);
    }

    #[test]
    fn min_picks_smallest() {
        let body = func_body("p { width: min(50px, 100px, 25px); }", "min");
        let v = evaluate_function("min", &body, &ctx()).unwrap();
        assert!((v - 25.0).abs() < 1e-3);
    }

    #[test]
    fn max_picks_largest() {
        let body = func_body("p { width: max(50px, 100px, 25px); }", "max");
        let v = evaluate_function("max", &body, &ctx()).unwrap();
        assert!((v - 100.0).abs() < 1e-3);
    }

    #[test]
    fn clamp_three_args() {
        // clamp(50px, 100%, 800px) where parent is 600px: 50 < 600 < 800 → 600
        let body = func_body("p { width: clamp(50px, 100%, 800px); }", "clamp");
        let v = evaluate_function("clamp", &body, &ctx()).unwrap();
        assert!((v - 600.0).abs() < 1e-3);
    }

    #[test]
    fn clamp_lower_bound_engaged() {
        let body = func_body("p { width: clamp(700px, 100%, 800px); }", "clamp");
        let v = evaluate_function("clamp", &body, &ctx()).unwrap();
        assert!((v - 700.0).abs() < 1e-3);
    }

    #[test]
    fn clamp_upper_bound_engaged() {
        let body = func_body("p { width: clamp(50px, 100%, 400px); }", "clamp");
        let v = evaluate_function("clamp", &body, &ctx()).unwrap();
        assert!((v - 400.0).abs() < 1e-3);
    }

    #[test]
    fn nested_calc_in_calc() {
        let body = func_body("p { width: calc(10px + calc(5px + 5px)); }", "calc");
        let v = evaluate_function("calc", &body, &ctx()).unwrap();
        assert!((v - 20.0).abs() < 1e-3);
    }

    #[test]
    fn min_in_calc() {
        let body = func_body("p { width: calc(10px + min(20px, 30px)); }", "calc");
        let v = evaluate_function("calc", &body, &ctx()).unwrap();
        assert!((v - 30.0).abs() < 1e-3);
    }

    #[test]
    fn unary_minus() {
        let body = func_body("p { width: calc(-10px + 50px); }", "calc");
        let v = evaluate_function("calc", &body, &ctx()).unwrap();
        assert!((v - 40.0).abs() < 1e-3);
    }

    #[test]
    fn division_by_zero_errors() {
        let body = func_body("p { width: calc(10px / 0); }", "calc");
        let res = evaluate_function("calc", &body, &ctx());
        assert!(matches!(res, Err(EvalError::DivByZero)));
    }

    #[test]
    fn unknown_unit_errors() {
        let body = func_body("p { width: calc(12foo + 1px); }", "calc");
        let res = evaluate_function("calc", &body, &ctx());
        assert!(matches!(res, Err(EvalError::UnknownUnit(_))));
    }

    #[test]
    fn unsupported_math_function() {
        let body = func_body("p { width: calc(sin(1deg)); }", "calc");
        let res = evaluate_function("calc", &body, &ctx());
        assert!(matches!(res, Err(EvalError::UnsupportedFunction(_))));
    }
}