Skip to main content

rust_css_parser/ast/mixins/
custom_function.rs

1//! Port of `src/ast/mixins/custom-function.ts`: a custom function call (`<dashed-function>`) is replaced by the
2//! result of the function, like var() is replaced by the value of a custom property
3//! (<https://drafts.csswg.org/css-mixins-1/#defining-custom-functions>).
4//!
5//! The registry is shared by the scopes (`Rc`): its counters and sets are interior mutable.
6
7use super::variables::{
8    declaration_value, first_token, has_reference, is_at_rule, is_custom_property, matches_type, parameter_syntax, parse_arguments, parse_parameters,
9    resolve, resolve_definitions, rule_properties, substitute, Definition, Entry, Found, Parameter, RuleScope, Substituted, VariableEntry,
10    VariableScope,
11};
12use crate::ast::arena::AstArena;
13use crate::ast::types::{EnumAstNodeStatus, EnumToken};
14use crate::options::ParserOptions;
15use crate::parser::declaration::JsMap;
16use crate::parser::parse::parse_declarations;
17use std::cell::{Cell, RefCell};
18use crate::utils::fx::{HashMap, HashSet};
19use std::rc::{Rc, Weak};
20
21/// maximum number of nested custom function calls
22const MAX_DEPTH: usize = 32;
23
24/// custom function definition
25#[derive(Clone)]
26pub struct FunctionDefinition {
27    pub node: u32,
28    pub name: String,
29    pub parameters: Vec<Parameter>,
30    /// syntax of the return type: `returns <length>`. `None` when the result is not typed
31    pub returns: Option<String>,
32    /// the function body contains conditional rules: the function is not evaluated
33    pub conditional_body: bool,
34    /// local variables: the custom properties declared in the function body. the last declaration wins
35    pub locals: Rc<JsMap<Vec<u32>>>,
36    /// result tokens: the last `result` descriptor. `None` when the function has no result
37    pub result: Option<Vec<u32>>,
38}
39
40impl Definition for FunctionDefinition {
41    fn node(&self) -> u32 {
42        self.node
43    }
44}
45
46/// variables visible from the body of a custom function
47struct FunctionScope {
48    locals: RefCell<HashMap<String, Entry>>,
49    args: RefCell<HashMap<String, Entry>>,
50    /// scope of the call: the calling function, or the element
51    parent: Rc<dyn VariableScope>,
52    functions: Rc<FunctionRegistry>,
53}
54
55impl VariableScope for FunctionScope {
56    fn lookup(&self, name: &str, descendant: bool) -> Found {
57        let found = self.locals.borrow().get(name).cloned().or_else(|| self.args.borrow().get(name).cloned());
58        if let Some(entry) = found {
59            return Found::Entry(entry);
60        }
61        self.parent.lookup(name, descendant)
62    }
63
64    fn functions(&self) -> Option<Rc<FunctionRegistry>> {
65        Some(self.functions.clone())
66    }
67}
68
69/// parse a custom function definition. `None` if the prelude is not valid
70///
71/// ```css
72/// @function --name(--a <length>: 1px) returns <length> { result: calc(2 * var(--a)) }
73/// ```
74pub fn parse_function(arena: &AstArena, node: u32) -> Option<FunctionDefinition> {
75    let tokens = arena.tokens(node);
76    let reference = first_token(arena, &tokens).filter(|&r| arena.data_types.get(r) == EnumToken::CustomFunctionTokenType)?;
77    let parameters = parse_parameters(arena, reference)?;
78    // [ returns <css-type> ]?
79    let returns = tokens
80        .iter()
81        .position(|&t| arena.data_types.get(t) == EnumToken::IdenTokenType && arena.string_equals_ignore_case(arena.string_value.get(t), "returns"))
82        .and_then(|index| parameter_syntax(arena, &tokens[index + 1..]));
83    let mut definition = FunctionDefinition {
84        node,
85        name: arena.resolve_string(arena.string_value.get(reference)).to_string(),
86        parameters,
87        returns,
88        conditional_body: false,
89        locals: Rc::new(JsMap::new()),
90        result: None,
91    };
92    let mut locals: JsMap<Vec<u32>> = JsMap::new();
93    let mut child = arena.first_child.get(node);
94    while child != 0 {
95        if arena.data_types.get(child) == EnumToken::AtRuleNodeType {
96            definition.conditional_body = true;
97        } else if is_custom_property(arena, child) {
98            locals.set(arena.resolve_string(arena.name.get(child)).to_string(), declaration_value(arena, child));
99        } else if arena.data_types.get(child) == EnumToken::DeclarationNodeType && arena.string_equals(arena.name.get(child), "result") {
100            definition.result = Some(declaration_value(arena, child));
101        }
102        child = arena.next_sibling.get(child);
103    }
104    definition.locals = Rc::new(locals);
105    Some(definition)
106}
107
108/// local variable of a custom function. `initial`: the value of the parameter with the same name; `inherit` /
109/// `unset`: the value of the variable with the same name in the calling context
110fn local_variable(
111    arena: &AstArena,
112    name: &str,
113    tokens: &[u32],
114    values: &HashMap<String, Entry>,
115    context: &Rc<dyn VariableScope>,
116    scope: &Rc<dyn VariableScope>,
117    descendant: bool,
118) -> Entry {
119    if tokens.len() == 1 && arena.data_types.get(tokens[0]) == EnumToken::IdenTokenType {
120        let value = arena.string_value.get(tokens[0]);
121        if arena.string_equals_ignore_case(value, "initial") {
122            return values.get(name).cloned().unwrap_or_else(|| VariableEntry::resolved(None));
123        }
124        if arena.string_equals_ignore_case(value, "inherit") || arena.string_equals_ignore_case(value, "unset") {
125            return match context.lookup(name, descendant) {
126                Found::Undefined => VariableEntry::resolved(None),
127                Found::Entry(entry) => entry,
128                Found::Null => VariableEntry::resolved(Some(format!("var({})", name))),
129            };
130        }
131    }
132    VariableEntry::unresolved(tokens.to_vec(), scope)
133}
134
135/// evaluates the custom function calls (`FunctionRegistry`)
136pub struct FunctionRegistry {
137    /// the function definitions that have been evaluated
138    pub evaluated: RefCell<HashSet<u32>>,
139    /// the function definitions referenced by the calls that have not been evaluated: they are kept
140    pub pending: RefCell<HashSet<u32>>,
141    /// number of evaluated calls
142    pub count: Cell<usize>,
143    /// number of calls that are not evaluated
144    pub failed: Cell<usize>,
145    /// the calls are located in a custom property declaration
146    pub custom_property: Cell<bool>,
147    /// location of the calls: the declaration or the `@apply` rule that contains them
148    pub site: Cell<u32>,
149    /// functions being evaluated
150    stack: RefCell<Vec<String>>,
151    /// the functions that call themselves, directly or through other functions
152    recursive: RefCell<HashMap<String, bool>>,
153    /// function definitions by name, in document order
154    pub definitions: JsMap<Vec<FunctionDefinition>>,
155    options: ParserOptions,
156    this: Weak<FunctionRegistry>,
157}
158
159impl FunctionRegistry {
160    pub fn new(definitions: JsMap<Vec<FunctionDefinition>>, options: &ParserOptions) -> Rc<Self> {
161        Rc::new_cyclic(|this| FunctionRegistry {
162            evaluated: RefCell::new(HashSet::default()),
163            pending: RefCell::new(HashSet::default()),
164            count: Cell::new(0),
165            failed: Cell::new(0),
166            custom_property: Cell::new(false),
167            site: Cell::new(0),
168            stack: RefCell::new(Vec::new()),
169            recursive: RefCell::new(HashMap::default()),
170            definitions,
171            options: options.clone(),
172            this: this.clone(),
173        })
174    }
175
176    /// result of a custom function call: the result that replaces the call, `Unchanged` when the call is not evaluated
177    pub fn call(&self, arena: &AstArena, token: u32, caller: &Rc<dyn VariableScope>, descendant: bool) -> Substituted {
178        let name = arena.resolve_string(arena.string_value.get(token));
179        // the function is not defined in the stylesheet
180        let Some(all) = self.definitions.get(&name) else {
181            return Substituted::Unchanged;
182        };
183        // the functions visible from the call
184        let definitions = resolve_definitions(arena, Some(all), self.site.get());
185        let definition = if definitions.len() == 1 { Some(&definitions[0]) } else { None };
186        let unusable = match definition {
187            None => true,
188            Some(d) => {
189                d.conditional_body
190                    || self.stack.borrow().len() >= MAX_DEPTH
191                    || self.is_recursive(arena, &name, &mut Vec::new())
192                    || (self.custom_property.get() && (d.returns.is_some() || d.parameters.iter().any(|p| p.syntax.is_some())))
193            }
194        };
195        if unusable {
196            // the visible definitions are kept
197            for visible in &definitions {
198                self.pending.borrow_mut().insert(visible.node);
199            }
200            self.failed.set(self.failed.get() + 1);
201            return Substituted::Unchanged;
202        }
203        let definition = definition.unwrap();
204        let failed = self.failed.get();
205        let mut result = self.evaluate(arena, definition, token, caller, descendant);
206        // a call of the function body is not evaluated: the function is not evaluated
207        if result.is_some() && self.failed.get() != failed {
208            result = None;
209        }
210        match result {
211            None => {
212                self.pending.borrow_mut().insert(definition.node);
213                self.failed.set(self.failed.get() + 1);
214                Substituted::Unchanged
215            }
216            Some(result) => {
217                self.evaluated.borrow_mut().insert(definition.node);
218                self.count.set(self.count.get() + 1);
219                Substituted::Value(result)
220            }
221        }
222    }
223
224    /// evaluate a call. `None` when the arguments do not match the parameters or the result is not valid
225    fn evaluate(&self, arena: &AstArena, definition: &FunctionDefinition, token: u32, caller: &Rc<dyn VariableScope>, descendant: bool) -> Option<String> {
226        let args = parse_arguments(arena, token);
227        if args.len() > definition.parameters.len() {
228            return None;
229        }
230        // the variables of the call site: the custom properties of the rule, or the variables of the calling function
231        let context: Rc<dyn VariableScope> = caller.dynamic().unwrap_or_else(|| caller.clone());
232        let argument_scope: Rc<dyn VariableScope> = caller.arguments().unwrap_or_else(|| caller.clone());
233        let function_scope = Rc::new(FunctionScope {
234            locals: RefCell::new(HashMap::default()),
235            args: RefCell::new(HashMap::default()),
236            parent: context.clone(),
237            functions: self.this.upgrade().expect("registry"),
238        });
239        let scope: Rc<dyn VariableScope> = function_scope.clone();
240        for (index, parameter) in definition.parameters.iter().enumerate() {
241            let entry = if index < args.len() {
242                // the arguments are evaluated in the scope of the call
243                VariableEntry::resolved(Some(substitute(arena, &args[index], &argument_scope, descendant)?))
244            } else if let Some(default) = &parameter.default_value {
245                VariableEntry::unresolved(default.clone(), &scope)
246            } else {
247                return None;
248            };
249            function_scope.args.borrow_mut().insert(parameter.name.clone(), entry);
250        }
251        for (name, tokens) in definition.locals.iter() {
252            let values = function_scope.args.borrow().clone();
253            let entry = local_variable(arena, name, tokens, &values, &context, &scope, descendant);
254            function_scope.locals.borrow_mut().insert(name.to_string(), entry);
255        }
256        self.stack.borrow_mut().push(definition.name.clone());
257        let result = (|| {
258            for parameter in &definition.parameters {
259                let entry = function_scope.args.borrow().get(&parameter.name).cloned()?;
260                let value = resolve(arena, &entry, descendant)?;
261                if !matches_type(arena, parameter.syntax.as_deref(), &value, &self.options) {
262                    return None;
263                }
264            }
265            // no result: guaranteed-invalid value. the call is left as is
266            let tokens = definition.result.as_ref()?;
267            let result = substitute(arena, tokens, &scope, descendant)?;
268            // a result that does not match the return type: the call is left as is
269            if !matches_type(arena, definition.returns.as_deref(), &result, &self.options) {
270                return None;
271            }
272            Some(result)
273        })();
274        self.stack.borrow_mut().pop();
275        result
276    }
277
278    /// true if a function calls itself, directly or through the functions it calls
279    fn is_recursive(&self, arena: &AstArena, name: &str, stack: &mut Vec<String>) -> bool {
280        if stack.iter().any(|s| s == name) {
281            return true;
282        }
283        if let Some(&result) = self.recursive.borrow().get(name) {
284            return result;
285        }
286        let mut result = false;
287        stack.push(name.to_string());
288        'definitions: for definition in self.definitions.get(name).map(|d| d.as_slice()).unwrap_or(&[]) {
289            let mut values: Vec<&Vec<u32>> = definition.locals.values().collect();
290            if let Some(result) = &definition.result {
291                values.push(result);
292            }
293            for parameter in &definition.parameters {
294                if let Some(default) = &parameter.default_value {
295                    values.push(default);
296                }
297            }
298            for tokens in values {
299                for call in find_calls(arena, tokens) {
300                    let callee = arena.resolve_string(arena.string_value.get(call));
301                    if self.definitions.has(&callee) && self.is_recursive(arena, &callee, stack) {
302                        result = true;
303                        break 'definitions;
304                    }
305                }
306            }
307        }
308        stack.pop();
309        // a function that reaches one of the functions being checked is part of a cycle
310        self.recursive.borrow_mut().insert(name.to_string(), result);
311        result
312    }
313}
314
315/// the custom function calls of a list of tokens and their descendants
316pub fn find_calls(arena: &AstArena, tokens: &[u32]) -> Vec<u32> {
317    let mut result = Vec::new();
318    find_calls_into(arena, tokens, &mut result);
319    result
320}
321
322fn find_calls_into(arena: &AstArena, tokens: &[u32], result: &mut Vec<u32>) {
323    for &token in tokens {
324        if arena.data_types.get(token) == EnumToken::CustomFunctionTokenType {
325            result.push(token);
326        }
327        if arena.first_token.get(token) != 0 || arena.first_child.get(token) != 0 {
328            find_calls_into(arena, &arena.sub_tokens(token), result);
329        }
330    }
331}
332
333/// replace the custom function calls of the declarations of a stylesheet with their result. the bodies of the mixins
334/// and of the custom functions are evaluated when they are used
335pub fn evaluate_functions(arena: &AstArena, ast: u32, registry: &Rc<FunctionRegistry>) {
336    let mut stack: Vec<u32> = Vec::new();
337    let mut child = arena.last_child.get(ast);
338    while child != 0 {
339        stack.push(child);
340        child = arena.previous_sibling.get(child);
341    }
342    while let Some(node) = stack.pop() {
343        if is_at_rule(arena, node, "mixin") || is_at_rule(arena, node, "function") {
344            continue;
345        }
346        if arena.data_types.get(node) == EnumToken::DeclarationNodeType {
347            evaluate_declaration(arena, node, registry);
348            continue;
349        }
350        if arena.flags.get(node) & EnumAstNodeStatus::HasChildren != 0 {
351            let mut child = arena.last_child.get(node);
352            while child != 0 {
353                stack.push(child);
354                child = arena.previous_sibling.get(child);
355            }
356        }
357    }
358}
359
360/// replace the custom function calls of a declaration with their result
361fn evaluate_declaration(arena: &AstArena, declaration: u32, registry: &Rc<FunctionRegistry>) {
362    let tokens = arena.tokens(declaration);
363    if !tokens.iter().any(|&t| has_reference(arena, t, true)) {
364        return;
365    }
366    // the var() functions of the declaration are not modified. the custom functions see the custom properties of the
367    // rule: the call site
368    let dynamic = RuleScope::new(Rc::new(rule_properties(arena, declaration).unwrap_or_default()), Some(registry.clone()), None);
369    let scope = RuleScope::new(Rc::new(HashMap::default()), Some(registry.clone()), Some(dynamic));
370    let count = registry.count.get();
371    let failed = registry.failed.get();
372    registry.custom_property.set(is_custom_property(arena, declaration));
373    registry.site.set(declaration);
374    let value = substitute(arena, &tokens, &scope, false);
375    // no call has been evaluated, a call is not evaluated or the value is not valid: the declaration is left as is
376    let Some(value) = value.filter(|_| registry.count.get() != count && registry.failed.get() == failed) else {
377        return;
378    };
379    let css = format!("{}:{}", arena.resolve_string(arena.name.get(declaration)), value);
380    let (_, nodes) = parse_declarations(&css, Some(arena.rc()));
381    let nodes: Vec<u32> = nodes.into_iter().filter(|&n| arena.data_types.get(n) == EnumToken::DeclarationNodeType).collect();
382    if nodes.len() == 1 {
383        arena.copy_location(nodes[0], declaration);
384        arena.replace_child(declaration, &[nodes[0]]);
385    }
386}