Skip to main content

strata_style/
calc.rs

1//! CSS calc() mathematical expression tree, tokenizer, parser, and evaluator.
2//!
3//! Evaluates complex mixed-unit expressions (e.g. `calc(100% - 24px + 2rem)`)
4//! with strict arithmetic operator precedence and contextual dimension resolution.
5
6use super::types::Dimension;
7use std::sync::{Arc, RwLock};
8
9/// Identifier for an interned calc expression AST.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub struct CalcId(pub u32);
12
13const MAX_CALC_ENTRIES: usize = 8192;
14
15struct CalcInternerState {
16    entries: Vec<Arc<CalcExpr>>,
17    index: std::collections::HashMap<u64, Vec<u32>>,
18}
19
20impl CalcInternerState {
21    fn new() -> Self {
22        Self {
23            entries: Vec::new(),
24            index: std::collections::HashMap::new(),
25        }
26    }
27}
28
29static CALC_INTERNER: std::sync::LazyLock<RwLock<CalcInternerState>> =
30    std::sync::LazyLock::new(|| RwLock::new(CalcInternerState::new()));
31
32#[inline]
33fn feed_hash(h: &mut u64, v: u64) {
34    *h ^= v;
35    *h = h.wrapping_mul(0x100000001b3);
36}
37
38fn hash_dimension_bits(dim: &Dimension, h: &mut u64) {
39    match *dim {
40        Dimension::Auto => feed_hash(h, 0),
41        Dimension::Px(v) => {
42            feed_hash(h, 1);
43            feed_hash(h, v.to_bits() as u64);
44        }
45        Dimension::Percent(v) => {
46            feed_hash(h, 2);
47            feed_hash(h, v.to_bits() as u64);
48        }
49        Dimension::Vw(v) => {
50            feed_hash(h, 3);
51            feed_hash(h, v.to_bits() as u64);
52        }
53        Dimension::Vh(v) => {
54            feed_hash(h, 4);
55            feed_hash(h, v.to_bits() as u64);
56        }
57        Dimension::Rem(v) => {
58            feed_hash(h, 5);
59            feed_hash(h, v.to_bits() as u64);
60        }
61        Dimension::Em(v) => {
62            feed_hash(h, 6);
63            feed_hash(h, v.to_bits() as u64);
64        }
65        Dimension::Calc(id) => {
66            feed_hash(h, 7);
67            feed_hash(h, id.0 as u64);
68        }
69        Dimension::MinContent => feed_hash(h, 8),
70        Dimension::MaxContent => feed_hash(h, 9),
71        Dimension::FitContent(v) => {
72            feed_hash(h, 10);
73            feed_hash(h, v.to_bits() as u64);
74        }
75    }
76}
77
78fn hash_calc_expr_bits(expr: &CalcExpr, h: &mut u64) {
79    match expr {
80        CalcExpr::Value(dim) => {
81            feed_hash(h, 100);
82            hash_dimension_bits(dim, h);
83        }
84        CalcExpr::Add(l, r) => {
85            feed_hash(h, 101);
86            hash_calc_expr_bits(l, h);
87            hash_calc_expr_bits(r, h);
88        }
89        CalcExpr::Sub(l, r) => {
90            feed_hash(h, 102);
91            hash_calc_expr_bits(l, h);
92            hash_calc_expr_bits(r, h);
93        }
94        CalcExpr::Mul(l, s) => {
95            feed_hash(h, 103);
96            hash_calc_expr_bits(l, h);
97            feed_hash(h, s.to_bits() as u64);
98        }
99        CalcExpr::Div(l, s) => {
100            feed_hash(h, 104);
101            hash_calc_expr_bits(l, h);
102            feed_hash(h, s.to_bits() as u64);
103        }
104    }
105}
106
107fn compute_expr_hash(expr: &CalcExpr) -> u64 {
108    let mut h = 0xcbf29ce484222325u64;
109    hash_calc_expr_bits(expr, &mut h);
110    h
111}
112
113/// Interns a calc expression AST into the global cache and returns its lightweight CalcId.
114/// Automatically deduplicates identical expressions and bounds capacity to prevent memory leaks.
115pub fn intern_calc(expr: CalcExpr) -> CalcId {
116    let hash = compute_expr_hash(&expr);
117
118    // Fast path: check for existing interned expression under read lock
119    {
120        let state = CALC_INTERNER.read().unwrap();
121        if let Some(candidates) = state.index.get(&hash) {
122            for &id in candidates {
123                if let Some(existing) = state.entries.get(id as usize) {
124                    if **existing == expr {
125                        return CalcId(id);
126                    }
127                }
128            }
129        }
130    }
131
132    // Slow path: acquire write lock to insert
133    let mut state = CALC_INTERNER.write().unwrap();
134    if let Some(candidates) = state.index.get(&hash) {
135        for &id in candidates {
136            if let Some(existing) = state.entries.get(id as usize) {
137                if **existing == expr {
138                    return CalcId(id);
139                }
140            }
141        }
142    }
143
144    if state.entries.len() >= MAX_CALC_ENTRIES {
145        // Enforce hard bound to avoid unbounded memory leak under dynamic DoS
146        return CalcId(0);
147    }
148
149    let id = state.entries.len() as u32;
150    state.entries.push(Arc::new(expr));
151    state.index.entry(hash).or_default().push(id);
152    CalcId(id)
153}
154
155/// Retrieves an interned calc expression AST by its CalcId.
156pub fn get_calc(id: CalcId) -> Option<Arc<CalcExpr>> {
157    let state = CALC_INTERNER.read().unwrap();
158    state.entries.get(id.0 as usize).cloned()
159}
160
161/// Contextual environment for resolving relative CSS units inside a calc() expression.
162#[derive(Debug, Clone, Copy, PartialEq)]
163pub struct CalcContext {
164    /// Resolved parent container dimension in CSS pixels (for resolving percentages).
165    pub parent_size: f32,
166    /// Root font size in CSS pixels (for resolving `rem`, default 16.0).
167    pub root_font_size: f32,
168    /// Current element font size in CSS pixels (for resolving `em`, default 16.0).
169    pub current_font_size: f32,
170    /// Viewport width in CSS pixels (for resolving `vw`).
171    pub viewport_width: f32,
172    /// Viewport height in CSS pixels (for resolving `vh`).
173    pub viewport_height: f32,
174}
175
176impl Default for CalcContext {
177    fn default() -> Self {
178        Self {
179            parent_size: 1000.0,
180            root_font_size: 16.0,
181            current_font_size: 16.0,
182            viewport_width: 1920.0,
183            viewport_height: 1080.0,
184        }
185    }
186}
187
188/// Recursive AST representation of a CSS calc() expression.
189#[derive(Debug, Clone, PartialEq)]
190pub enum CalcExpr {
191    /// Concrete or relative dimension value (e.g. `24px`, `50%`, `1.5rem`).
192    Value(Dimension),
193    /// Addition: `Left + Right`.
194    Add(Box<CalcExpr>, Box<CalcExpr>),
195    /// Subtraction: `Left - Right`.
196    Sub(Box<CalcExpr>, Box<CalcExpr>),
197    /// Multiplication by a scalar: `Expr * Scalar`.
198    Mul(Box<CalcExpr>, f32),
199    /// Division by a scalar: `Expr / Scalar`.
200    Div(Box<CalcExpr>, f32),
201}
202
203impl CalcExpr {
204    /// Evaluates the expression AST to concrete CSS pixels given a context.
205    pub fn eval(&self, ctx: &CalcContext) -> f32 {
206        let raw = match self {
207            CalcExpr::Value(dim) => match *dim {
208                Dimension::Auto => 0.0,
209                Dimension::Px(px) => px,
210                Dimension::Percent(pct) => ctx.parent_size * (pct / 100.0),
211                Dimension::Rem(rem) => rem * ctx.root_font_size,
212                Dimension::Em(em) => em * ctx.current_font_size,
213                Dimension::Vw(vw) => ctx.viewport_width * (vw / 100.0),
214                Dimension::Vh(vh) => ctx.viewport_height * (vh / 100.0),
215                Dimension::Calc(id) => get_calc(id).map(|inner| inner.eval(ctx)).unwrap_or(0.0),
216                Dimension::MinContent | Dimension::MaxContent | Dimension::FitContent(_) => 0.0,
217            },
218            CalcExpr::Add(left, right) => left.eval(ctx) + right.eval(ctx),
219            CalcExpr::Sub(left, right) => left.eval(ctx) - right.eval(ctx),
220            CalcExpr::Mul(left, scalar) => {
221                if scalar.is_finite() {
222                    left.eval(ctx) * scalar
223                } else {
224                    0.0
225                }
226            }
227            CalcExpr::Div(left, scalar) => {
228                if scalar.is_finite() && *scalar != 0.0 {
229                    left.eval(ctx) / scalar
230                } else {
231                    0.0
232                }
233            }
234        };
235
236        if raw.is_finite() {
237            raw
238        } else {
239            0.0
240        }
241    }
242
243    /// Convenience constructor for px value.
244    pub fn px(val: f32) -> Self {
245        CalcExpr::Value(Dimension::Px(val))
246    }
247
248    /// Convenience constructor for percentage value.
249    pub fn percent(val: f32) -> Self {
250        CalcExpr::Value(Dimension::Percent(val))
251    }
252
253    /// Convenience constructor for rem value.
254    pub fn rem(val: f32) -> Self {
255        CalcExpr::Value(Dimension::Rem(val))
256    }
257}
258
259/// Tokenizer token for calc() expressions.
260#[derive(Debug, Clone, PartialEq)]
261enum Token {
262    Dim(Dimension),
263    Number(f32),
264    Plus,
265    Minus,
266    Star,
267    Slash,
268    LParen,
269    RParen,
270}
271
272/// Maximum recursion depth allowed during calc() parsing to prevent stack overflow crashes.
273pub const MAX_CALC_DEPTH: usize = 32;
274
275/// Parses a CSS calc(...) expression string into a `CalcExpr` AST.
276pub fn parse_calc(input: &str) -> Result<CalcExpr, String> {
277    let clean = input.trim();
278    let inner = if clean.starts_with("calc(") && clean.ends_with(')') {
279        &clean[5..clean.len() - 1]
280    } else {
281        clean
282    };
283
284    let tokens = tokenize_calc(inner)?;
285    let mut cursor = TokenCursor::new(tokens);
286    let expr = parse_add_sub(&mut cursor, 0)?;
287
288    if !cursor.is_eof() {
289        return Err(format!(
290            "Unexpected tokens remaining in calc(): {:?}",
291            cursor.peek()
292        ));
293    }
294
295    Ok(expr)
296}
297
298struct TokenCursor {
299    tokens: Vec<Token>,
300    pos: usize,
301}
302
303impl TokenCursor {
304    fn new(tokens: Vec<Token>) -> Self {
305        Self { tokens, pos: 0 }
306    }
307
308    fn peek(&self) -> Option<&Token> {
309        self.tokens.get(self.pos)
310    }
311
312    fn next(&mut self) -> Option<Token> {
313        if self.pos < self.tokens.len() {
314            let t = self.tokens[self.pos].clone();
315            self.pos += 1;
316            Some(t)
317        } else {
318            None
319        }
320    }
321
322    fn is_eof(&self) -> bool {
323        self.pos >= self.tokens.len()
324    }
325}
326
327fn tokenize_calc(s: &str) -> Result<Vec<Token>, String> {
328    let mut tokens = Vec::new();
329    let bytes = s.as_bytes();
330    let mut i = 0;
331
332    while i < bytes.len() {
333        let b = bytes[i];
334        if b.is_ascii_whitespace() {
335            i += 1;
336            continue;
337        }
338
339        match b {
340            b'+' => {
341                tokens.push(Token::Plus);
342                i += 1;
343            }
344            b'-' => {
345                // Distinguish between binary minus and negative number
346                tokens.push(Token::Minus);
347                i += 1;
348            }
349            b'*' => {
350                tokens.push(Token::Star);
351                i += 1;
352            }
353            b'/' => {
354                tokens.push(Token::Slash);
355                i += 1;
356            }
357            b'(' => {
358                tokens.push(Token::LParen);
359                i += 1;
360            }
361            b')' => {
362                tokens.push(Token::RParen);
363                i += 1;
364            }
365            _ if b.is_ascii_digit() || b == b'.' => {
366                let start = i;
367                while i < bytes.len()
368                    && (bytes[i].is_ascii_digit()
369                        || bytes[i] == b'.'
370                        || bytes[i].is_ascii_alphabetic()
371                        || bytes[i] == b'%')
372                {
373                    i += 1;
374                }
375                let raw = &s[start..i];
376                if let Some(dim) = parse_dimension_token(raw) {
377                    tokens.push(Token::Dim(dim));
378                } else if let Ok(num) = raw.parse::<f32>() {
379                    tokens.push(Token::Number(num));
380                } else {
381                    return Err(format!("Unrecognized calc token: '{}'", raw));
382                }
383            }
384            _ => {
385                i += 1;
386            }
387        }
388    }
389
390    Ok(tokens)
391}
392
393fn parse_dimension_token(raw: &str) -> Option<Dimension> {
394    let parse_num = |s: &str| -> Option<f32> {
395        let n = s.parse::<f32>().ok()?;
396        if n.is_finite() {
397            Some(n)
398        } else {
399            None
400        }
401    };
402
403    if let Some(stripped) = raw.strip_suffix("px") {
404        parse_num(stripped).map(Dimension::Px)
405    } else if let Some(stripped) = raw.strip_suffix('%') {
406        parse_num(stripped).map(Dimension::Percent)
407    } else if let Some(stripped) = raw.strip_suffix("rem") {
408        parse_num(stripped).map(Dimension::Rem)
409    } else if let Some(stripped) = raw.strip_suffix("em") {
410        parse_num(stripped).map(Dimension::Em)
411    } else if let Some(stripped) = raw.strip_suffix("vw") {
412        parse_num(stripped).map(Dimension::Vw)
413    } else if let Some(stripped) = raw.strip_suffix("vh") {
414        parse_num(stripped).map(Dimension::Vh)
415    } else {
416        None
417    }
418}
419
420// Precedence Level 1: Add (+) and Sub (-)
421fn parse_add_sub(cursor: &mut TokenCursor, depth: usize) -> Result<CalcExpr, String> {
422    if depth > MAX_CALC_DEPTH {
423        return Err(format!(
424            "Maximum calc() expression nesting depth ({MAX_CALC_DEPTH}) exceeded"
425        ));
426    }
427    let mut left = parse_mul_div(cursor, depth)?;
428
429    while let Some(tok) = cursor.peek() {
430        match tok {
431            Token::Plus => {
432                cursor.next();
433                let right = parse_mul_div(cursor, depth)?;
434                left = CalcExpr::Add(Box::new(left), Box::new(right));
435            }
436            Token::Minus => {
437                cursor.next();
438                let right = parse_mul_div(cursor, depth)?;
439                left = CalcExpr::Sub(Box::new(left), Box::new(right));
440            }
441            _ => break,
442        }
443    }
444
445    Ok(left)
446}
447
448// Precedence Level 2: Mul (*) and Div (/)
449fn parse_mul_div(cursor: &mut TokenCursor, depth: usize) -> Result<CalcExpr, String> {
450    if depth > MAX_CALC_DEPTH {
451        return Err(format!(
452            "Maximum calc() expression nesting depth ({MAX_CALC_DEPTH}) exceeded"
453        ));
454    }
455    let mut left = parse_factor(cursor, depth)?;
456
457    while let Some(tok) = cursor.peek() {
458        match tok {
459            Token::Star => {
460                cursor.next();
461                match cursor.next() {
462                    Some(Token::Number(scalar)) => {
463                        if !scalar.is_finite() {
464                            return Err(format!(
465                                "Non-finite scalar multiplier in calc(): {scalar}"
466                            ));
467                        }
468                        left = CalcExpr::Mul(Box::new(left), scalar);
469                    }
470                    other => {
471                        return Err(format!(
472                            "Expected scalar number after '*', found {:?}",
473                            other
474                        ))
475                    }
476                }
477            }
478            Token::Slash => {
479                cursor.next();
480                match cursor.next() {
481                    Some(Token::Number(scalar)) => {
482                        if !scalar.is_finite() || scalar == 0.0 {
483                            return Err(format!(
484                                "Division by zero or non-finite scalar in calc(): {scalar}"
485                            ));
486                        }
487                        left = CalcExpr::Div(Box::new(left), scalar);
488                    }
489                    other => {
490                        return Err(format!(
491                            "Expected scalar number after '/', found {:?}",
492                            other
493                        ))
494                    }
495                }
496            }
497            _ => break,
498        }
499    }
500
501    Ok(left)
502}
503
504// Precedence Level 3: Atoms, Parentheses, Values
505fn parse_factor(cursor: &mut TokenCursor, depth: usize) -> Result<CalcExpr, String> {
506    if depth > MAX_CALC_DEPTH {
507        return Err(format!(
508            "Maximum calc() expression nesting depth ({MAX_CALC_DEPTH}) exceeded"
509        ));
510    }
511    match cursor.next() {
512        Some(Token::Dim(dim)) => Ok(CalcExpr::Value(dim)),
513        Some(Token::Number(num)) => {
514            if !num.is_finite() {
515                return Err(format!("Non-finite number in calc(): {num}"));
516            }
517            Ok(CalcExpr::Value(Dimension::Px(num)))
518        }
519        Some(Token::LParen) => {
520            let inner = parse_add_sub(cursor, depth + 1)?;
521            match cursor.next() {
522                Some(Token::RParen) => Ok(inner),
523                other => Err(format!("Expected ')', found {:?}", other)),
524            }
525        }
526        other => Err(format!("Unexpected token in calc() factor: {:?}", other)),
527    }
528}