Skip to main content

rust_css_parser/ast/features/
calc.rs

1//! Port of `src/ast/features/calc.ts`.
2
3use super::r#type::FeatureWalkMode;
4use super::{FeatureResult, MinifyFeature, SharedFeature};
5use crate::ast::arena::{is_numeric_token_type, AstArena, TokenField};
6use crate::ast::math::expression::evaluate;
7use crate::ast::minify::MinifyContext;
8use crate::ast::mixins::utils::is_in_template;
9use crate::ast::types::{EnumAstNodeStatus, EnumToken};
10use crate::ast::walk::{ValueWalker, WalkerValueOptions};
11use crate::options::ParserOptions;
12use crate::syntax::constants::{is_function_type, MATH_FUNCS};
13use std::cell::RefCell;
14use crate::utils::fx::HashSet;
15use std::rc::Rc;
16
17pub struct ComputeCalcExpressionFeature;
18
19const ACCEPT: [u8; 2] = [EnumToken::RuleNodeType, EnumToken::AtRuleNodeType];
20
21impl ComputeCalcExpressionFeature {
22    pub fn register(options: &ParserOptions, features: &mut Vec<SharedFeature>) {
23        if options.compute_calc_expression == Some(true) {
24            features.push(Rc::new(RefCell::new(ComputeCalcExpressionFeature)));
25        }
26    }
27}
28
29impl MinifyFeature for ComputeCalcExpressionFeature {
30    fn accept(&self) -> Option<&[u8]> {
31        Some(&ACCEPT)
32    }
33
34    fn ordering(&self) -> i32 {
35        3
36    }
37
38    fn process_mode(&self) -> u32 {
39        FeatureWalkMode::Post
40    }
41
42    fn run(&mut self, arena: &AstArena, ast: u32, _options: &ParserOptions, _parent: u32, _context: &mut MinifyContext, _mode: u32) -> FeatureResult {
43        // the mixin and custom function bodies are templates: the expressions are computed once they are used
44        if arena.flags.get(ast) & EnumAstNodeStatus::HasChildren == 0 || is_in_template(arena, ast) {
45            return FeatureResult::None;
46        }
47        let t = |x: u32| arena.data_types.get(x);
48        let s = |x: u32| arena.resolve_string(arena.string_value.get(x));
49        let mut node = arena.first_child.get(ast);
50        while node != 0 {
51            if t(node) == EnumToken::DeclarationNodeType && has_expression(arena, node) {
52                // function tokens already evaluated, created on demand
53                let mut set: Option<HashSet<u32>> = None;
54                let mut walker = ValueWalker::of_node(arena, node, WalkerValueOptions::default(), false);
55                while let Some(value) = walker.next(arena) {
56                    // the parent of a detached token is the declaration
57                    let parent = match arena.get_value_parent(value) {
58                        0 => node,
59                        p => p,
60                    };
61                    if t(parent) == EnumToken::BinaryExpressionTokenType {
62                        continue;
63                    }
64                    let typ = t(value);
65                    if typ == EnumToken::BinaryExpressionTokenType {
66                        let result = evaluate(arena, &[value]);
67                        if !result.is_empty() {
68                            arena.replace_token(value, &result);
69                        }
70                        continue;
71                    }
72                    if !is_function_type(typ) {
73                        continue;
74                    }
75                    let set = set.get_or_insert_with(HashSet::default);
76                    if !set.insert(value) {
77                        continue;
78                    }
79                    let name = s(value);
80                    let should_evaluate = typ == EnumToken::MathFunctionTokenType || (typ == EnumToken::FunctionTokenType && MATH_FUNCS.contains(&name.as_str()));
81                    if !should_evaluate {
82                        continue;
83                    }
84                    let cp: Vec<u32> = if name != "calc" { vec![value] } else { arena.tokens(value) };
85                    let values = evaluate(arena, &cp);
86                    // fix a + -b into a - b
87                    let mut inner = ValueWalker::of_tokens(&values, WalkerValueOptions::default(), false);
88                    while let Some(v) = inner.next(arena) {
89                        if t(v) == EnumToken::BinaryExpressionTokenType {
90                            let r = if arena.get_child_at(v, TokenField::R).is_none() { 0 } else { arena.field_tokens(v, TokenField::R).first().copied().unwrap_or(0) };
91                            if arena.numeric_value.get(v) as u8 == EnumToken::Add && is_numeric_token_type(t(r)) && arena.numeric_value.get(r) < 0.0 {
92                                arena.numeric_value.set(v, EnumToken::Sub as f64);
93                                arena.numeric_value.set(r, -arena.numeric_value.get(r));
94                            }
95                        }
96                    }
97                    // the value is replaced by the computed tokens or wrapped into a calc() function
98                    if values.len() == 1 && t(values[0]) != EnumToken::BinaryExpressionTokenType {
99                        let parent_type = t(parent);
100                        let v0 = values[0];
101                        let wrap = !(parent_type == EnumToken::MathFunctionTokenType || (parent_type == EnumToken::FunctionTokenType && s(parent) == "calc"))
102                            && (!is_numeric_token_type(t(v0)) || arena.has_fraction(v0))
103                            && !(t(v0) == EnumToken::MathFunctionTokenType || (t(v0) == EnumToken::FunctionTokenType && MATH_FUNCS.contains(&s(v0).as_str())));
104                        let replacement = if wrap { create_calc(arena, value, &values) } else { v0 };
105                        arena.replace_token(value, &[replacement]);
106                    } else {
107                        let calc = create_calc(arena, value, &values);
108                        arena.replace_token(value, &[calc]);
109                    }
110                }
111            }
112            node = arena.next_sibling.get(node);
113        }
114        FeatureResult::None
115    }
116}
117
118/// wrap tokens into a calc() function
119fn create_calc(arena: &AstArena, source: u32, values: &[u32]) -> u32 {
120    let calc = arena.create_function(EnumToken::MathFunctionTokenType, "calc", Some(values));
121    arena.copy_location(calc, source);
122    calc
123}
124
125/// true if a value token of the declaration is a function, an expression or has children
126fn has_expression(arena: &AstArena, node: u32) -> bool {
127    let mut token = arena.first_token.get(node);
128    while token != 0 {
129        let typ = arena.data_types.get(token);
130        if typ == EnumToken::BinaryExpressionTokenType || is_function_type(typ) || arena.first_token.get(token) != 0 || arena.first_child.get(token) != 0 {
131            return true;
132        }
133        token = arena.next_sibling.get(token);
134    }
135    false
136}