browser_oxide 0.1.3

Stealth headless browser engine in Rust: real HTML/CSS/DOM/JS, V8 via deno_core, own BoringSSL TLS/JA4 fingerprint, no Chromium, no CDP — for anti-bot web scraping, archival, and AI agents
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! CSS `calc()` parser — converts a `CssFunction` from `css_parser` into
//! a [`CalcExpr`] tree that [`CalcExpr::evaluate`] can resolve.
//!
//! Implements the full CSS Values 4 math function set Chrome 147 ships:
//! - arithmetic: `+`, `-`, `*`, `/`
//! - comparison: `min(...)`, `max(...)`, `clamp(min, val, max)`
//! - stepped: `round([strategy,] a [, b])`, `mod(a, b)`, `rem(a, b)`
//! - trigonometric: `sin/cos/tan/asin/acos/atan/atan2`
//! - exponential: `pow(b, e)`, `sqrt(x)`, `hypot(...)`, `log(x [, b])`, `exp(x)`
//! - sign: `abs(x)`, `sign(x)`
//! - constants: `pi`, `e`, `infinity`, `-infinity`, `NaN`
//!
//! See `crates/css_values/src/types/length.rs` for the AST + evaluator.
//!
//! Why this exists: the challenge vendor (and many other antibot stacks)
//! inject deeply-nested calc() expressions with sin/cos/tan/sqrt/pi as a
//! browser-fingerprint precision probe — they evaluate the result via
//! `getComputedStyle` and compare against expected Chrome f64 output.
//! Engines that don't implement these functions return `auto` or wrong
//! values and get caught.

use crate::css_parser::ast::{ComponentValue, CssFunction};
use crate::css_parser::token::{Token, TokenKind};
use crate::css_values::types::length::{
    AngleUnit, CalcExpr, CalcValue, LengthUnit, NumericConstant, RoundStrategy,
};

#[derive(Debug)]
pub enum CalcParseError {
    Empty,
    UnexpectedToken(String),
    UnknownFunction(String),
    WrongArity {
        name: String,
        expected: &'static str,
        got: usize,
    },
    InvalidUnit(String),
}

impl std::fmt::Display for CalcParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Empty => write!(f, "empty calc() arguments"),
            Self::UnexpectedToken(s) => write!(f, "unexpected token: {s}"),
            Self::UnknownFunction(s) => write!(f, "unknown math function: {s}"),
            Self::WrongArity {
                name,
                expected,
                got,
            } => {
                write!(f, "{name}() arity: expected {expected}, got {got}")
            }
            Self::InvalidUnit(s) => write!(f, "unknown unit: {s}"),
        }
    }
}

impl std::error::Error for CalcParseError {}

/// Parse a top-level math function call (`calc`, `min`, `max`, `clamp`,
/// or any other CSS Values 4 math function name) into a [`CalcExpr`].
/// Returns `Ok(None)` if the function name is not a math function — the
/// caller should fall through to its existing parse path for `var()`,
/// `env()`, gradient functions, etc.
pub fn parse_math_function(f: &CssFunction<'_>) -> Result<Option<CalcExpr>, CalcParseError> {
    let name = f.name.to_ascii_lowercase();
    match name.as_str() {
        "calc" => Ok(Some(parse_sum(&filter_ws(&f.arguments))?)),
        "min" | "max" | "hypot" => {
            let parts = split_top_level_commas(&f.arguments);
            if parts.is_empty() {
                return Err(CalcParseError::Empty);
            }
            let exprs = parts
                .into_iter()
                .map(|p| parse_sum(&filter_ws(p)))
                .collect::<Result<Vec<_>, _>>()?;
            Ok(Some(match name.as_str() {
                "min" => CalcExpr::Min(exprs),
                "max" => CalcExpr::Max(exprs),
                "hypot" => CalcExpr::Hypot(exprs),
                _ => unreachable!(),
            }))
        }
        "clamp" => {
            let parts = split_top_level_commas(&f.arguments);
            if parts.len() != 3 {
                return Err(CalcParseError::WrongArity {
                    name: "clamp".into(),
                    expected: "3 (min, val, max)",
                    got: parts.len(),
                });
            }
            Ok(Some(CalcExpr::Clamp {
                min: Box::new(parse_sum(&filter_ws(parts[0]))?),
                preferred: Box::new(parse_sum(&filter_ws(parts[1]))?),
                max: Box::new(parse_sum(&filter_ws(parts[2]))?),
            }))
        }
        "sin" | "cos" | "tan" | "asin" | "acos" | "atan" | "sqrt" | "exp" | "abs" | "sign" => {
            let parts = split_top_level_commas(&f.arguments);
            if parts.len() != 1 {
                return Err(CalcParseError::WrongArity {
                    name,
                    expected: "1",
                    got: parts.len(),
                });
            }
            let inner = Box::new(parse_sum(&filter_ws(parts[0]))?);
            Ok(Some(match name.as_str() {
                "sin" => CalcExpr::Sin(inner),
                "cos" => CalcExpr::Cos(inner),
                "tan" => CalcExpr::Tan(inner),
                "asin" => CalcExpr::Asin(inner),
                "acos" => CalcExpr::Acos(inner),
                "atan" => CalcExpr::Atan(inner),
                "sqrt" => CalcExpr::Sqrt(inner),
                "exp" => CalcExpr::Exp(inner),
                "abs" => CalcExpr::Abs(inner),
                "sign" => CalcExpr::Sign(inner),
                _ => unreachable!(),
            }))
        }
        "atan2" | "pow" | "mod" | "rem" => {
            let parts = split_top_level_commas(&f.arguments);
            if parts.len() != 2 {
                return Err(CalcParseError::WrongArity {
                    name,
                    expected: "2",
                    got: parts.len(),
                });
            }
            let a = Box::new(parse_sum(&filter_ws(parts[0]))?);
            let b = Box::new(parse_sum(&filter_ws(parts[1]))?);
            Ok(Some(match name.as_str() {
                "atan2" => CalcExpr::Atan2(a, b),
                "pow" => CalcExpr::Pow(a, b),
                "mod" => CalcExpr::Mod(a, b),
                "rem" => CalcExpr::Rem(a, b),
                _ => unreachable!(),
            }))
        }
        "log" => {
            let parts = split_top_level_commas(&f.arguments);
            match parts.len() {
                1 => Ok(Some(CalcExpr::Log {
                    value: Box::new(parse_sum(&filter_ws(parts[0]))?),
                    base: None,
                })),
                2 => Ok(Some(CalcExpr::Log {
                    value: Box::new(parse_sum(&filter_ws(parts[0]))?),
                    base: Some(Box::new(parse_sum(&filter_ws(parts[1]))?)),
                })),
                got => Err(CalcParseError::WrongArity {
                    name: "log".into(),
                    expected: "1 or 2",
                    got,
                }),
            }
        }
        "round" => {
            // round([strategy ,] A [, B])
            let parts = split_top_level_commas(&f.arguments);
            let (strategy, value_idx) = if let Some(first) = parts.first() {
                let toks = filter_ws(first);
                if toks.len() == 1 {
                    if let ComponentValue::Token(Token {
                        kind: TokenKind::Ident(id),
                        ..
                    }) = &toks[0]
                    {
                        match id.to_ascii_lowercase().as_str() {
                            "nearest" => (RoundStrategy::Nearest, 1),
                            "up" => (RoundStrategy::Up, 1),
                            "down" => (RoundStrategy::Down, 1),
                            "to-zero" => (RoundStrategy::ToZero, 1),
                            _ => (RoundStrategy::Nearest, 0),
                        }
                    } else {
                        (RoundStrategy::Nearest, 0)
                    }
                } else {
                    (RoundStrategy::Nearest, 0)
                }
            } else {
                return Err(CalcParseError::Empty);
            };
            let value = Box::new(parse_sum(&filter_ws(parts[value_idx]))?);
            let step: Box<CalcExpr> = if parts.len() > value_idx + 1 {
                Box::new(parse_sum(&filter_ws(parts[value_idx + 1]))?)
            } else {
                Box::new(CalcExpr::Value(CalcValue::Number(1.0)))
            };
            Ok(Some(CalcExpr::Round(strategy, value, step)))
        }
        // Not a math function — caller may handle (var(), env(), etc.).
        _ => Ok(None),
    }
}

// =====================================================================
// Recursive-descent precedence parser for calc()'s grammar:
//   sum     := product (('+'|'-') product)*
//   product := unary (('*'|'/') unary)*
//   unary   := '-' unary | atom
//   atom    := number | dimension | percentage | constant-ident
//            | '(' sum ')' | math-function
// CSS Values 4 requires whitespace around '+'/'-' (already handled by the
// tokenizer producing separate Whitespace + Delim tokens). We expect the
// caller to have already stripped Whitespace via `filter_ws` so the
// grammar can match on Delim positions cleanly.
// =====================================================================

fn filter_ws<'a>(tokens: &'a [ComponentValue<'a>]) -> Vec<&'a ComponentValue<'a>> {
    tokens
        .iter()
        .filter(|cv| {
            !matches!(
                cv,
                ComponentValue::Token(Token {
                    kind: TokenKind::Whitespace,
                    ..
                })
            )
        })
        .collect()
}

fn split_top_level_commas<'a>(tokens: &'a [ComponentValue<'a>]) -> Vec<&'a [ComponentValue<'a>]> {
    let mut out = Vec::new();
    let mut start = 0usize;
    for (i, cv) in tokens.iter().enumerate() {
        if matches!(
            cv,
            ComponentValue::Token(Token {
                kind: TokenKind::Comma,
                ..
            })
        ) {
            out.push(&tokens[start..i]);
            start = i + 1;
        }
    }
    if start <= tokens.len() {
        let tail = &tokens[start..];
        // Skip a trailing-only-whitespace tail (no real argument).
        if !tail.iter().all(|cv| {
            matches!(
                cv,
                ComponentValue::Token(Token {
                    kind: TokenKind::Whitespace,
                    ..
                })
            )
        }) {
            out.push(tail);
        }
    }
    out
}

fn parse_sum<'a>(tokens: &[&'a ComponentValue<'a>]) -> Result<CalcExpr, CalcParseError> {
    if tokens.is_empty() {
        return Err(CalcParseError::Empty);
    }
    let mut pos = 0usize;
    let mut left = parse_product(tokens, &mut pos)?;
    while pos < tokens.len() {
        match tokens[pos] {
            ComponentValue::Token(Token {
                kind: TokenKind::Delim('+'),
                ..
            }) => {
                pos += 1;
                let right = parse_product(tokens, &mut pos)?;
                left = CalcExpr::Add(Box::new(left), Box::new(right));
            }
            ComponentValue::Token(Token {
                kind: TokenKind::Delim('-'),
                ..
            }) => {
                pos += 1;
                let right = parse_product(tokens, &mut pos)?;
                left = CalcExpr::Sub(Box::new(left), Box::new(right));
            }
            other => {
                return Err(CalcParseError::UnexpectedToken(format!("{:?}", other)));
            }
        }
    }
    Ok(left)
}

fn parse_product<'a>(
    tokens: &[&'a ComponentValue<'a>],
    pos: &mut usize,
) -> Result<CalcExpr, CalcParseError> {
    let mut left = parse_unary(tokens, pos)?;
    while *pos < tokens.len() {
        match tokens[*pos] {
            ComponentValue::Token(Token {
                kind: TokenKind::Delim('*'),
                ..
            }) => {
                *pos += 1;
                let right = parse_unary(tokens, pos)?;
                left = CalcExpr::Mul(Box::new(left), Box::new(right));
            }
            ComponentValue::Token(Token {
                kind: TokenKind::Delim('/'),
                ..
            }) => {
                *pos += 1;
                let right = parse_unary(tokens, pos)?;
                left = CalcExpr::Div(Box::new(left), Box::new(right));
            }
            _ => break,
        }
    }
    Ok(left)
}

fn parse_unary<'a>(
    tokens: &[&'a ComponentValue<'a>],
    pos: &mut usize,
) -> Result<CalcExpr, CalcParseError> {
    if *pos >= tokens.len() {
        return Err(CalcParseError::Empty);
    }
    if let ComponentValue::Token(Token {
        kind: TokenKind::Delim('-'),
        ..
    }) = tokens[*pos]
    {
        *pos += 1;
        let inner = parse_unary(tokens, pos)?;
        return Ok(CalcExpr::Negate(Box::new(inner)));
    }
    if let ComponentValue::Token(Token {
        kind: TokenKind::Delim('+'),
        ..
    }) = tokens[*pos]
    {
        *pos += 1;
        return parse_unary(tokens, pos);
    }
    parse_atom(tokens, pos)
}

fn parse_atom<'a>(
    tokens: &[&'a ComponentValue<'a>],
    pos: &mut usize,
) -> Result<CalcExpr, CalcParseError> {
    let cv = tokens[*pos];
    *pos += 1;
    match cv {
        ComponentValue::Token(t) => match &t.kind {
            TokenKind::Number { value, .. } => Ok(CalcExpr::Value(CalcValue::Number(*value))),
            TokenKind::Percentage { value, .. } => {
                Ok(CalcExpr::Value(CalcValue::Percentage(*value)))
            }
            TokenKind::Dimension { value, unit, .. } => {
                if let Some(u) = parse_length_unit(unit) {
                    Ok(CalcExpr::Value(CalcValue::Length(*value, u)))
                } else if let Some(u) = parse_angle_unit(unit) {
                    Ok(CalcExpr::Value(CalcValue::Angle(*value, u)))
                } else {
                    Err(CalcParseError::InvalidUnit((*unit).to_string()))
                }
            }
            TokenKind::Ident(id) => match id.to_ascii_lowercase().as_str() {
                "pi" => Ok(CalcExpr::Value(CalcValue::Constant(NumericConstant::Pi))),
                "e" => Ok(CalcExpr::Value(CalcValue::Constant(NumericConstant::E))),
                "infinity" => Ok(CalcExpr::Value(CalcValue::Constant(
                    NumericConstant::Infinity,
                ))),
                "-infinity" => Ok(CalcExpr::Value(CalcValue::Constant(
                    NumericConstant::NegInfinity,
                ))),
                "nan" => Ok(CalcExpr::Value(CalcValue::Constant(NumericConstant::NaN))),
                other => Err(CalcParseError::UnexpectedToken(format!("ident `{other}`"))),
            },
            other => Err(CalcParseError::UnexpectedToken(format!("{:?}", other))),
        },
        ComponentValue::SimpleBlock(b) if b.token == '(' => {
            // Parenthesized sub-expression. Recurse on the inner tokens.
            let inner = filter_ws(&b.value);
            parse_sum(&inner)
        }
        ComponentValue::Function(inner_fn) => {
            // Nested math-function call (sin/cos/etc. inside calc()).
            match parse_math_function(inner_fn)? {
                Some(expr) => Ok(expr),
                None => Err(CalcParseError::UnknownFunction(inner_fn.name.to_string())),
            }
        }
        other => Err(CalcParseError::UnexpectedToken(format!("{:?}", other))),
    }
}

fn parse_length_unit(unit: &str) -> Option<LengthUnit> {
    Some(match unit.to_ascii_lowercase().as_str() {
        "px" => LengthUnit::Px,
        "em" => LengthUnit::Em,
        "rem" => LengthUnit::Rem,
        "vw" => LengthUnit::Vw,
        "vh" => LengthUnit::Vh,
        "vmin" => LengthUnit::Vmin,
        "vmax" => LengthUnit::Vmax,
        "cm" => LengthUnit::Cm,
        "mm" => LengthUnit::Mm,
        "in" => LengthUnit::In,
        "pt" => LengthUnit::Pt,
        "pc" => LengthUnit::Pc,
        "ch" => LengthUnit::Ch,
        "ex" => LengthUnit::Ex,
        "cqw" => LengthUnit::Cqw,
        "cqh" => LengthUnit::Cqh,
        _ => return None,
    })
}

fn parse_angle_unit(unit: &str) -> Option<AngleUnit> {
    Some(match unit.to_ascii_lowercase().as_str() {
        "deg" => AngleUnit::Deg,
        "rad" => AngleUnit::Rad,
        "grad" => AngleUnit::Grad,
        "turn" => AngleUnit::Turn,
        _ => return None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::css_values::types::length::CalcContext;

    /// Parse a math expression source (e.g. `"calc(1px + 2px)"`) into a
    /// `CalcExpr` for testing. Wraps it in a synthetic declaration list
    /// so the css_parser entry point accepts it.
    fn parse_calc(src: &str) -> CalcExpr {
        let css = format!("width: {src};");
        let (decls, _errs) = crate::css_parser::parse_declaration_list(&css);
        let decl = decls.first().expect("at least one decl parsed");
        for c in &decl.value {
            if let ComponentValue::Function(f) = c {
                let parsed = parse_math_function(f).expect("parse ok");
                return parsed.expect("math fn recognised");
            }
        }
        panic!("no function in {src}");
    }

    fn approx(a: f64, b: f64) {
        assert!((a - b).abs() < 1e-9, "{a} ≉ {b}");
    }

    #[test]
    fn calc_basic_arithmetic() {
        let ctx = CalcContext::default();
        approx(parse_calc("calc(1 + 2 * 3)").evaluate(&ctx), 7.0);
        approx(parse_calc("calc((1 + 2) * 3)").evaluate(&ctx), 9.0);
        approx(parse_calc("calc(10 - 4 - 1)").evaluate(&ctx), 5.0);
        approx(parse_calc("calc(20 / 4 / 5)").evaluate(&ctx), 1.0);
    }

    #[test]
    fn calc_with_lengths() {
        let ctx = CalcContext::default();
        approx(parse_calc("calc(10px + 5px)").evaluate(&ctx), 15.0);
        approx(parse_calc("calc(2 * 8px)").evaluate(&ctx), 16.0);
    }

    #[test]
    fn min_max_clamp() {
        let ctx = CalcContext::default();
        approx(parse_calc("min(10, 5, 7)").evaluate(&ctx), 5.0);
        approx(parse_calc("max(10, 5, 7)").evaluate(&ctx), 10.0);
        approx(parse_calc("clamp(0, 99, 10)").evaluate(&ctx), 10.0);
        approx(parse_calc("clamp(0, 5, 10)").evaluate(&ctx), 5.0);
    }

    #[test]
    fn trig_functions() {
        let ctx = CalcContext::default();
        approx(parse_calc("cos(0)").evaluate(&ctx), 1.0);
        approx(parse_calc("sin(0)").evaluate(&ctx), 0.0);
        approx(parse_calc("tan(0)").evaluate(&ctx), 0.0);
        approx(parse_calc("sin(pi)").evaluate(&ctx), 0.0); // within tolerance
        approx(parse_calc("cos(pi)").evaluate(&ctx), -1.0);
        approx(
            parse_calc("atan2(1, 1)").evaluate(&ctx),
            std::f64::consts::FRAC_PI_4,
        );
    }

    #[test]
    fn power_log_exp() {
        let ctx = CalcContext::default();
        approx(parse_calc("pow(2, 10)").evaluate(&ctx), 1024.0);
        approx(parse_calc("sqrt(81)").evaluate(&ctx), 9.0);
        approx(parse_calc("hypot(3, 4)").evaluate(&ctx), 5.0);
        approx(parse_calc("hypot(3, 4, 12)").evaluate(&ctx), 13.0);
        approx(parse_calc("log(e)").evaluate(&ctx), 1.0);
        approx(parse_calc("log(100, 10)").evaluate(&ctx), 2.0);
        approx(parse_calc("exp(0)").evaluate(&ctx), 1.0);
    }

    #[test]
    fn round_strategies_via_parser() {
        let ctx = CalcContext::default();
        approx(parse_calc("round(up, 1.1, 1)").evaluate(&ctx), 2.0);
        approx(parse_calc("round(down, 1.9, 1)").evaluate(&ctx), 1.0);
        approx(parse_calc("round(to-zero, -1.9, 1)").evaluate(&ctx), -1.0);
        approx(parse_calc("round(2.5)").evaluate(&ctx), 2.0); // ties-to-even
    }

    #[test]
    #[allow(
        clippy::approx_constant,
        reason = "2.71828 is test input, not std::f64::consts::E"
    )]
    fn nested_calc_with_trig_and_constants() {
        // Nested calc(1px * (<float> * <float> + sin(...))) exercising
        // multiplication, addition, and a trig call inside one expression.
        let ctx = CalcContext::default();
        let v = parse_calc("calc(1px * (2.71828 * 0.5 + sin(pi / 2)))").evaluate(&ctx);
        approx(v, 1.0 * (2.71828 * 0.5 + 1.0));
    }

    #[test]
    fn unary_negation() {
        let ctx = CalcContext::default();
        approx(parse_calc("calc(-5)").evaluate(&ctx), -5.0);
        approx(parse_calc("calc(0 - -5)").evaluate(&ctx), 5.0);
    }

    #[test]
    fn angle_units_in_trig() {
        let ctx = CalcContext::default();
        approx(parse_calc("sin(90deg)").evaluate(&ctx), 1.0);
        approx(parse_calc("cos(180deg)").evaluate(&ctx), -1.0);
        approx(parse_calc("sin(0.25turn)").evaluate(&ctx), 1.0);
    }
}

// =====================================================================
// Top-level entry point used by getComputedStyle resolution: take a
// raw property-value string (as it appears in the cascade), detect
// math functions, evaluate them, and return the resolved string in
// Chrome's serialization format. Used by `op_dom_get_computed_style`.
// =====================================================================

use crate::css_values::types::length::CalcContext;

/// Resolve any top-level math-function call in `value` to a single
/// numeric+unit string (e.g. `"calc(1px * sin(pi/2))"` → `"1px"`).
/// Returns the input unchanged if it doesn't begin with a math function
/// or if parsing fails — preserves backward compatibility with values
/// that don't need resolution.
///
/// This matches Chrome's getComputedStyle behaviour: math functions are
/// resolved to their used pixel value at access time, not echoed back
/// as the original calc tree.
pub fn resolve_computed_value(value: &str, ctx: &CalcContext) -> String {
    let trimmed = value.trim();
    // Cheap rejection — if it doesn't look like a math fn, skip.
    if !looks_like_math_function(trimmed) {
        return value.to_string();
    }
    // Wrap in a synthetic declaration so the css_parser entry point
    // accepts it. We only care about the first ComponentValue.
    let css = format!("__:{};", trimmed);
    let (decls, _errs) = crate::css_parser::parse_declaration_list(&css);
    let Some(decl) = decls.first() else {
        return value.to_string();
    };
    // We only resolve when the value is *exactly* one top-level math
    // function (with optional surrounding whitespace). A value like
    // `pow(2, 5) * 1px` is invalid CSS — Chrome rejects it — so we
    // pass it through unchanged rather than partially evaluating.
    let non_ws: Vec<&ComponentValue<'_>> = decl
        .value
        .iter()
        .filter(|cv| {
            !matches!(
                cv,
                ComponentValue::Token(Token {
                    kind: TokenKind::Whitespace,
                    ..
                })
            )
        })
        .collect();
    if non_ws.len() != 1 {
        return value.to_string();
    }
    if let ComponentValue::Function(f) = non_ws[0] {
        match parse_math_function(f) {
            Ok(Some(expr)) => {
                let v = expr.evaluate(ctx);
                return format_resolved_value(v, trimmed);
            }
            _ => return value.to_string(),
        }
    }
    value.to_string()
}

fn looks_like_math_function(s: &str) -> bool {
    // Top-level fn-call check. Cheap heuristic: starts with one of the
    // math-function names followed by `(`. Avoids paying the parser
    // cost on the 99% of values that are plain dimensions.
    const NAMES: &[&str] = &[
        "calc(", "min(", "max(", "clamp(", "round(", "mod(", "rem(", "sin(", "cos(", "tan(",
        "asin(", "acos(", "atan(", "atan2(", "pow(", "sqrt(", "hypot(", "log(", "exp(", "abs(",
        "sign(",
    ];
    let lower = s.to_ascii_lowercase();
    NAMES.iter().any(|n| lower.starts_with(n))
}

/// Format an evaluated f64 with a unit suffix derived from the input.
/// We pick `"px"` by default since most layout-resolved properties are
/// pixel-typed (Chrome serializes width/margin/etc. as `"NNpx"`).
/// `1px → "1px"`, `1.5px → "1.5px"`, `0 → "0px"`.
fn format_resolved_value(v: f64, original: &str) -> String {
    let unit = guess_output_unit(original);
    if v.fract() == 0.0 && v.is_finite() {
        format!("{}{}", v as i64, unit)
    } else {
        // Match Chrome's truncation to ~6 significant digits.
        let formatted = format!("{:.6}", v);
        // Strip trailing zeros after a decimal point.
        let trimmed = formatted
            .trim_end_matches('0')
            .trim_end_matches('.')
            .to_string();
        format!("{trimmed}{unit}")
    }
}

fn guess_output_unit(original: &str) -> &'static str {
    // Look for any dimension token (number-followed-by-unit) in the
    // source. Substring matching alone is broken — `sin(...)` would
    // match `in` for example. So tokenize via the css_parser and look
    // for a Dimension token; if any present, output is px.
    let css = format!("__:{};", original);
    let (decls, _) = crate::css_parser::parse_declaration_list(&css);
    let Some(decl) = decls.first() else {
        return "";
    };
    fn has_dim(values: &[ComponentValue<'_>]) -> bool {
        for cv in values {
            match cv {
                ComponentValue::Token(Token {
                    kind: TokenKind::Dimension { .. },
                    ..
                }) => {
                    return true;
                }
                ComponentValue::Function(f) if has_dim(&f.arguments) => {
                    return true;
                }
                ComponentValue::SimpleBlock(b) if has_dim(&b.value) => {
                    return true;
                }
                _ => {}
            }
        }
        false
    }
    if has_dim(&decl.value) {
        "px"
    } else {
        ""
    }
}

#[cfg(test)]
mod resolve_tests {
    use super::*;

    fn ctx() -> CalcContext {
        CalcContext::default()
    }

    #[test]
    fn passes_through_plain_values() {
        assert_eq!(resolve_computed_value("12px", &ctx()), "12px");
        assert_eq!(resolve_computed_value("auto", &ctx()), "auto");
        assert_eq!(resolve_computed_value("rgb(0,0,0)", &ctx()), "rgb(0,0,0)");
    }

    #[test]
    fn resolves_basic_calc() {
        assert_eq!(resolve_computed_value("calc(10px + 5px)", &ctx()), "15px");
        assert_eq!(resolve_computed_value("calc(2 * 8px)", &ctx()), "16px");
    }

    #[test]
    fn resolves_math_functions() {
        assert_eq!(resolve_computed_value("min(10px, 5px)", &ctx()), "5px");
        assert_eq!(resolve_computed_value("max(10px, 5px)", &ctx()), "10px");
        // sin(0) → 0 → "0" (no px since input had none)
        assert_eq!(resolve_computed_value("sin(0)", &ctx()), "0");
    }

    #[test]
    fn resolves_challenge_style_nested() {
        // The shape the challenge vendor injects: calc(1px * (...))
        let v = resolve_computed_value("calc(1px * (2.71828 * 0.5 + sin(pi / 2)))", &ctx());
        // 2.71828 * 0.5 + 1 = 2.35914
        // Format with up to 6 decimals, trailing-zeros stripped.
        assert_eq!(v, "2.35914px");
    }

    #[test]
    fn integer_results_serialize_without_decimals() {
        assert_eq!(resolve_computed_value("calc(2px + 3px)", &ctx()), "5px");
        // `pow(2, 5) * 1px` is invalid CSS (math fn followed by extra
        // tokens) — Chrome rejects it. We pass through.
        assert_eq!(
            resolve_computed_value("pow(2, 5) * 1px", &ctx()),
            "pow(2, 5) * 1px"
        );
    }
}