Skip to main content

rust_css_parser/ast/features/
mixin.rs

1//! Port of `src/ast/features/mixin.ts`: the `@apply` rules are replaced by the body of the mixin they reference,
2//! the custom function calls by the result of the function (<https://drafts.csswg.org/css-mixins-1/#mixin-rule>).
3
4use super::r#type::FeatureWalkMode;
5use super::{FeatureResult, MinifyFeature, SharedFeature};
6use crate::ast::arena::{AstArena, StrOrId, TokenValue};
7use crate::ast::minify::{split_rule, MinifyContext};
8use crate::ast::mixins::custom_function::{evaluate_functions, find_calls, parse_function, FunctionRegistry};
9use crate::ast::mixins::variables::{
10    collect_definitions, declaration_value, finalize_definitions, first_token, is_at_rule, is_custom_property, matches_type, parse_arguments,
11    parse_parameters, render, resolve, resolve_definitions, rule_properties, split_arguments, substitute, trim, Definition, Entry, Found, Parameter,
12    RuleScope, VariableEntry, VariableScope,
13};
14use crate::ast::types::{EnumAstNodeStatus, EnumToken};
15use crate::options::ParserOptions;
16use crate::parser::declaration::JsMap;
17use crate::parser::parse::{parse_declarations, parse_rule_content};
18use std::cell::{Cell, RefCell};
19use crate::utils::fx::{HashMap, HashSet};
20use std::rc::Rc;
21
22/// the subject of the rule is the element the mixin is applied to: `&`, `&.active`, `&::before`
23const SELF: u8 = 0;
24/// the subject of the rule is a descendant of the element the mixin is applied to: `& *`, `& > *`, `.child`
25const DESCENDANT: u8 = 1;
26/// the subject of the rule is not in the subtree of the element the mixin is applied to: `& + *`, `& ~ *`
27const OUTSIDE: u8 = 2;
28/// maximum number of nested `@apply` rules
29const MAX_DEPTH: usize = 32;
30
31/// private variables by name, shared by the levels of the nested scopes
32type Privates = Rc<RefCell<HashMap<String, Entry>>>;
33
34/// variables declared by a rule of the mixin body (or by the mixin body itself)
35#[derive(Clone)]
36struct ScopeLevel {
37    /// custom properties declared with `@private`
38    privates: Privates,
39    /// relation of the subject of the current rule to the subject of the rule that declares the variables
40    relation: u8,
41}
42
43/// mixin definition
44#[derive(Clone)]
45struct MixinDefinition {
46    node: u32,
47    parameters: Vec<Parameter>,
48}
49
50impl Definition for MixinDefinition {
51    fn node(&self) -> u32 {
52        self.node
53    }
54}
55
56/// evaluation state
57struct EvaluationState {
58    /// valid mixin definitions by name, in document order
59    definitions: JsMap<Vec<MixinDefinition>>,
60    /// the mixins that are not valid: they are ignored and left as is
61    invalid: Vec<u32>,
62    /// the mixin definitions referenced by the `@apply` rules that have not been evaluated: they are kept
63    pending: HashSet<u32>,
64    /// mixins being applied, for each `@apply` rule generated by a mixin: recursion detection
65    chains: HashMap<u32, Vec<String>>,
66    /// the mixins that apply themselves, directly or through other mixins
67    recursive: HashMap<String, bool>,
68    ast: u32,
69    registry: Rc<FunctionRegistry>,
70    /// names of the custom properties of the stylesheet: the names of the registered custom properties are unique
71    names: Rc<RefCell<HashSet<String>>>,
72    options: ParserOptions,
73}
74
75/// typed argument: its value is computed on the element the mixin is applied to (`TypedArgument`)
76struct TypedArgument {
77    value: String,
78    syntax: String,
79    /// variable that references the registered custom property
80    entry: Option<Entry>,
81}
82
83/// registered custom property of a typed argument
84struct RegisteredProperty {
85    name: String,
86    syntax: String,
87    initial_value: String,
88    value: String,
89}
90
91/// application of a mixin: the variables shared by the scopes of the mixin body
92struct MixinApplication {
93    name: String,
94    /// mixin arguments and default values
95    args: RefCell<HashMap<String, Entry>>,
96    /// the typed arguments that depend on the element the mixin is applied to
97    typed: RefCell<HashMap<String, TypedArgument>>,
98    /// registered custom properties of the typed arguments
99    registered: RefCell<Vec<RegisteredProperty>>,
100    /// the mixin cannot be evaluated: a typed argument cannot be registered
101    failed: Cell<bool>,
102    /// the variables visible from the bodies of the custom functions called by the mixin body
103    dynamic: Rc<dyn VariableScope>,
104    /// custom properties declared in the rule the mixin is applied to
105    properties: Rc<HashMap<String, Entry>>,
106    /// serialized contents block of the `@apply` rule
107    contents: Option<String>,
108    names: Option<Rc<RefCell<HashSet<String>>>>,
109    registry: Option<Rc<FunctionRegistry>>,
110}
111
112impl MixinApplication {
113    fn new(
114        name: &str,
115        properties: Rc<HashMap<String, Entry>>,
116        contents: Option<String>,
117        names: Option<Rc<RefCell<HashSet<String>>>>,
118        registry: Option<Rc<FunctionRegistry>>,
119    ) -> Rc<Self> {
120        Rc::new(MixinApplication {
121            name: name.to_string(),
122            args: RefCell::new(HashMap::default()),
123            typed: RefCell::new(HashMap::default()),
124            registered: RefCell::new(Vec::new()),
125            failed: Cell::new(false),
126            dynamic: RuleScope::new(properties.clone(), registry.clone(), None),
127            properties,
128            contents,
129            names,
130            registry,
131        })
132    }
133
134    /// variable that references the registered custom property of a typed argument. `None` when the argument cannot
135    /// be registered
136    fn typed_entry(&self, name: &str) -> Option<Entry> {
137        let mut typed = self.typed.borrow_mut();
138        let argument = typed.get_mut(name)?;
139        if argument.entry.is_none() {
140            let initial_value = initial_value_of(&argument.syntax);
141            let (Some(initial_value), Some(names)) = (initial_value, self.names.as_ref()) else {
142                self.failed.set(true);
143                return None;
144            };
145            let prefix = format!("--{}-{}-", &self.name[2..], &name[2..]);
146            let mut index = 1;
147            while names.borrow().contains(&format!("{}{}", prefix, index)) {
148                index += 1;
149            }
150            let property = format!("{}{}", prefix, index);
151            let text = format!("var({})", property);
152            let entry = Rc::new(RefCell::new(VariableEntry { text: Some(Some(text.clone())), descendant_text: Some(Some(text)), ..Default::default() }));
153            argument.entry = Some(entry);
154            names.borrow_mut().insert(property.clone());
155            self.registered.borrow_mut().push(RegisteredProperty { name: property, syntax: argument.syntax.clone(), initial_value, value: argument.value.clone() });
156        }
157        argument.entry.clone()
158    }
159}
160
161/// variables visible from a node of a mixin body
162struct MixinScope {
163    /// variables declared by the mixin body and the rules that contain the current node, outer first
164    levels: Vec<ScopeLevel>,
165    application: Rc<MixinApplication>,
166    /// custom properties declared in the mixin body: they override the rule custom properties
167    masked: Rc<HashSet<String>>,
168}
169
170impl MixinScope {
171    fn new(levels: Vec<ScopeLevel>, application: Rc<MixinApplication>, masked: Rc<HashSet<String>>) -> Rc<Self> {
172        Rc::new(MixinScope { levels, application, masked })
173    }
174
175    /// the subject of the current rule is a descendant of the element the mixin is applied to
176    fn descendant(&self) -> bool {
177        self.levels[0].relation == DESCENDANT
178    }
179
180    /// scope of a nested rule
181    fn child(&self, relation: u8, masked: &HashSet<String>) -> Rc<MixinScope> {
182        let mut levels: Vec<ScopeLevel> =
183            self.levels.iter().map(|level| ScopeLevel { privates: level.privates.clone(), relation: compose(level.relation, relation) }).collect();
184        levels.push(ScopeLevel { privates: Privates::default(), relation: SELF });
185        let masked = if masked.is_empty() { self.masked.clone() } else { Rc::new(self.masked.iter().chain(masked.iter()).cloned().collect()) };
186        MixinScope::new(levels, self.application.clone(), masked)
187    }
188}
189
190impl VariableScope for MixinScope {
191    fn lookup(&self, name: &str, descendant: bool) -> Found {
192        // the inner declarations override the outer declarations
193        for level in self.levels[1..].iter().rev() {
194            if let Some(entry) = level.privates.borrow().get(name) {
195                return Found::Entry(entry.clone());
196            }
197        }
198        // the private variables of the mixin body are not visible from the siblings of the element
199        let visible = self.levels[0].relation != OUTSIDE;
200        let private = self.levels[0].privates.borrow().get(name).cloned();
201        if let (Some(entry), true) = (&private, visible) {
202            return Found::Entry(entry.clone());
203        }
204        let application = &self.application;
205        let arg = application.args.borrow().get(name).cloned();
206        if let Some(arg) = arg {
207            if !visible {
208                return Found::Undefined;
209            }
210            // the descendants inherit the value computed on the element
211            if descendant && application.typed.borrow().contains_key(name) {
212                return Found::Entry(application.typed_entry(name).unwrap_or(arg));
213            }
214            return Found::Entry(arg);
215        }
216        if private.is_some() {
217            return Found::Undefined;
218        }
219        // the custom properties of the rule the mixin is applied to. the descendants inherit them
220        if visible && !self.masked.contains(name) {
221            if let Some(entry) = application.properties.get(name) {
222                return Found::Entry(entry.clone());
223            }
224        }
225        Found::Null
226    }
227
228    fn functions(&self) -> Option<Rc<FunctionRegistry>> {
229        self.application.registry.clone()
230    }
231
232    /// the custom functions see the custom properties of the rule, not the private variables
233    fn dynamic(&self) -> Option<Rc<dyn VariableScope>> {
234        Some(self.application.dynamic.clone())
235    }
236}
237
238fn as_scope(scope: &Rc<MixinScope>) -> Rc<dyn VariableScope> {
239    scope.clone()
240}
241
242/// initial value of a registered custom property: a computationally independent value that matches the syntax
243fn initial_value_of(syntax: &str) -> Option<String> {
244    let defaults = |name: &str| -> Option<&'static str> {
245        Some(match name {
246            "length" | "length-percentage" => "0px",
247            "percentage" => "0%",
248            "number" | "integer" => "0",
249            "angle" => "0deg",
250            "time" => "0s",
251            "resolution" => "1dppx",
252            "color" => "transparent",
253            "custom-ident" => "none",
254            "string" => "\"\"",
255            "transform-function" | "transform-list" => "scale(1)",
256            _ => return None,
257        })
258    };
259    for component in syntax.split('|') {
260        // `/^(?:<([a-z-]+)>|([a-z][a-z0-9-]*))[+#]?$/i`
261        let component = component.trim();
262        let body = component.strip_suffix(['+', '#']).unwrap_or(component);
263        if let Some(name) = body.strip_prefix('<').and_then(|b| b.strip_suffix('>')) {
264            if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphabetic() || b == b'-') {
265                return None;
266            }
267            if let Some(value) = defaults(&name.to_lowercase()) {
268                return Some(value.to_string());
269            }
270        } else {
271            let mut chars = body.bytes();
272            let valid = chars.next().is_some_and(|b| b.is_ascii_alphabetic()) && chars.all(|b| b.is_ascii_alphanumeric() || b == b'-');
273            if !valid {
274                return None;
275            }
276            return Some(body.to_string());
277        }
278    }
279    None
280}
281
282/// relation of the subject of a nested rule to the subject of an outer rule
283fn compose(outer: u8, relation: u8) -> u8 {
284    if outer == SELF {
285        relation
286    } else {
287        outer
288    }
289}
290
291/// names of the custom properties declared by a mixin body or a rule (the nested at-rules included, `@private` and the
292/// nested rules excluded)
293fn collect_masked(arena: &AstArena, node: u32, result: &mut HashSet<String>) {
294    let mut child = arena.first_child.get(node);
295    while child != 0 {
296        if is_custom_property(arena, child) {
297            result.insert(arena.resolve_string(arena.name.get(child)).to_string());
298        } else if arena.data_types.get(child) == EnumToken::AtRuleNodeType
299            && arena.flags.get(child) & EnumAstNodeStatus::HasChildren != 0
300            && !is_at_rule(arena, child, "private")
301        {
302            collect_masked(arena, child, result);
303        }
304        child = arena.next_sibling.get(child);
305    }
306}
307
308/// declare the private variables (`@private`) of a mixin body or a rule in the innermost level of the scope
309fn declare_privates(arena: &AstArena, node: u32, scope: &Rc<MixinScope>) {
310    let privates = scope.levels.last().unwrap().privates.clone();
311    let dyn_scope = as_scope(scope);
312    let mut child = arena.first_child.get(node);
313    while child != 0 {
314        if is_at_rule(arena, child, "private") {
315            let mut n = arena.first_child.get(child);
316            while n != 0 {
317                if is_custom_property(arena, n) {
318                    // the last declaration wins
319                    let entry = VariableEntry::unresolved(declaration_value(arena, n), &dyn_scope);
320                    privates.borrow_mut().insert(arena.resolve_string(arena.name.get(n)).to_string(), entry);
321                }
322                n = arena.next_sibling.get(n);
323            }
324        }
325        child = arena.next_sibling.get(child);
326    }
327}
328
329/// true if a node contains nested rules
330fn has_nested_rules(arena: &AstArena, node: u32) -> bool {
331    let mut child = arena.first_child.get(node);
332    while child != 0 {
333        if arena.data_types.get(child) == EnumToken::RuleNodeType
334            || (arena.data_types.get(child) == EnumToken::AtRuleNodeType
335                && arena.flags.get(child) & EnumAstNodeStatus::HasChildren != 0
336                && has_nested_rules(arena, child))
337        {
338            return true;
339        }
340        child = arena.next_sibling.get(child);
341    }
342    false
343}
344
345/// true if the compound selector part references the nesting selector: `&`, `:is(&)`, `:where(&)`
346fn is_nesting_part(part: &str) -> bool {
347    if part == "&" {
348        return true;
349    }
350    let lower = part.to_ascii_lowercase();
351    ["is", "where"].iter().any(|f| {
352        lower
353            .strip_prefix(':')
354            .and_then(|r| r.strip_prefix(f))
355            .and_then(|r| r.strip_prefix('('))
356            .and_then(|r| r.strip_suffix(')'))
357            .is_some_and(|inner| inner.trim() == "&")
358    })
359}
360
361/// relation of the subject of a nested selector to the subject of the rule that contains it
362fn selector_relation(parts: &[String]) -> u8 {
363    let mut compounds: Vec<Vec<&str>> = vec![Vec::new()];
364    let mut combinators: Vec<&str> = Vec::new();
365    let mut whitespace = false;
366    for part in parts {
367        if part.trim().is_empty() {
368            whitespace = true;
369            continue;
370        }
371        if matches!(part.as_str(), ">" | "+" | "~" | "||") {
372            combinators.push(part);
373            compounds.push(Vec::new());
374            whitespace = false;
375            continue;
376        }
377        if whitespace && !compounds.last().unwrap().is_empty() {
378            // descendant combinator
379            combinators.push(" ");
380            compounds.push(Vec::new());
381        }
382        whitespace = false;
383        compounds.last_mut().unwrap().push(part);
384    }
385    // relative selector: `> .child`, `+ .sibling`
386    if compounds[0].is_empty() {
387        compounds[0].push("&");
388    }
389    match compounds.iter().rposition(|c| c.iter().any(|p| is_nesting_part(p))) {
390        None => {
391            // '&' used in a way that is not handled: the relation is unknown
392            if parts.iter().any(|p| p.contains('&')) {
393                OUTSIDE
394            } else {
395                // the selector is implicitly prefixed with `& `
396                DESCENDANT
397            }
398        }
399        Some(index) if index == compounds.len() - 1 => SELF,
400        Some(index) => {
401            if combinators[index] == " " || combinators[index] == ">" {
402                DESCENDANT
403            } else {
404                OUTSIDE
405            }
406        }
407    }
408}
409
410/// serialize a declaration of a mixin body. the declaration is left as is when it references an invalid variable
411fn serialize_declaration(arena: &AstArena, declaration: u32, scope: &Rc<MixinScope>) -> String {
412    let name = arena.resolve_string(arena.name.get(declaration));
413    let custom = arena.starts_with(declaration, "nam", "--");
414    if let Some(registry) = &scope.application.registry {
415        registry.custom_property.set(custom);
416    }
417    let tokens = arena.tokens(declaration);
418    // a custom property is inherited by the descendants: a typed argument is the value computed on the element
419    let value = substitute(arena, &tokens, &as_scope(scope), scope.descendant() || custom);
420    format!("{}:{}", name, value.unwrap_or_else(|| render(arena, &tokens)))
421}
422
423/// serialize an `@apply` rule of a mixin body. its arguments may reference the private variables
424fn serialize_apply(arena: &AstArena, node: u32, scope: &Rc<MixinScope>) -> String {
425    let tokens = arena.tokens(node);
426    let prelude = match first_token(arena, &tokens).filter(|&r| arena.data_types.get(r) == EnumToken::CustomFunctionTokenType) {
427        Some(reference) => {
428            // the arguments are substituted one by one: an invalid argument is kept
429            let dyn_scope = as_scope(scope);
430            let args: Vec<String> = split_arguments(arena, &arena.tokens(reference))
431                .iter()
432                .map(|arg| substitute(arena, arg, &dyn_scope, scope.descendant()).unwrap_or_else(|| render(arena, arg)))
433                .collect();
434            format!("{}({})", arena.resolve_string(arena.string_value.get(reference)), args.join(","))
435        }
436        None => render(arena, trim(arena, &tokens)),
437    };
438    let block = if arena.flags.get(node) & EnumAstNodeStatus::HasChildren != 0 {
439        format!("{{{}}}", serialize_declarations(arena, node, scope))
440    } else {
441        ";".to_string()
442    };
443    format!("@apply {}{}", prelude, block)
444}
445
446/// serialize the declarations of a contents block
447fn serialize_declarations(arena: &AstArena, node: u32, scope: &Rc<MixinScope>) -> String {
448    let mut result = String::new();
449    let mut child = arena.first_child.get(node);
450    while child != 0 {
451        if arena.data_types.get(child) == EnumToken::DeclarationNodeType {
452            result.push_str(&serialize_declaration(arena, child, scope));
453            result.push(';');
454        } else if is_at_rule(arena, child, "contents") {
455            // the contents block is forwarded: `@apply --mixin { @contents; }`
456            result.push_str(&serialize_contents(arena, child, scope));
457        }
458        child = arena.next_sibling.get(child);
459    }
460    result
461}
462
463/// serialize a `@contents` rule: the contents block of the `@apply` rule, otherwise the default contents block
464fn serialize_contents(arena: &AstArena, node: u32, scope: &Rc<MixinScope>) -> String {
465    if let Some(contents) = &scope.application.contents {
466        return contents.clone();
467    }
468    if arena.flags.get(node) & EnumAstNodeStatus::HasChildren != 0 {
469        serialize_declarations(arena, node, scope)
470    } else {
471        String::new()
472    }
473}
474
475/// serialize a nested rule of a mixin body. the rule is split when its selectors do not have the same relation to the
476/// rule the mixin is applied to
477fn serialize_rule(arena: &AstArena, rule: u32, scope: &Rc<MixinScope>) -> String {
478    // insertion ordered groups of selectors by relation
479    let mut groups: Vec<(u8, Vec<String>)> = Vec::new();
480    let merge = !has_nested_rules(arena, rule) && scope.application.typed.borrow().is_empty();
481    for parts in split_rule(&arena.resolve_string(arena.name.get(rule))) {
482        let mut relation = selector_relation(&parts);
483        if merge && relation == DESCENDANT {
484            relation = SELF;
485        }
486        match groups.iter_mut().find(|(r, _)| *r == relation) {
487            Some((_, list)) => list.push(parts.concat()),
488            None => groups.push((relation, vec![parts.concat()])),
489        }
490    }
491    let mut masked = HashSet::default();
492    collect_masked(arena, rule, &mut masked);
493    let mut result = String::new();
494    for (relation, selectors) in groups {
495        let child = scope.child(relation, &masked);
496        declare_privates(arena, rule, &child);
497        result.push_str(&format!("{}{{{}}}", selectors.join(","), serialize_block(arena, rule, &child)));
498    }
499    result
500}
501
502/// serialize the children of a mixin body, a nested rule or a nested at-rule
503fn serialize_block(arena: &AstArena, node: u32, scope: &Rc<MixinScope>) -> String {
504    let mut result = String::new();
505    let mut child = arena.first_child.get(node);
506    while child != 0 {
507        match arena.data_types.get(child) {
508            EnumToken::DeclarationNodeType => {
509                result.push_str(&serialize_declaration(arena, child, scope));
510                result.push(';');
511            }
512            EnumToken::RuleNodeType => result.push_str(&serialize_rule(arena, child, scope)),
513            EnumToken::AtRuleNodeType => {
514                let name = arena.name.get(child);
515                if arena.string_equals(name, "private") {
516                    // the private variables are substituted
517                } else if arena.string_equals(name, "apply") {
518                    result.push_str(&serialize_apply(arena, child, scope));
519                } else if arena.string_equals(name, "result") {
520                    // the content of `@result` is the result of the mixin
521                    result.push_str(&serialize_block(arena, child, scope));
522                } else if arena.string_equals(name, "contents") {
523                    result.push_str(&serialize_contents(arena, child, scope));
524                } else {
525                    let prelude = arena.resolve_string(arena.string_value.get(child));
526                    result.push('@');
527                    result.push_str(&arena.resolve_string(name));
528                    if !prelude.is_empty() {
529                        result.push(' ');
530                        result.push_str(&prelude);
531                    }
532                    if arena.flags.get(child) & EnumAstNodeStatus::HasChildren != 0 {
533                        result.push('{');
534                        result.push_str(&serialize_block(arena, child, scope));
535                        result.push('}');
536                    } else {
537                        result.push(';');
538                    }
539                }
540            }
541            _ => {}
542        }
543        child = arena.next_sibling.get(child);
544    }
545    result
546}
547
548/// the generated nodes are located at the `@apply` rule
549fn locate(arena: &AstArena, node: u32, location: u32) {
550    arena.copy_location(node, location);
551    if arena.flags.get(node) & EnumAstNodeStatus::HasChildren != 0 {
552        let mut child = arena.first_child.get(node);
553        while child != 0 {
554            locate(arena, child, location);
555            child = arena.next_sibling.get(child);
556        }
557    }
558}
559
560/// parse a mixin definition. `None` if the prelude is not valid
561fn parse_mixin(arena: &AstArena, node: u32) -> Option<MixinDefinition> {
562    let reference = first_token(arena, &arena.tokens(node))?;
563    let parameters = match arena.data_types.get(reference) {
564        EnumToken::CustomFunctionTokenType => parse_parameters(arena, reference)?,
565        EnumToken::DashedIdenTokenType => Vec::new(),
566        _ => return None,
567    };
568    Some(MixinDefinition { node, parameters })
569}
570
571/// parse the prelude of an `@apply` rule: the name of the mixin and the arguments
572fn parse_apply(arena: &AstArena, node: u32) -> Option<(String, Vec<Vec<u32>>)> {
573    let reference = first_token(arena, &arena.tokens(node))?;
574    let name = arena.resolve_string(arena.string_value.get(reference)).to_string();
575    match arena.data_types.get(reference) {
576        EnumToken::DashedIdenTokenType => Some((name, Vec::new())),
577        EnumToken::CustomFunctionTokenType => Some((name, parse_arguments(arena, reference))),
578        _ => None,
579    }
580}
581
582/// bind the arguments to the mixin parameters. false when the arguments do not match the parameters
583fn bind_parameters(arena: &AstArena, definition: &MixinDefinition, args: &[Vec<u32>], caller: &Rc<MixinScope>, scope: &Rc<MixinScope>, options: &ParserOptions) -> bool {
584    let application = &scope.application;
585    if args.len() > definition.parameters.len() {
586        return false;
587    }
588    let caller_scope = as_scope(caller);
589    let body_scope = as_scope(scope);
590    for (index, parameter) in definition.parameters.iter().enumerate() {
591        let entry = if index < args.len() {
592            // `{ tokens: null, text, scope }`: the value is resolved
593            let entry = VariableEntry::resolved(substitute(arena, &args[index], &caller_scope, false));
594            entry.borrow_mut().scope = Some(Rc::downgrade(&body_scope));
595            entry
596        } else if let Some(default) = &parameter.default_value {
597            // the default value may reference the other variables: it is resolved once the variables are declared
598            VariableEntry::unresolved(default.clone(), &body_scope)
599        } else {
600            return false;
601        };
602        application.args.borrow_mut().insert(parameter.name.clone(), entry);
603    }
604    // the private variables may be referenced by the default values
605    declare_privates(arena, definition.node, scope);
606    for parameter in &definition.parameters {
607        let entry = application.args.borrow().get(&parameter.name).cloned().unwrap();
608        let Some(value) = resolve(arena, &entry, false) else {
609            return false;
610        };
611        if !matches_type(arena, parameter.syntax.as_deref(), &value, options) {
612            return false;
613        }
614        // the value of a typed argument is computed on the element the mixin is applied to
615        if let Some(syntax) = &parameter.syntax {
616            application.typed.borrow_mut().insert(parameter.name.clone(), TypedArgument { value, syntax: syntax.clone(), entry: None });
617        }
618    }
619    true
620}
621
622/// create the registered custom property of a typed argument
623fn register_property(arena: &AstArena, property: &RegisteredProperty) -> u32 {
624    let token = arena.create_token(EnumToken::DashedIdenTokenType, TokenValue::Str(&property.name), None);
625    let node = arena.create_at_rule(
626        EnumToken::AtRuleNodeType,
627        StrOrId::Str("property"),
628        StrOrId::Str(&property.name),
629        true,
630        Some(&[token]),
631        EnumAstNodeStatus::Validated,
632        None,
633    );
634    let css = format!("syntax:{};inherits:true;initial-value:{}", serde_json::to_string(&property.syntax).unwrap(), property.initial_value);
635    let (_, nodes) = parse_declarations(&css, Some(arena.rc()));
636    arena.append_child_list(node, &nodes);
637    node
638}
639
640/// true if a mixin applies itself, directly or through the mixins it applies
641fn is_recursive(arena: &AstArena, name: &str, state: &mut EvaluationState, stack: &mut Vec<String>) -> bool {
642    if stack.iter().any(|s| s == name) {
643        return true;
644    }
645    if let Some(&result) = state.recursive.get(name) {
646        return result;
647    }
648    let definitions = state.definitions.get(name).cloned().unwrap_or_default();
649    let mut result = false;
650    stack.push(name.to_string());
651    'definitions: for definition in definitions {
652        let mut walker = arena.walk(definition.node, None, false);
653        while let Some(id) = walker.next(arena) {
654            if id != definition.node && is_at_rule(arena, id, "apply") {
655                if let Some((reference, _)) = parse_apply(arena, id) {
656                    if is_recursive(arena, &reference, state, stack) {
657                        result = true;
658                        break 'definitions;
659                    }
660                }
661            }
662        }
663    }
664    stack.pop();
665    // a mixin that reaches one of the mixins being checked is part of a cycle
666    state.recursive.insert(name.to_string(), result);
667    result
668}
669
670/// replace an `@apply` rule with the evaluated body of the mixin. `None` when the `@apply` rule is not evaluated
671fn apply(arena: &AstArena, node: u32, state: &mut EvaluationState) -> Option<Vec<u32>> {
672    let (name, args) = parse_apply(arena, node)?;
673    // the mixins visible from the `@apply` rule
674    let definitions = resolve_definitions(arena, state.definitions.get(&name), node);
675    let definition = if definitions.len() == 1 { Some(definitions[0].clone()) } else { None };
676    let properties = rule_properties(arena, node);
677    let chain = state.chains.get(&node).cloned().unwrap_or_default();
678    let usable = definition.is_some()
679        && properties.is_some()
680        && !is_recursive(arena, &name, state, &mut Vec::new())
681        && !chain.contains(&name)
682        && chain.len() < MAX_DEPTH;
683    let (Some(definition), Some(properties), true) = (definition, properties, usable) else {
684        // the visible definitions are kept
685        for visible in &definitions {
686            state.pending.insert(visible.node);
687        }
688        return None;
689    };
690    let properties = Rc::new(properties);
691    let level = || vec![ScopeLevel { privates: Privates::default(), relation: SELF }];
692    // the contents block is a declaration list. its variables are not private variables: they are not substituted
693    let contents = if arena.flags.get(node) & EnumAstNodeStatus::HasChildren != 0 {
694        let empty = MixinApplication::new(&name, Rc::new(HashMap::default()), None, None, None);
695        let scope = MixinScope::new(level(), empty, Rc::new(HashSet::default()));
696        Some(serialize_declarations(arena, node, &scope))
697    } else {
698        None
699    };
700    let application = MixinApplication::new(&name, properties.clone(), contents, Some(state.names.clone()), Some(state.registry.clone()));
701    // the arguments are evaluated in the context of the `@apply` rule
702    let caller = MixinScope::new(level(), MixinApplication::new(&name, properties, None, None, None), Rc::new(HashSet::default()));
703    let mut masked = HashSet::default();
704    collect_masked(arena, definition.node, &mut masked);
705    let scope = MixinScope::new(level(), application.clone(), Rc::new(masked));
706    if !bind_parameters(arena, &definition, &args, &caller, &scope, &state.options) {
707        state.pending.insert(definition.node);
708        return None;
709    }
710    // the custom functions called by the mixin body are evaluated in the context of the `@apply` rule
711    state.registry.site.set(node);
712    let failed = state.registry.failed.get();
713    let mut css = serialize_block(arena, definition.node, &scope);
714    // a typed argument cannot be registered, or a custom function call is not evaluated
715    if application.failed.get() || state.registry.failed.get() != failed {
716        state.pending.insert(definition.node);
717        return None;
718    }
719    if !application.registered.borrow().is_empty() {
720        // the top level node that contains the `@apply` rule
721        let mut top = node;
722        while arena.parents.get(top) != state.ast && arena.parents.get(top) != 0 {
723            top = arena.parents.get(top);
724        }
725        let mut declarations = String::new();
726        for property in application.registered.borrow().iter() {
727            let registered = register_property(arena, property);
728            locate(arena, registered, node);
729            arena.insert_before(top, &[registered]);
730            // the value is computed on the element the mixin is applied to
731            declarations.push_str(&format!("{}:{};", property.name, property.value));
732        }
733        css = declarations + &css;
734    }
735    // the body is parsed as the content of the rule the mixin is applied to: '&' is that rule
736    let nodes = parse_rule_content(&css, arena.rc(), state.options.parse_color);
737    let mut nested = chain;
738    nested.push(name);
739    for &child in &nodes {
740        locate(arena, child, node);
741        arena.insert_before(node, &[child]);
742        // the `@apply` rules of the mixin body
743        let mut walker = arena.walk(child, None, false);
744        while let Some(id) = walker.next(arena) {
745            if is_at_rule(arena, id, "apply") {
746                state.chains.insert(id, nested.clone());
747            }
748        }
749    }
750    arena.detach(node);
751    Some(nodes)
752}
753
754/// the definitions that are kept: the referenced definitions that are not evaluated, the functions that are not
755/// called, and the definitions referenced by them
756fn kept_definitions(arena: &AstArena, state: &EvaluationState, registry: &FunctionRegistry) -> HashSet<u32> {
757    let mut kept: HashSet<u32> = state.pending.iter().chain(registry.pending.borrow().iter()).copied().collect();
758    let mut queue: Vec<u32> = kept.iter().copied().collect();
759    for definitions in registry.definitions.values() {
760        for definition in definitions {
761            if !registry.evaluated.borrow().contains(&definition.node) && kept.insert(definition.node) {
762                queue.push(definition.node);
763            }
764        }
765    }
766    queue.extend(state.invalid.iter().copied());
767    while let Some(node) = queue.pop() {
768        let mut referenced: Vec<u32> = Vec::new();
769        let mut walker = arena.walk(node, None, false);
770        while let Some(id) = walker.next(arena) {
771            if id != node && is_at_rule(arena, id, "apply") {
772                if let Some((reference, _)) = parse_apply(arena, id) {
773                    referenced.extend(resolve_definitions(arena, state.definitions.get(&reference), id).iter().map(|d| d.node));
774                }
775            }
776            for call in find_calls(arena, &arena.tokens(id)) {
777                let name = arena.resolve_string(arena.string_value.get(call));
778                referenced.extend(resolve_definitions(arena, registry.definitions.get(&name), id).iter().map(|d| d.node));
779            }
780        }
781        for definition in referenced {
782            if kept.insert(definition) {
783                queue.push(definition);
784            }
785        }
786    }
787    kept
788}
789
790/// evaluate the mixins and the custom functions of a stylesheet (`EvaluateMixinFeature.evaluate()`)
791pub fn evaluate_mixins(arena: &AstArena, ast: u32, options: &ParserOptions) {
792    let mut invalid_mixins: Vec<u32> = Vec::new();
793    let mut invalid_functions: Vec<u32> = Vec::new();
794    let mut functions = JsMap::new();
795    collect_definitions(arena, ast, "function", &parse_function, &mut functions, &mut invalid_functions);
796    let registry = FunctionRegistry::new(functions, options);
797    let mut mixins = JsMap::new();
798    collect_definitions(arena, ast, "mixin", &parse_mixin, &mut mixins, &mut invalid_mixins);
799    let mut state = EvaluationState {
800        definitions: mixins,
801        invalid: invalid_mixins.clone(),
802        pending: HashSet::default(),
803        chains: HashMap::default(),
804        recursive: HashMap::default(),
805        ast,
806        registry: registry.clone(),
807        names: Rc::new(RefCell::new(HashSet::default())),
808        options: options.clone(),
809    };
810    // the custom functions that are not valid are dropped
811    for &node in &invalid_functions {
812        arena.detach(node);
813    }
814    if state.definitions.is_empty() && registry.definitions.is_empty() {
815        return;
816    }
817    if !state.definitions.is_empty() {
818        let mut walker = arena.walk(ast, None, false);
819        while let Some(id) = walker.next(arena) {
820            if is_custom_property(arena, id) {
821                state.names.borrow_mut().insert(arena.resolve_string(arena.name.get(id)).to_string());
822            } else if is_at_rule(arena, id, "property") {
823                state.names.borrow_mut().insert(arena.resolve_string(arena.string_value.get(id)).trim().to_string());
824            }
825        }
826        // depth first traversal, in document order
827        let mut stack: Vec<u32> = Vec::new();
828        let mut child = arena.last_child.get(ast);
829        while child != 0 {
830            stack.push(child);
831            child = arena.previous_sibling.get(child);
832        }
833        while let Some(node) = stack.pop() {
834            if arena.data_types.get(node) == EnumToken::AtRuleNodeType {
835                // the mixin and the function bodies are evaluated when they are used
836                if is_at_rule(arena, node, "mixin") || is_at_rule(arena, node, "function") {
837                    continue;
838                }
839                if is_at_rule(arena, node, "apply") {
840                    if let Some(nodes) = apply(arena, node, &mut state) {
841                        // the mixin body may apply other mixins
842                        stack.extend(nodes.iter().rev());
843                        continue;
844                    }
845                }
846            }
847            if arena.flags.get(node) & EnumAstNodeStatus::HasChildren != 0 {
848                let mut child = arena.last_child.get(node);
849                while child != 0 {
850                    stack.push(child);
851                    child = arena.previous_sibling.get(child);
852                }
853            }
854        }
855    }
856    // the custom function calls, including the calls of the evaluated mixins
857    if !registry.definitions.is_empty() {
858        evaluate_functions(arena, ast, &registry);
859    }
860    let kept = kept_definitions(arena, &state, &registry);
861    let keep = options.keep_mixins == Some(true);
862    finalize_definitions(arena, ast, "mixin", &kept, keep, &invalid_mixins);
863    finalize_definitions(arena, ast, "function", &kept, keep, &[]);
864}
865
866/// evaluate the css mixins and the custom functions (`EvaluateMixinFeature`)
867pub struct EvaluateMixinFeature;
868
869const ACCEPT: [u8; 1] = [EnumToken::StyleSheetNodeType];
870
871impl EvaluateMixinFeature {
872    pub fn register(options: &ParserOptions, features: &mut Vec<SharedFeature>) {
873        if options.evaluate_mixins == Some(true) {
874            features.push(Rc::new(RefCell::new(EvaluateMixinFeature)));
875        }
876    }
877}
878
879impl MinifyFeature for EvaluateMixinFeature {
880    fn accept(&self) -> Option<&[u8]> {
881        Some(&ACCEPT)
882    }
883
884    fn ordering(&self) -> i32 {
885        0
886    }
887
888    fn process_mode(&self) -> u32 {
889        FeatureWalkMode::Pre
890    }
891
892    fn run(&mut self, arena: &AstArena, ast: u32, options: &ParserOptions, _parent: u32, _context: &mut MinifyContext, _mode: u32) -> FeatureResult {
893        evaluate_mixins(arena, ast, options);
894        FeatureResult::None
895    }
896}