Skip to main content

rust_css_parser/ast/mixins/
variables.rs

1//! Port of `src/ast/mixins/variables.ts`: the variables of the mixins and of the custom functions. The var()
2//! functions that reference the private variables (mixin arguments, `@private`, local variables of a custom function,
3//! ...) are replaced by a copy of the variable value (<https://drafts.csswg.org/css-mixins-1/>).
4//!
5//! The scopes are trait objects (`VariableScope`), the variables are shared cells. A variable refers to the scope its
6//! value is resolved in with a weak reference: the scopes own their variables (no reference cycle), the scopes are
7//! alive while their variables are resolved.
8
9use super::custom_function::FunctionRegistry;
10use crate::ast::arena::{AstArena, TokenValue};
11use crate::ast::types::{EnumAstNodeStatus, EnumToken};
12use crate::options::{ConvertColor, ParserOptions};
13use crate::parser::declaration::JsMap;
14use crate::parser::parse::parse_declarations;
15use crate::parser::source::SourceFile;
16use crate::printer::render::render_value;
17use crate::validation::match_::{create_validation_context, match_all_syntaxes, Syntax};
18use crate::validation::parser::parse::parse_syntax;
19use std::cell::RefCell;
20use crate::utils::fx::{HashMap, HashSet};
21use std::rc::{Rc, Weak};
22
23/// a private variable (`VariableEntry`)
24#[derive(Default)]
25pub struct VariableEntry {
26    /// value tokens. `None` when the value is already resolved (see `text`)
27    pub tokens: Option<Vec<u32>>,
28    /// resolved value: `None` when it is not resolved yet (`undefined`), `Some(None)` when the value is invalid
29    pub text: Option<Option<String>>,
30    /// resolved value in the descendants of the element the mixin is applied to
31    pub descendant_text: Option<Option<String>>,
32    /// the value is being resolved: dependency cycle detection
33    pub resolving: bool,
34    /// scope used to resolve the var() functions of the value
35    pub scope: Option<Weak<dyn VariableScope>>,
36}
37
38/// a shared variable
39pub type Entry = Rc<RefCell<VariableEntry>>;
40
41impl VariableEntry {
42    /// a resolved value (`{ tokens: null, text, scope: null }`)
43    pub fn resolved(text: Option<String>) -> Entry {
44        Rc::new(RefCell::new(VariableEntry { text: Some(text), ..Default::default() }))
45    }
46
47    /// a value resolved in a scope (`{ tokens, scope }`)
48    pub fn unresolved(tokens: Vec<u32>, scope: &Rc<dyn VariableScope>) -> Entry {
49        Rc::new(RefCell::new(VariableEntry { tokens: Some(tokens), scope: Some(Rc::downgrade(scope)), ..Default::default() }))
50    }
51}
52
53/// result of [`VariableScope::lookup`]
54pub enum Found {
55    /// the variable entry
56    Entry(Entry),
57    /// a private variable that is not visible (`UNDEFINED`): the fallback of var() is used
58    Undefined,
59    /// not a private variable (`null`): the var() function is evaluated by the browser
60    Null,
61}
62
63/// variables visible from a value
64pub trait VariableScope {
65    /// find a variable. `descendant`: the variable is referenced by a descendant of the element a mixin is applied to
66    fn lookup(&self, name: &str, descendant: bool) -> Found;
67
68    /// the custom function calls are evaluated. `None` when they are not evaluated
69    fn functions(&self) -> Option<Rc<FunctionRegistry>>;
70
71    /// the variables of the call site that are visible from the body of a custom function. the scope itself when `None`
72    fn dynamic(&self) -> Option<Rc<dyn VariableScope>> {
73        None
74    }
75
76    /// the variables visible from the arguments of a custom function call. the scope itself when `None`
77    fn arguments(&self) -> Option<Rc<dyn VariableScope>> {
78        None
79    }
80}
81
82/// custom properties by name
83pub type Properties = Rc<HashMap<String, Entry>>;
84
85/// variables of a style rule: the custom properties declared by the rule
86pub struct RuleScope {
87    pub properties: Properties,
88    pub functions: Option<Rc<FunctionRegistry>>,
89    pub dynamic: Option<Rc<dyn VariableScope>>,
90}
91
92impl RuleScope {
93    pub fn new(properties: Properties, functions: Option<Rc<FunctionRegistry>>, dynamic: Option<Rc<dyn VariableScope>>) -> Rc<dyn VariableScope> {
94        Rc::new(RuleScope { properties, functions, dynamic })
95    }
96}
97
98impl VariableScope for RuleScope {
99    fn lookup(&self, name: &str, _descendant: bool) -> Found {
100        match self.properties.get(name) {
101            Some(entry) => Found::Entry(entry.clone()),
102            None => Found::Null,
103        }
104    }
105
106    fn functions(&self) -> Option<Rc<FunctionRegistry>> {
107        self.functions.clone()
108    }
109
110    fn dynamic(&self) -> Option<Rc<dyn VariableScope>> {
111        self.dynamic.clone()
112    }
113
114    /// the arguments see the variables of the call site
115    fn arguments(&self) -> Option<Rc<dyn VariableScope>> {
116        self.dynamic.clone()
117    }
118}
119
120/// at-rules that may contain mixin and custom function definitions
121pub const SCOPE_RULES: [&str; 6] = ["media", "supports", "container", "layer", "when", "else"];
122
123/// mixin or custom function parameter
124#[derive(Clone, Debug)]
125pub struct Parameter {
126    pub name: String,
127    /// syntax of the parameter type: `<color>`, `<length> | auto`. `None` when the parameter is not typed
128    pub syntax: Option<String>,
129    /// default value tokens
130    pub default_value: Option<Vec<u32>>,
131}
132
133/// true if the token is a whitespace or a comment
134pub fn is_blank(arena: &AstArena, token: u32) -> bool {
135    matches!(arena.data_types.get(token), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType)
136}
137
138pub fn is_comment(arena: &AstArena, token: u32) -> bool {
139    arena.data_types.get(token) == EnumToken::CommentTokenType
140}
141
142/// remove the leading and trailing whitespace and comments
143pub fn trim<'t>(arena: &AstArena, tokens: &'t [u32]) -> &'t [u32] {
144    let mut start = 0;
145    let mut end = tokens.len();
146    while start < end && is_blank(arena, tokens[start]) {
147        start += 1;
148    }
149    while end > start && is_blank(arena, tokens[end - 1]) {
150        end -= 1;
151    }
152    &tokens[start..end]
153}
154
155/// remove the curly braces that wrap a comma containing value: `{a, b}` -> `a, b`
156pub fn unwrap(arena: &AstArena, tokens: &[u32]) -> Vec<u32> {
157    let t = |x: u32| arena.data_types.get(x);
158    // the curly braces of a declaration value: `--fn({a, b})`
159    if tokens.len() == 1 && t(tokens[0]) == EnumToken::WrappedValuesTokenType {
160        return trim(arena, &arena.tokens(tokens[0])).to_vec();
161    }
162    if tokens.len() < 2 || t(tokens[0]) != EnumToken::BlockStartTokenType || t(tokens[tokens.len() - 1]) != EnumToken::BlockEndTokenType {
163        return tokens.to_vec();
164    }
165    let mut depth = 0;
166    for (i, &token) in tokens.iter().enumerate() {
167        if t(token) == EnumToken::BlockStartTokenType {
168            depth += 1;
169        } else if t(token) == EnumToken::BlockEndTokenType {
170            depth -= 1;
171            // the first brace is closed before the end: `{a} b {c}`
172            if depth == 0 && i < tokens.len() - 1 {
173                return tokens.to_vec();
174            }
175        }
176    }
177    trim(arena, &tokens[1..tokens.len() - 1]).to_vec()
178}
179
180/// split a list of tokens on the commas that are not wrapped in curly braces. the comments are ignored
181pub fn split_arguments(arena: &AstArena, tokens: &[u32]) -> Vec<Vec<u32>> {
182    let mut result: Vec<Vec<u32>> = vec![Vec::new()];
183    let mut depth = 0;
184    for &token in tokens {
185        if is_comment(arena, token) {
186            continue;
187        }
188        let typ = arena.data_types.get(token);
189        if typ == EnumToken::BlockStartTokenType {
190            depth += 1;
191        } else if typ == EnumToken::BlockEndTokenType && depth > 0 {
192            depth -= 1;
193        } else if typ == EnumToken::CommaTokenType && depth == 0 {
194            result.push(Vec::new());
195            continue;
196        }
197        result.last_mut().unwrap().push(token);
198    }
199    result.into_iter().map(|part| trim(arena, &part).to_vec()).collect()
200}
201
202/// first token that is not a whitespace or a comment
203pub fn first_token(arena: &AstArena, tokens: &[u32]) -> Option<u32> {
204    tokens.iter().copied().find(|&t| !is_blank(arena, t))
205}
206
207/// true if the token is a var() function
208pub fn is_var(arena: &AstArena, token: u32) -> bool {
209    arena.data_types.get(token) == EnumToken::WildCardFunctionTokenType && arena.string_equals_ignore_case(arena.string_value.get(token), "var")
210}
211
212/// true if a token or one of its descendants is a var() function, or a custom function call when `functions` is set
213pub fn has_reference(arena: &AstArena, token: u32, functions: bool) -> bool {
214    if is_var(arena, token) || (functions && arena.data_types.get(token) == EnumToken::CustomFunctionTokenType) {
215        return true;
216    }
217    if arena.first_token.get(token) == 0 && arena.first_child.get(token) == 0 {
218        return false;
219    }
220    arena.sub_tokens(token).into_iter().any(|child| has_reference(arena, child, functions))
221}
222
223thread_local! {
224    /// render options of the tokens: the values are parsed again, the colors are not converted
225    static RENDER_OPTIONS: ParserOptions = ParserOptions { convert_color: Some(ConvertColor::Bool(false)), ..Default::default() };
226}
227
228/// render tokens
229pub fn render(arena: &AstArena, tokens: &[u32]) -> String {
230    RENDER_OPTIONS.with(|options| {
231        let mut result = String::new();
232        for &token in tokens {
233            result.push_str(&render_value(arena, token, options));
234        }
235        result
236    })
237}
238
239/// render tokens, the var() functions that reference a private variable replaced by a copy of the variable value, the
240/// custom function calls replaced by their result when the scope evaluates them. `None` when a variable is invalid
241/// and var() has no fallback: the value is not valid
242pub fn substitute(arena: &AstArena, tokens: &[u32], scope: &Rc<dyn VariableScope>, descendant: bool) -> Option<String> {
243    let functions = scope.functions().is_some();
244    if !tokens.iter().any(|&t| has_reference(arena, t, functions)) {
245        return Some(render(arena, tokens));
246    }
247    // the copies of the tokens are modified: the var() functions are replaced by their value
248    let copies: Vec<u32> = tokens.iter().map(|&t| arena.clone_node_deep(t, true, None)).collect();
249    let list = arena.create_list(EnumToken::ListToken, Some(&copies));
250    if !replace_variables(arena, list, scope, descendant) {
251        return None;
252    }
253    Some(render(arena, &arena.tokens(list)))
254}
255
256/// replace the var() functions that reference a private variable with literal tokens holding the value. false when
257/// the value is not valid
258pub fn replace_variables(arena: &AstArena, parent: u32, scope: &Rc<dyn VariableScope>, descendant: bool) -> bool {
259    let literal = |value: &str| arena.create_token(EnumToken::LiteralTokenType, TokenValue::Str(value), None);
260    for token in arena.sub_tokens(parent) {
261        if is_var(arena, token) {
262            match substitute_variable(arena, token, scope, descendant) {
263                Substituted::Invalid => return false,
264                Substituted::Value(value) => arena.replace_token(token, &[literal(&value)]),
265                Substituted::Unchanged => {}
266            }
267        } else if let (Some(functions), EnumToken::CustomFunctionTokenType) = (scope.functions(), arena.data_types.get(token)) {
268            // custom function call: `--fn(1px)`
269            match functions.call(arena, token, scope, descendant) {
270                Substituted::Invalid => return false,
271                Substituted::Value(value) => arena.replace_token(token, &[literal(&value)]),
272                // the call is not evaluated: its arguments may reference variables
273                Substituted::Unchanged => {
274                    if !replace_variables(arena, token, scope, descendant) {
275                        return false;
276                    }
277                }
278            }
279        } else if (arena.first_token.get(token) != 0 || arena.first_child.get(token) != 0) && !replace_variables(arena, token, scope, descendant) {
280            return false;
281        }
282    }
283    true
284}
285
286/// value of a var() function or of a custom function call
287pub enum Substituted {
288    /// the value that replaces the function
289    Value(String),
290    /// `undefined`: the function is not modified
291    Unchanged,
292    /// `null`: the value is invalid
293    Invalid,
294}
295
296impl From<Option<String>> for Substituted {
297    fn from(value: Option<String>) -> Self {
298        match value {
299            Some(v) => Substituted::Value(v),
300            None => Substituted::Invalid,
301        }
302    }
303}
304
305/// value of a var() function
306pub fn substitute_variable(arena: &AstArena, token: u32, scope: &Rc<dyn VariableScope>, descendant: bool) -> Substituted {
307    let children = arena.tokens(token);
308    let Some(name_token) = first_token(arena, &children).filter(|&n| arena.data_types.get(n) == EnumToken::DashedIdenTokenType) else {
309        return Substituted::Unchanged;
310    };
311    let name = arena.resolve_string(arena.string_value.get(name_token));
312    let fallback: Option<&[u32]> = children
313        .iter()
314        .position(|&c| arena.data_types.get(c) == EnumToken::CommaTokenType)
315        .map(|comma| trim(arena, &children[comma + 1..]));
316    match scope.lookup(&name, descendant) {
317        Found::Null => {
318            // not a private variable: the fallback may reference private variables `var(--color, var(--private))`
319            if let Some(fallback) = fallback {
320                let functions = scope.functions().is_some();
321                if fallback.iter().any(|&c| has_reference(arena, c, functions)) {
322                    // an invalid fallback is equivalent to no fallback
323                    return Substituted::Value(match substitute(arena, fallback, scope, descendant) {
324                        None => format!("var({})", name),
325                        Some(value) => format!("var({},{})", name, value),
326                    });
327                }
328            }
329            Substituted::Unchanged
330        }
331        found => {
332            if let Found::Entry(entry) = found {
333                if let Some(value) = resolve(arena, &entry, descendant) {
334                    return Substituted::Value(value);
335                }
336            }
337            // the variable is not defined or is invalid
338            match fallback {
339                None => Substituted::Invalid,
340                Some(fallback) => substitute(arena, fallback, scope, descendant).into(),
341            }
342        }
343    }
344}
345
346/// resolved value of a variable. `None` when the value is invalid
347pub fn resolve(arena: &AstArena, entry: &Entry, descendant: bool) -> Option<String> {
348    let (tokens, scope) = {
349        let e = entry.borrow();
350        match (&e.tokens, e.scope.as_ref().and_then(|s| s.upgrade())) {
351            // the value is already resolved: the custom properties of the rule, the arguments
352            (None, _) | (_, None) => return e.text.clone().flatten(),
353            (Some(tokens), Some(scope)) => {
354                let cached = if descendant { &e.descendant_text } else { &e.text };
355                if let Some(value) = cached {
356                    return value.clone();
357                }
358                // dependency cycle
359                if e.resolving {
360                    return None;
361                }
362                (tokens.clone(), scope)
363            }
364        }
365    };
366    entry.borrow_mut().resolving = true;
367    let value = substitute(arena, &tokens, &scope, descendant);
368    let mut e = entry.borrow_mut();
369    e.resolving = false;
370    if descendant {
371        e.descendant_text = Some(value.clone());
372    } else {
373        e.text = Some(value.clone());
374    }
375    value
376}
377
378/// value tokens of a declaration, without `!important`
379pub fn declaration_value(arena: &AstArena, declaration: u32) -> Vec<u32> {
380    let all = arena.tokens(declaration);
381    let tokens = trim(arena, &all);
382    if tokens.last().is_some_and(|&l| arena.data_types.get(l) == EnumToken::ImportantTokenType) {
383        return trim(arena, &tokens[..tokens.len() - 1]).to_vec();
384    }
385    tokens.to_vec()
386}
387
388/// true if the node is an at-rule with the given name
389pub fn is_at_rule(arena: &AstArena, node: u32, name: &str) -> bool {
390    arena.data_types.get(node) == EnumToken::AtRuleNodeType && arena.string_equals(arena.name.get(node), name)
391}
392
393/// true if the node is an at-rule with a block that may contain mixin definitions
394pub fn is_scope_rule(arena: &AstArena, node: u32) -> bool {
395    arena.data_types.get(node) == EnumToken::AtRuleNodeType
396        && arena.flags.get(node) & EnumAstNodeStatus::HasChildren != 0
397        && SCOPE_RULES.iter().any(|name| arena.string_equals(arena.name.get(node), name))
398}
399
400/// true if the node is a custom property declaration
401pub fn is_custom_property(arena: &AstArena, node: u32) -> bool {
402    arena.data_types.get(node) == EnumToken::DeclarationNodeType && arena.string_starts_with(arena.name.get(node), "--")
403}
404
405/// custom properties declared by the children of a node: the `!important` declarations override the other
406/// declarations, the last declaration wins. the declarations of the inner nodes override the outer nodes
407pub fn collect_properties(arena: &AstArena, node: u32, result: &mut HashMap<String, Entry>) {
408    let mut important: HashSet<String> = HashSet::default();
409    let mut properties: JsMap<Entry> = JsMap::new();
410    let mut child = arena.first_child.get(node);
411    while child != 0 {
412        if is_custom_property(arena, child) {
413            let name = arena.resolve_string(arena.name.get(child)).to_string();
414            let is_important = arena.flags.get(child) & EnumAstNodeStatus::ImportantDeclaration != 0;
415            if !(important.contains(&name) && !is_important) {
416                if is_important {
417                    important.insert(name.clone());
418                }
419                properties.set(name, VariableEntry::resolved(Some(render(arena, &declaration_value(arena, child)))));
420            }
421        }
422        child = arena.next_sibling.get(child);
423    }
424    for (name, entry) in properties.iter() {
425        result.entry(name.to_string()).or_insert_with(|| entry.clone());
426    }
427}
428
429/// syntax of a parameter type: `<color>` -> `<color>`, `type(<length> | auto)` -> `<length> | auto`. `None` when the
430/// parameter is not typed or accepts any value
431pub fn parameter_syntax(arena: &AstArena, tokens: &[u32]) -> Option<String> {
432    let filtered: Vec<u32> = tokens.iter().copied().filter(|&t| !is_comment(arena, t)).collect();
433    let typ = trim(arena, &filtered);
434    if typ.is_empty() {
435        return None;
436    }
437    let syntax = if typ.len() == 1 && arena.data_types.get(typ[0]) == EnumToken::FunctionTokenType && arena.string_equals_ignore_case(arena.string_value.get(typ[0]), "type") {
438        render(arena, trim(arena, &arena.tokens(typ[0]))).trim().to_string()
439    } else {
440        render(arena, typ).trim().to_string()
441    };
442    if syntax.is_empty() || syntax == "*" {
443        None
444    } else {
445        Some(syntax)
446    }
447}
448
449/// the values that are resolved by the browser: `/(^|[^\w-])(var|env|...)\(/i`
450fn is_unresolved_value(value: &str) -> bool {
451    const NAMES: [&str; 28] = [
452        "var", "env", "attr", "if", "calc", "min", "max", "clamp", "round", "mod", "rem", "sin", "cos", "tan", "asin", "acos", "atan", "atan2", "pow", "sqrt",
453        "hypot", "log", "exp", "abs", "sign", "calc-size", "progress", "random",
454    ];
455    let lower = value.to_ascii_lowercase();
456    let bytes = lower.as_bytes();
457    NAMES.iter().any(|name| {
458        let pattern = format!("{}(", name);
459        lower.match_indices(&pattern).any(|(at, _)| at == 0 || !(bytes[at - 1].is_ascii_alphanumeric() || bytes[at - 1] == b'_' || bytes[at - 1] == b'-'))
460    })
461}
462
463thread_local! {
464    /// parsed syntaxes of the parameter types
465    static SYNTAXES: RefCell<HashMap<String, Option<Rc<Vec<Syntax>>>>> = RefCell::new(HashMap::default());
466}
467
468/// parse a syntax: `None` when it is not supported (the typescript parser throws)
469fn parse_type_syntax(syntax: &str) -> Option<Rc<Vec<Syntax>>> {
470    let previous = std::panic::take_hook();
471    std::panic::set_hook(Box::new(|_| {}));
472    let parsed = std::panic::catch_unwind(|| parse_syntax(syntax)).ok();
473    std::panic::set_hook(previous);
474    parsed.filter(|p| !p.is_empty()).map(Rc::new)
475}
476
477/// true if a value matches the type of a parameter. a value that is resolved by the browser is not checked
478pub fn matches_type(arena: &AstArena, syntax: Option<&str>, value: &str, options: &ParserOptions) -> bool {
479    let Some(syntax) = syntax else {
480        return true;
481    };
482    if is_unresolved_value(value) {
483        return true;
484    }
485    let parsed = SYNTAXES.with(|s| s.borrow_mut().entry(syntax.to_string()).or_insert_with(|| parse_type_syntax(syntax)).clone());
486    let Some(parsed) = parsed else {
487        return true;
488    };
489    // the value is parsed as a declaration value: the math functions are parsed into expressions
490    let (_, nodes) = parse_declarations(&format!("--value:{}", value), Some(arena.rc()));
491    let Some(declaration) = nodes.into_iter().find(|&n| arena.data_types.get(n) == EnumToken::DeclarationNodeType) else {
492        return false;
493    };
494    let tokens = arena.tokens(declaration);
495    thread_local! {
496        /// source of the validation errors of the parameter types
497        static VALIDATION_SOURCE: Rc<SourceFile> = SourceFile::new(Rc::from(""), Vec::new(), Some(Rc::from("")));
498    }
499    let options = ParserOptions { source: Some(VALIDATION_SOURCE.with(|s| s.clone())), ..options.clone() };
500    match_all_syntaxes(arena, Some(&parsed), &create_validation_context(arena, &tokens), &options).success
501}
502
503/// custom properties of the rule the `@apply` rule belongs to: the declarations of the nearest style rule and of the
504/// at-rules between them. `None` when the `@apply` rule is not inside a style rule
505pub fn rule_properties(arena: &AstArena, node: u32) -> Option<HashMap<String, Entry>> {
506    let mut result: HashMap<String, Entry> = HashMap::default();
507    let mut parent = arena.parents.get(node);
508    while parent != 0 {
509        match arena.data_types.get(parent) {
510            EnumToken::AtRuleNodeType => collect_properties(arena, parent, &mut result),
511            EnumToken::RuleNodeType => {
512                collect_properties(arena, parent, &mut result);
513                return Some(result);
514            }
515            _ => return None,
516        }
517        parent = arena.parents.get(parent);
518    }
519    None
520}
521
522/// parse the parameters of a mixin or a custom function: `--name(--a, --b <color>: red)`. `None` when the parameters
523/// are not valid
524pub fn parse_parameters(arena: &AstArena, reference: u32) -> Option<Vec<Parameter>> {
525    let mut parameters: Vec<Parameter> = Vec::new();
526    let all = arena.tokens(reference);
527    let children = trim(arena, &all);
528    if children.iter().all(|&t| is_blank(arena, t)) {
529        return Some(parameters);
530    }
531    let mut list = split_arguments(arena, children);
532    // trailing comma: `@mixin --name(--a, --b,)`
533    if list.len() > 1 && list.last().unwrap().is_empty() {
534        list.pop();
535    }
536    for parameter in list {
537        if parameter.is_empty() || arena.data_types.get(parameter[0]) != EnumToken::DashedIdenTokenType {
538            return None;
539        }
540        // <dashed-ident> <css-type>? [ : <default-value> ]?
541        let colon = parameter.iter().position(|&t| arena.data_types.get(t) == EnumToken::ColonTokenType);
542        let name = arena.resolve_string(arena.string_value.get(parameter[0])).to_string();
543        // the parameters are unique
544        if parameters.iter().any(|p| p.name == name) {
545            return None;
546        }
547        let end = colon.unwrap_or(parameter.len());
548        parameters.push(Parameter {
549            name,
550            syntax: parameter_syntax(arena, &parameter[1..end]),
551            default_value: colon.map(|c| unwrap(arena, trim(arena, &parameter[c + 1..]))),
552        });
553    }
554    Some(parameters)
555}
556
557/// arguments of a mixin or a custom function call: the comments and the whitespace are ignored, the curly braces are
558/// removed
559pub fn parse_arguments(arena: &AstArena, reference: u32) -> Vec<Vec<u32>> {
560    let children = arena.tokens(reference);
561    if children.iter().all(|&t| is_blank(arena, t)) {
562        return Vec::new();
563    }
564    split_arguments(arena, &children).iter().map(|arg| unwrap(arena, arg)).collect()
565}
566
567/// a definition located in the tree
568pub trait Definition {
569    fn node(&self) -> u32;
570}
571
572/// the definitions visible from a reference: the definitions of the innermost scope that defines the name
573pub fn resolve_definitions<T: Definition + Clone>(arena: &AstArena, definitions: Option<&Vec<T>>, site: u32) -> Vec<T> {
574    let Some(definitions) = definitions.filter(|d| !d.is_empty()) else {
575        return Vec::new();
576    };
577    let mut scope = arena.parents.get(site);
578    while scope != 0 {
579        let result: Vec<T> = definitions.iter().filter(|d| arena.parents.get(d.node()) == scope).cloned().collect();
580        if !result.is_empty() {
581            return result;
582        }
583        scope = arena.parents.get(scope);
584    }
585    Vec::new()
586}
587
588/// name of a mixin or a custom function definition: `@mixin --name(...)`, `@function --name(...)`
589pub fn definition_name(arena: &AstArena, node: u32) -> Option<String> {
590    first_token(arena, &arena.tokens(node)).map(|r| arena.resolve_string(arena.string_value.get(r)).to_string())
591}
592
593/// collect the mixin or custom function definitions of a stylesheet, a conditional group rule or a cascade layer.
594/// the definitions that are not valid are collected in `invalid`
595pub fn collect_definitions<T>(arena: &AstArena, node: u32, name: &str, parse: &dyn Fn(&AstArena, u32) -> Option<T>, definitions: &mut JsMap<Vec<T>>, invalid: &mut Vec<u32>) {
596    let mut child = arena.first_child.get(node);
597    while child != 0 {
598        if is_at_rule(arena, child, name) {
599            let key = definition_name(arena, child);
600            match key.and_then(|k| parse(arena, child).map(|d| (k, d))) {
601                None => invalid.push(child),
602                Some((key, definition)) => match definitions.get_mut(&key) {
603                    Some(list) => list.push(definition),
604                    None => definitions.set(key, vec![definition]),
605                },
606            }
607        } else if is_scope_rule(arena, child) {
608            collect_definitions(arena, child, name, parse, definitions, invalid);
609        }
610        child = arena.next_sibling.get(child);
611    }
612}
613
614/// the mixin or custom function at-rules of a stylesheet
615pub fn collect_at_rules(arena: &AstArena, node: u32, name: &str, result: &mut Vec<u32>) {
616    let mut child = arena.first_child.get(node);
617    while child != 0 {
618        if is_at_rule(arena, child, name) {
619            result.push(child);
620        } else if is_scope_rule(arena, child) {
621            collect_at_rules(arena, child, name, result);
622        }
623        child = arena.next_sibling.get(child);
624    }
625}
626
627/// the prelude of a definition in its comment: the comments are removed (`/\/\*[\s\S]*?\*\//g`), the whitespace after
628/// `(` (`/\(\s+/g`) and before `)` and `,` (`/\s+([),])/g`) too
629fn comment_prelude(prelude: &str) -> String {
630    let mut without_comments = String::with_capacity(prelude.len());
631    let mut rest = prelude;
632    while let Some(start) = rest.find("/*") {
633        match rest[start + 2..].find("*/") {
634            Some(end) => {
635                without_comments.push_str(&rest[..start]);
636                rest = &rest[start + 2 + end + 2..];
637            }
638            None => break,
639        }
640    }
641    without_comments.push_str(rest);
642    let chars: Vec<char> = without_comments.chars().collect();
643    let mut result = String::with_capacity(chars.len());
644    let mut i = 0;
645    while i < chars.len() {
646        let c = chars[i];
647        if c == '(' {
648            result.push(c);
649            i += 1;
650            while i < chars.len() && chars[i].is_whitespace() {
651                i += 1;
652            }
653            continue;
654        }
655        if c.is_whitespace() {
656            let mut j = i;
657            while j < chars.len() && chars[j].is_whitespace() {
658                j += 1;
659            }
660            if j < chars.len() && (chars[j] == ')' || chars[j] == ',') {
661                i = j;
662                continue;
663            }
664        }
665        result.push(c);
666        i += 1;
667    }
668    result.trim().to_string()
669}
670
671/// finalize the mixin or custom function definitions once they are evaluated: the evaluated definitions are replaced
672/// with a comment unless `keep` is set, the definitions that are kept are reduced to their last definition in the same
673/// scope, the definitions that are not valid are left as is
674pub fn finalize_definitions(arena: &AstArena, ast: u32, name: &str, kept: &HashSet<u32>, keep: bool, invalid: &[u32]) {
675    // the last definition in the same scope
676    let mut last: HashMap<u32, HashMap<String, u32>> = HashMap::default();
677    let mut nodes = Vec::new();
678    collect_at_rules(arena, ast, name, &mut nodes);
679    for node in nodes {
680        let Some(key) = definition_name(arena, node) else {
681            continue;
682        };
683        if invalid.contains(&node) {
684            continue;
685        }
686        if !kept.contains(&node) {
687            if !keep {
688                // the comments of the prelude are removed: the comments are not nested
689                let text = format!("/* @{} {} */", name, comment_prelude(&arena.resolve_string(arena.string_value.get(node))));
690                let comment = arena.create_comment(EnumToken::CommentTokenType, crate::ast::arena::StrOrId::Str(&text));
691                arena.copy_location(comment, node);
692                arena.replace_child(node, &[comment]);
693            }
694            continue;
695        }
696        let scope = last.entry(arena.parents.get(node)).or_default();
697        // the definition is defined only once in the same scope: the last definition wins
698        if let Some(previous) = scope.insert(key, node) {
699            arena.detach(previous);
700        }
701    }
702}