rust-css-parser 2.3.0

Fault-tolerant CSS parser, validator, minifier and renderer: the Rust port of @tbela99/css-parser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
//! Port of `src/ast/features/mixin.ts`: the `@apply` rules are replaced by the body of the mixin they reference,
//! the custom function calls by the result of the function (<https://drafts.csswg.org/css-mixins-1/#mixin-rule>).

use super::r#type::FeatureWalkMode;
use super::{FeatureResult, MinifyFeature, SharedFeature};
use crate::ast::arena::{AstArena, StrOrId, TokenValue};
use crate::ast::minify::{split_rule, MinifyContext};
use crate::ast::mixins::custom_function::{evaluate_functions, find_calls, parse_function, FunctionRegistry};
use crate::ast::mixins::variables::{
    collect_definitions, declaration_value, finalize_definitions, first_token, is_at_rule, is_custom_property, matches_type, parse_arguments,
    parse_parameters, render, resolve, resolve_definitions, rule_properties, split_arguments, substitute, trim, Definition, Entry, Found, Parameter,
    RuleScope, VariableEntry, VariableScope,
};
use crate::ast::types::{EnumAstNodeStatus, EnumToken};
use crate::options::ParserOptions;
use crate::parser::declaration::JsMap;
use crate::parser::parse::{parse_declarations, parse_rule_content};
use std::cell::{Cell, RefCell};
use crate::utils::fx::{HashMap, HashSet};
use std::rc::Rc;

/// the subject of the rule is the element the mixin is applied to: `&`, `&.active`, `&::before`
const SELF: u8 = 0;
/// the subject of the rule is a descendant of the element the mixin is applied to: `& *`, `& > *`, `.child`
const DESCENDANT: u8 = 1;
/// the subject of the rule is not in the subtree of the element the mixin is applied to: `& + *`, `& ~ *`
const OUTSIDE: u8 = 2;
/// maximum number of nested `@apply` rules
const MAX_DEPTH: usize = 32;

/// private variables by name, shared by the levels of the nested scopes
type Privates = Rc<RefCell<HashMap<String, Entry>>>;

/// variables declared by a rule of the mixin body (or by the mixin body itself)
#[derive(Clone)]
struct ScopeLevel {
    /// custom properties declared with `@private`
    privates: Privates,
    /// relation of the subject of the current rule to the subject of the rule that declares the variables
    relation: u8,
}

/// mixin definition
#[derive(Clone)]
struct MixinDefinition {
    node: u32,
    parameters: Vec<Parameter>,
}

impl Definition for MixinDefinition {
    fn node(&self) -> u32 {
        self.node
    }
}

/// evaluation state
struct EvaluationState {
    /// valid mixin definitions by name, in document order
    definitions: JsMap<Vec<MixinDefinition>>,
    /// the mixins that are not valid: they are ignored and left as is
    invalid: Vec<u32>,
    /// the mixin definitions referenced by the `@apply` rules that have not been evaluated: they are kept
    pending: HashSet<u32>,
    /// mixins being applied, for each `@apply` rule generated by a mixin: recursion detection
    chains: HashMap<u32, Vec<String>>,
    /// the mixins that apply themselves, directly or through other mixins
    recursive: HashMap<String, bool>,
    ast: u32,
    registry: Rc<FunctionRegistry>,
    /// names of the custom properties of the stylesheet: the names of the registered custom properties are unique
    names: Rc<RefCell<HashSet<String>>>,
    options: ParserOptions,
}

/// typed argument: its value is computed on the element the mixin is applied to (`TypedArgument`)
struct TypedArgument {
    value: String,
    syntax: String,
    /// variable that references the registered custom property
    entry: Option<Entry>,
}

/// registered custom property of a typed argument
struct RegisteredProperty {
    name: String,
    syntax: String,
    initial_value: String,
    value: String,
}

/// application of a mixin: the variables shared by the scopes of the mixin body
struct MixinApplication {
    name: String,
    /// mixin arguments and default values
    args: RefCell<HashMap<String, Entry>>,
    /// the typed arguments that depend on the element the mixin is applied to
    typed: RefCell<HashMap<String, TypedArgument>>,
    /// registered custom properties of the typed arguments
    registered: RefCell<Vec<RegisteredProperty>>,
    /// the mixin cannot be evaluated: a typed argument cannot be registered
    failed: Cell<bool>,
    /// the variables visible from the bodies of the custom functions called by the mixin body
    dynamic: Rc<dyn VariableScope>,
    /// custom properties declared in the rule the mixin is applied to
    properties: Rc<HashMap<String, Entry>>,
    /// serialized contents block of the `@apply` rule
    contents: Option<String>,
    names: Option<Rc<RefCell<HashSet<String>>>>,
    registry: Option<Rc<FunctionRegistry>>,
}

impl MixinApplication {
    fn new(
        name: &str,
        properties: Rc<HashMap<String, Entry>>,
        contents: Option<String>,
        names: Option<Rc<RefCell<HashSet<String>>>>,
        registry: Option<Rc<FunctionRegistry>>,
    ) -> Rc<Self> {
        Rc::new(MixinApplication {
            name: name.to_string(),
            args: RefCell::new(HashMap::default()),
            typed: RefCell::new(HashMap::default()),
            registered: RefCell::new(Vec::new()),
            failed: Cell::new(false),
            dynamic: RuleScope::new(properties.clone(), registry.clone(), None),
            properties,
            contents,
            names,
            registry,
        })
    }

    /// variable that references the registered custom property of a typed argument. `None` when the argument cannot
    /// be registered
    fn typed_entry(&self, name: &str) -> Option<Entry> {
        let mut typed = self.typed.borrow_mut();
        let argument = typed.get_mut(name)?;
        if argument.entry.is_none() {
            let initial_value = initial_value_of(&argument.syntax);
            let (Some(initial_value), Some(names)) = (initial_value, self.names.as_ref()) else {
                self.failed.set(true);
                return None;
            };
            let prefix = format!("--{}-{}-", &self.name[2..], &name[2..]);
            let mut index = 1;
            while names.borrow().contains(&format!("{}{}", prefix, index)) {
                index += 1;
            }
            let property = format!("{}{}", prefix, index);
            let text = format!("var({})", property);
            let entry = Rc::new(RefCell::new(VariableEntry { text: Some(Some(text.clone())), descendant_text: Some(Some(text)), ..Default::default() }));
            argument.entry = Some(entry);
            names.borrow_mut().insert(property.clone());
            self.registered.borrow_mut().push(RegisteredProperty { name: property, syntax: argument.syntax.clone(), initial_value, value: argument.value.clone() });
        }
        argument.entry.clone()
    }
}

/// variables visible from a node of a mixin body
struct MixinScope {
    /// variables declared by the mixin body and the rules that contain the current node, outer first
    levels: Vec<ScopeLevel>,
    application: Rc<MixinApplication>,
    /// custom properties declared in the mixin body: they override the rule custom properties
    masked: Rc<HashSet<String>>,
}

impl MixinScope {
    fn new(levels: Vec<ScopeLevel>, application: Rc<MixinApplication>, masked: Rc<HashSet<String>>) -> Rc<Self> {
        Rc::new(MixinScope { levels, application, masked })
    }

    /// the subject of the current rule is a descendant of the element the mixin is applied to
    fn descendant(&self) -> bool {
        self.levels[0].relation == DESCENDANT
    }

    /// scope of a nested rule
    fn child(&self, relation: u8, masked: &HashSet<String>) -> Rc<MixinScope> {
        let mut levels: Vec<ScopeLevel> =
            self.levels.iter().map(|level| ScopeLevel { privates: level.privates.clone(), relation: compose(level.relation, relation) }).collect();
        levels.push(ScopeLevel { privates: Privates::default(), relation: SELF });
        let masked = if masked.is_empty() { self.masked.clone() } else { Rc::new(self.masked.iter().chain(masked.iter()).cloned().collect()) };
        MixinScope::new(levels, self.application.clone(), masked)
    }
}

impl VariableScope for MixinScope {
    fn lookup(&self, name: &str, descendant: bool) -> Found {
        // the inner declarations override the outer declarations
        for level in self.levels[1..].iter().rev() {
            if let Some(entry) = level.privates.borrow().get(name) {
                return Found::Entry(entry.clone());
            }
        }
        // the private variables of the mixin body are not visible from the siblings of the element
        let visible = self.levels[0].relation != OUTSIDE;
        let private = self.levels[0].privates.borrow().get(name).cloned();
        if let (Some(entry), true) = (&private, visible) {
            return Found::Entry(entry.clone());
        }
        let application = &self.application;
        let arg = application.args.borrow().get(name).cloned();
        if let Some(arg) = arg {
            if !visible {
                return Found::Undefined;
            }
            // the descendants inherit the value computed on the element
            if descendant && application.typed.borrow().contains_key(name) {
                return Found::Entry(application.typed_entry(name).unwrap_or(arg));
            }
            return Found::Entry(arg);
        }
        if private.is_some() {
            return Found::Undefined;
        }
        // the custom properties of the rule the mixin is applied to. the descendants inherit them
        if visible && !self.masked.contains(name) {
            if let Some(entry) = application.properties.get(name) {
                return Found::Entry(entry.clone());
            }
        }
        Found::Null
    }

    fn functions(&self) -> Option<Rc<FunctionRegistry>> {
        self.application.registry.clone()
    }

    /// the custom functions see the custom properties of the rule, not the private variables
    fn dynamic(&self) -> Option<Rc<dyn VariableScope>> {
        Some(self.application.dynamic.clone())
    }
}

fn as_scope(scope: &Rc<MixinScope>) -> Rc<dyn VariableScope> {
    scope.clone()
}

/// initial value of a registered custom property: a computationally independent value that matches the syntax
fn initial_value_of(syntax: &str) -> Option<String> {
    let defaults = |name: &str| -> Option<&'static str> {
        Some(match name {
            "length" | "length-percentage" => "0px",
            "percentage" => "0%",
            "number" | "integer" => "0",
            "angle" => "0deg",
            "time" => "0s",
            "resolution" => "1dppx",
            "color" => "transparent",
            "custom-ident" => "none",
            "string" => "\"\"",
            "transform-function" | "transform-list" => "scale(1)",
            _ => return None,
        })
    };
    for component in syntax.split('|') {
        // `/^(?:<([a-z-]+)>|([a-z][a-z0-9-]*))[+#]?$/i`
        let component = component.trim();
        let body = component.strip_suffix(['+', '#']).unwrap_or(component);
        if let Some(name) = body.strip_prefix('<').and_then(|b| b.strip_suffix('>')) {
            if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphabetic() || b == b'-') {
                return None;
            }
            if let Some(value) = defaults(&name.to_lowercase()) {
                return Some(value.to_string());
            }
        } else {
            let mut chars = body.bytes();
            let valid = chars.next().is_some_and(|b| b.is_ascii_alphabetic()) && chars.all(|b| b.is_ascii_alphanumeric() || b == b'-');
            if !valid {
                return None;
            }
            return Some(body.to_string());
        }
    }
    None
}

/// relation of the subject of a nested rule to the subject of an outer rule
fn compose(outer: u8, relation: u8) -> u8 {
    if outer == SELF {
        relation
    } else {
        outer
    }
}

/// names of the custom properties declared by a mixin body or a rule (the nested at-rules included, `@private` and the
/// nested rules excluded)
fn collect_masked(arena: &AstArena, node: u32, result: &mut HashSet<String>) {
    let mut child = arena.first_child.get(node);
    while child != 0 {
        if is_custom_property(arena, child) {
            result.insert(arena.resolve_string(arena.name.get(child)).to_string());
        } else if arena.data_types.get(child) == EnumToken::AtRuleNodeType
            && arena.flags.get(child) & EnumAstNodeStatus::HasChildren != 0
            && !is_at_rule(arena, child, "private")
        {
            collect_masked(arena, child, result);
        }
        child = arena.next_sibling.get(child);
    }
}

/// declare the private variables (`@private`) of a mixin body or a rule in the innermost level of the scope
fn declare_privates(arena: &AstArena, node: u32, scope: &Rc<MixinScope>) {
    let privates = scope.levels.last().unwrap().privates.clone();
    let dyn_scope = as_scope(scope);
    let mut child = arena.first_child.get(node);
    while child != 0 {
        if is_at_rule(arena, child, "private") {
            let mut n = arena.first_child.get(child);
            while n != 0 {
                if is_custom_property(arena, n) {
                    // the last declaration wins
                    let entry = VariableEntry::unresolved(declaration_value(arena, n), &dyn_scope);
                    privates.borrow_mut().insert(arena.resolve_string(arena.name.get(n)).to_string(), entry);
                }
                n = arena.next_sibling.get(n);
            }
        }
        child = arena.next_sibling.get(child);
    }
}

/// true if a node contains nested rules
fn has_nested_rules(arena: &AstArena, node: u32) -> bool {
    let mut child = arena.first_child.get(node);
    while child != 0 {
        if arena.data_types.get(child) == EnumToken::RuleNodeType
            || (arena.data_types.get(child) == EnumToken::AtRuleNodeType
                && arena.flags.get(child) & EnumAstNodeStatus::HasChildren != 0
                && has_nested_rules(arena, child))
        {
            return true;
        }
        child = arena.next_sibling.get(child);
    }
    false
}

/// true if the compound selector part references the nesting selector: `&`, `:is(&)`, `:where(&)`
fn is_nesting_part(part: &str) -> bool {
    if part == "&" {
        return true;
    }
    let lower = part.to_ascii_lowercase();
    ["is", "where"].iter().any(|f| {
        lower
            .strip_prefix(':')
            .and_then(|r| r.strip_prefix(f))
            .and_then(|r| r.strip_prefix('('))
            .and_then(|r| r.strip_suffix(')'))
            .is_some_and(|inner| inner.trim() == "&")
    })
}

/// relation of the subject of a nested selector to the subject of the rule that contains it
fn selector_relation(parts: &[String]) -> u8 {
    let mut compounds: Vec<Vec<&str>> = vec![Vec::new()];
    let mut combinators: Vec<&str> = Vec::new();
    let mut whitespace = false;
    for part in parts {
        if part.trim().is_empty() {
            whitespace = true;
            continue;
        }
        if matches!(part.as_str(), ">" | "+" | "~" | "||") {
            combinators.push(part);
            compounds.push(Vec::new());
            whitespace = false;
            continue;
        }
        if whitespace && !compounds.last().unwrap().is_empty() {
            // descendant combinator
            combinators.push(" ");
            compounds.push(Vec::new());
        }
        whitespace = false;
        compounds.last_mut().unwrap().push(part);
    }
    // relative selector: `> .child`, `+ .sibling`
    if compounds[0].is_empty() {
        compounds[0].push("&");
    }
    match compounds.iter().rposition(|c| c.iter().any(|p| is_nesting_part(p))) {
        None => {
            // '&' used in a way that is not handled: the relation is unknown
            if parts.iter().any(|p| p.contains('&')) {
                OUTSIDE
            } else {
                // the selector is implicitly prefixed with `& `
                DESCENDANT
            }
        }
        Some(index) if index == compounds.len() - 1 => SELF,
        Some(index) => {
            if combinators[index] == " " || combinators[index] == ">" {
                DESCENDANT
            } else {
                OUTSIDE
            }
        }
    }
}

/// serialize a declaration of a mixin body. the declaration is left as is when it references an invalid variable
fn serialize_declaration(arena: &AstArena, declaration: u32, scope: &Rc<MixinScope>) -> String {
    let name = arena.resolve_string(arena.name.get(declaration));
    let custom = arena.starts_with(declaration, "nam", "--");
    if let Some(registry) = &scope.application.registry {
        registry.custom_property.set(custom);
    }
    let tokens = arena.tokens(declaration);
    // a custom property is inherited by the descendants: a typed argument is the value computed on the element
    let value = substitute(arena, &tokens, &as_scope(scope), scope.descendant() || custom);
    format!("{}:{}", name, value.unwrap_or_else(|| render(arena, &tokens)))
}

/// serialize an `@apply` rule of a mixin body. its arguments may reference the private variables
fn serialize_apply(arena: &AstArena, node: u32, scope: &Rc<MixinScope>) -> String {
    let tokens = arena.tokens(node);
    let prelude = match first_token(arena, &tokens).filter(|&r| arena.data_types.get(r) == EnumToken::CustomFunctionTokenType) {
        Some(reference) => {
            // the arguments are substituted one by one: an invalid argument is kept
            let dyn_scope = as_scope(scope);
            let args: Vec<String> = split_arguments(arena, &arena.tokens(reference))
                .iter()
                .map(|arg| substitute(arena, arg, &dyn_scope, scope.descendant()).unwrap_or_else(|| render(arena, arg)))
                .collect();
            format!("{}({})", arena.resolve_string(arena.string_value.get(reference)), args.join(","))
        }
        None => render(arena, trim(arena, &tokens)),
    };
    let block = if arena.flags.get(node) & EnumAstNodeStatus::HasChildren != 0 {
        format!("{{{}}}", serialize_declarations(arena, node, scope))
    } else {
        ";".to_string()
    };
    format!("@apply {}{}", prelude, block)
}

/// serialize the declarations of a contents block
fn serialize_declarations(arena: &AstArena, node: u32, scope: &Rc<MixinScope>) -> String {
    let mut result = String::new();
    let mut child = arena.first_child.get(node);
    while child != 0 {
        if arena.data_types.get(child) == EnumToken::DeclarationNodeType {
            result.push_str(&serialize_declaration(arena, child, scope));
            result.push(';');
        } else if is_at_rule(arena, child, "contents") {
            // the contents block is forwarded: `@apply --mixin { @contents; }`
            result.push_str(&serialize_contents(arena, child, scope));
        }
        child = arena.next_sibling.get(child);
    }
    result
}

/// serialize a `@contents` rule: the contents block of the `@apply` rule, otherwise the default contents block
fn serialize_contents(arena: &AstArena, node: u32, scope: &Rc<MixinScope>) -> String {
    if let Some(contents) = &scope.application.contents {
        return contents.clone();
    }
    if arena.flags.get(node) & EnumAstNodeStatus::HasChildren != 0 {
        serialize_declarations(arena, node, scope)
    } else {
        String::new()
    }
}

/// serialize a nested rule of a mixin body. the rule is split when its selectors do not have the same relation to the
/// rule the mixin is applied to
fn serialize_rule(arena: &AstArena, rule: u32, scope: &Rc<MixinScope>) -> String {
    // insertion ordered groups of selectors by relation
    let mut groups: Vec<(u8, Vec<String>)> = Vec::new();
    let merge = !has_nested_rules(arena, rule) && scope.application.typed.borrow().is_empty();
    for parts in split_rule(&arena.resolve_string(arena.name.get(rule))) {
        let mut relation = selector_relation(&parts);
        if merge && relation == DESCENDANT {
            relation = SELF;
        }
        match groups.iter_mut().find(|(r, _)| *r == relation) {
            Some((_, list)) => list.push(parts.concat()),
            None => groups.push((relation, vec![parts.concat()])),
        }
    }
    let mut masked = HashSet::default();
    collect_masked(arena, rule, &mut masked);
    let mut result = String::new();
    for (relation, selectors) in groups {
        let child = scope.child(relation, &masked);
        declare_privates(arena, rule, &child);
        result.push_str(&format!("{}{{{}}}", selectors.join(","), serialize_block(arena, rule, &child)));
    }
    result
}

/// serialize the children of a mixin body, a nested rule or a nested at-rule
fn serialize_block(arena: &AstArena, node: u32, scope: &Rc<MixinScope>) -> String {
    let mut result = String::new();
    let mut child = arena.first_child.get(node);
    while child != 0 {
        match arena.data_types.get(child) {
            EnumToken::DeclarationNodeType => {
                result.push_str(&serialize_declaration(arena, child, scope));
                result.push(';');
            }
            EnumToken::RuleNodeType => result.push_str(&serialize_rule(arena, child, scope)),
            EnumToken::AtRuleNodeType => {
                let name = arena.name.get(child);
                if arena.string_equals(name, "private") {
                    // the private variables are substituted
                } else if arena.string_equals(name, "apply") {
                    result.push_str(&serialize_apply(arena, child, scope));
                } else if arena.string_equals(name, "result") {
                    // the content of `@result` is the result of the mixin
                    result.push_str(&serialize_block(arena, child, scope));
                } else if arena.string_equals(name, "contents") {
                    result.push_str(&serialize_contents(arena, child, scope));
                } else {
                    let prelude = arena.resolve_string(arena.string_value.get(child));
                    result.push('@');
                    result.push_str(&arena.resolve_string(name));
                    if !prelude.is_empty() {
                        result.push(' ');
                        result.push_str(&prelude);
                    }
                    if arena.flags.get(child) & EnumAstNodeStatus::HasChildren != 0 {
                        result.push('{');
                        result.push_str(&serialize_block(arena, child, scope));
                        result.push('}');
                    } else {
                        result.push(';');
                    }
                }
            }
            _ => {}
        }
        child = arena.next_sibling.get(child);
    }
    result
}

/// the generated nodes are located at the `@apply` rule
fn locate(arena: &AstArena, node: u32, location: u32) {
    arena.copy_location(node, location);
    if arena.flags.get(node) & EnumAstNodeStatus::HasChildren != 0 {
        let mut child = arena.first_child.get(node);
        while child != 0 {
            locate(arena, child, location);
            child = arena.next_sibling.get(child);
        }
    }
}

/// parse a mixin definition. `None` if the prelude is not valid
fn parse_mixin(arena: &AstArena, node: u32) -> Option<MixinDefinition> {
    let reference = first_token(arena, &arena.tokens(node))?;
    let parameters = match arena.data_types.get(reference) {
        EnumToken::CustomFunctionTokenType => parse_parameters(arena, reference)?,
        EnumToken::DashedIdenTokenType => Vec::new(),
        _ => return None,
    };
    Some(MixinDefinition { node, parameters })
}

/// parse the prelude of an `@apply` rule: the name of the mixin and the arguments
fn parse_apply(arena: &AstArena, node: u32) -> Option<(String, Vec<Vec<u32>>)> {
    let reference = first_token(arena, &arena.tokens(node))?;
    let name = arena.resolve_string(arena.string_value.get(reference)).to_string();
    match arena.data_types.get(reference) {
        EnumToken::DashedIdenTokenType => Some((name, Vec::new())),
        EnumToken::CustomFunctionTokenType => Some((name, parse_arguments(arena, reference))),
        _ => None,
    }
}

/// bind the arguments to the mixin parameters. false when the arguments do not match the parameters
fn bind_parameters(arena: &AstArena, definition: &MixinDefinition, args: &[Vec<u32>], caller: &Rc<MixinScope>, scope: &Rc<MixinScope>, options: &ParserOptions) -> bool {
    let application = &scope.application;
    if args.len() > definition.parameters.len() {
        return false;
    }
    let caller_scope = as_scope(caller);
    let body_scope = as_scope(scope);
    for (index, parameter) in definition.parameters.iter().enumerate() {
        let entry = if index < args.len() {
            // `{ tokens: null, text, scope }`: the value is resolved
            let entry = VariableEntry::resolved(substitute(arena, &args[index], &caller_scope, false));
            entry.borrow_mut().scope = Some(Rc::downgrade(&body_scope));
            entry
        } else if let Some(default) = &parameter.default_value {
            // the default value may reference the other variables: it is resolved once the variables are declared
            VariableEntry::unresolved(default.clone(), &body_scope)
        } else {
            return false;
        };
        application.args.borrow_mut().insert(parameter.name.clone(), entry);
    }
    // the private variables may be referenced by the default values
    declare_privates(arena, definition.node, scope);
    for parameter in &definition.parameters {
        let entry = application.args.borrow().get(&parameter.name).cloned().unwrap();
        let Some(value) = resolve(arena, &entry, false) else {
            return false;
        };
        if !matches_type(arena, parameter.syntax.as_deref(), &value, options) {
            return false;
        }
        // the value of a typed argument is computed on the element the mixin is applied to
        if let Some(syntax) = &parameter.syntax {
            application.typed.borrow_mut().insert(parameter.name.clone(), TypedArgument { value, syntax: syntax.clone(), entry: None });
        }
    }
    true
}

/// create the registered custom property of a typed argument
fn register_property(arena: &AstArena, property: &RegisteredProperty) -> u32 {
    let token = arena.create_token(EnumToken::DashedIdenTokenType, TokenValue::Str(&property.name), None);
    let node = arena.create_at_rule(
        EnumToken::AtRuleNodeType,
        StrOrId::Str("property"),
        StrOrId::Str(&property.name),
        true,
        Some(&[token]),
        EnumAstNodeStatus::Validated,
        None,
    );
    let css = format!("syntax:{};inherits:true;initial-value:{}", serde_json::to_string(&property.syntax).unwrap(), property.initial_value);
    let (_, nodes) = parse_declarations(&css, Some(arena.rc()));
    arena.append_child_list(node, &nodes);
    node
}

/// true if a mixin applies itself, directly or through the mixins it applies
fn is_recursive(arena: &AstArena, name: &str, state: &mut EvaluationState, stack: &mut Vec<String>) -> bool {
    if stack.iter().any(|s| s == name) {
        return true;
    }
    if let Some(&result) = state.recursive.get(name) {
        return result;
    }
    let definitions = state.definitions.get(name).cloned().unwrap_or_default();
    let mut result = false;
    stack.push(name.to_string());
    'definitions: for definition in definitions {
        let mut walker = arena.walk(definition.node, None, false);
        while let Some(id) = walker.next(arena) {
            if id != definition.node && is_at_rule(arena, id, "apply") {
                if let Some((reference, _)) = parse_apply(arena, id) {
                    if is_recursive(arena, &reference, state, stack) {
                        result = true;
                        break 'definitions;
                    }
                }
            }
        }
    }
    stack.pop();
    // a mixin that reaches one of the mixins being checked is part of a cycle
    state.recursive.insert(name.to_string(), result);
    result
}

/// replace an `@apply` rule with the evaluated body of the mixin. `None` when the `@apply` rule is not evaluated
fn apply(arena: &AstArena, node: u32, state: &mut EvaluationState) -> Option<Vec<u32>> {
    let (name, args) = parse_apply(arena, node)?;
    // the mixins visible from the `@apply` rule
    let definitions = resolve_definitions(arena, state.definitions.get(&name), node);
    let definition = if definitions.len() == 1 { Some(definitions[0].clone()) } else { None };
    let properties = rule_properties(arena, node);
    let chain = state.chains.get(&node).cloned().unwrap_or_default();
    let usable = definition.is_some()
        && properties.is_some()
        && !is_recursive(arena, &name, state, &mut Vec::new())
        && !chain.contains(&name)
        && chain.len() < MAX_DEPTH;
    let (Some(definition), Some(properties), true) = (definition, properties, usable) else {
        // the visible definitions are kept
        for visible in &definitions {
            state.pending.insert(visible.node);
        }
        return None;
    };
    let properties = Rc::new(properties);
    let level = || vec![ScopeLevel { privates: Privates::default(), relation: SELF }];
    // the contents block is a declaration list. its variables are not private variables: they are not substituted
    let contents = if arena.flags.get(node) & EnumAstNodeStatus::HasChildren != 0 {
        let empty = MixinApplication::new(&name, Rc::new(HashMap::default()), None, None, None);
        let scope = MixinScope::new(level(), empty, Rc::new(HashSet::default()));
        Some(serialize_declarations(arena, node, &scope))
    } else {
        None
    };
    let application = MixinApplication::new(&name, properties.clone(), contents, Some(state.names.clone()), Some(state.registry.clone()));
    // the arguments are evaluated in the context of the `@apply` rule
    let caller = MixinScope::new(level(), MixinApplication::new(&name, properties, None, None, None), Rc::new(HashSet::default()));
    let mut masked = HashSet::default();
    collect_masked(arena, definition.node, &mut masked);
    let scope = MixinScope::new(level(), application.clone(), Rc::new(masked));
    if !bind_parameters(arena, &definition, &args, &caller, &scope, &state.options) {
        state.pending.insert(definition.node);
        return None;
    }
    // the custom functions called by the mixin body are evaluated in the context of the `@apply` rule
    state.registry.site.set(node);
    let failed = state.registry.failed.get();
    let mut css = serialize_block(arena, definition.node, &scope);
    // a typed argument cannot be registered, or a custom function call is not evaluated
    if application.failed.get() || state.registry.failed.get() != failed {
        state.pending.insert(definition.node);
        return None;
    }
    if !application.registered.borrow().is_empty() {
        // the top level node that contains the `@apply` rule
        let mut top = node;
        while arena.parents.get(top) != state.ast && arena.parents.get(top) != 0 {
            top = arena.parents.get(top);
        }
        let mut declarations = String::new();
        for property in application.registered.borrow().iter() {
            let registered = register_property(arena, property);
            locate(arena, registered, node);
            arena.insert_before(top, &[registered]);
            // the value is computed on the element the mixin is applied to
            declarations.push_str(&format!("{}:{};", property.name, property.value));
        }
        css = declarations + &css;
    }
    // the body is parsed as the content of the rule the mixin is applied to: '&' is that rule
    let nodes = parse_rule_content(&css, arena.rc(), state.options.parse_color);
    let mut nested = chain;
    nested.push(name);
    for &child in &nodes {
        locate(arena, child, node);
        arena.insert_before(node, &[child]);
        // the `@apply` rules of the mixin body
        let mut walker = arena.walk(child, None, false);
        while let Some(id) = walker.next(arena) {
            if is_at_rule(arena, id, "apply") {
                state.chains.insert(id, nested.clone());
            }
        }
    }
    arena.detach(node);
    Some(nodes)
}

/// the definitions that are kept: the referenced definitions that are not evaluated, the functions that are not
/// called, and the definitions referenced by them
fn kept_definitions(arena: &AstArena, state: &EvaluationState, registry: &FunctionRegistry) -> HashSet<u32> {
    let mut kept: HashSet<u32> = state.pending.iter().chain(registry.pending.borrow().iter()).copied().collect();
    let mut queue: Vec<u32> = kept.iter().copied().collect();
    for definitions in registry.definitions.values() {
        for definition in definitions {
            if !registry.evaluated.borrow().contains(&definition.node) && kept.insert(definition.node) {
                queue.push(definition.node);
            }
        }
    }
    queue.extend(state.invalid.iter().copied());
    while let Some(node) = queue.pop() {
        let mut referenced: Vec<u32> = Vec::new();
        let mut walker = arena.walk(node, None, false);
        while let Some(id) = walker.next(arena) {
            if id != node && is_at_rule(arena, id, "apply") {
                if let Some((reference, _)) = parse_apply(arena, id) {
                    referenced.extend(resolve_definitions(arena, state.definitions.get(&reference), id).iter().map(|d| d.node));
                }
            }
            for call in find_calls(arena, &arena.tokens(id)) {
                let name = arena.resolve_string(arena.string_value.get(call));
                referenced.extend(resolve_definitions(arena, registry.definitions.get(&name), id).iter().map(|d| d.node));
            }
        }
        for definition in referenced {
            if kept.insert(definition) {
                queue.push(definition);
            }
        }
    }
    kept
}

/// evaluate the mixins and the custom functions of a stylesheet (`EvaluateMixinFeature.evaluate()`)
pub fn evaluate_mixins(arena: &AstArena, ast: u32, options: &ParserOptions) {
    let mut invalid_mixins: Vec<u32> = Vec::new();
    let mut invalid_functions: Vec<u32> = Vec::new();
    let mut functions = JsMap::new();
    collect_definitions(arena, ast, "function", &parse_function, &mut functions, &mut invalid_functions);
    let registry = FunctionRegistry::new(functions, options);
    let mut mixins = JsMap::new();
    collect_definitions(arena, ast, "mixin", &parse_mixin, &mut mixins, &mut invalid_mixins);
    let mut state = EvaluationState {
        definitions: mixins,
        invalid: invalid_mixins.clone(),
        pending: HashSet::default(),
        chains: HashMap::default(),
        recursive: HashMap::default(),
        ast,
        registry: registry.clone(),
        names: Rc::new(RefCell::new(HashSet::default())),
        options: options.clone(),
    };
    // the custom functions that are not valid are dropped
    for &node in &invalid_functions {
        arena.detach(node);
    }
    if state.definitions.is_empty() && registry.definitions.is_empty() {
        return;
    }
    if !state.definitions.is_empty() {
        let mut walker = arena.walk(ast, None, false);
        while let Some(id) = walker.next(arena) {
            if is_custom_property(arena, id) {
                state.names.borrow_mut().insert(arena.resolve_string(arena.name.get(id)).to_string());
            } else if is_at_rule(arena, id, "property") {
                state.names.borrow_mut().insert(arena.resolve_string(arena.string_value.get(id)).trim().to_string());
            }
        }
        // depth first traversal, in document order
        let mut stack: Vec<u32> = Vec::new();
        let mut child = arena.last_child.get(ast);
        while child != 0 {
            stack.push(child);
            child = arena.previous_sibling.get(child);
        }
        while let Some(node) = stack.pop() {
            if arena.data_types.get(node) == EnumToken::AtRuleNodeType {
                // the mixin and the function bodies are evaluated when they are used
                if is_at_rule(arena, node, "mixin") || is_at_rule(arena, node, "function") {
                    continue;
                }
                if is_at_rule(arena, node, "apply") {
                    if let Some(nodes) = apply(arena, node, &mut state) {
                        // the mixin body may apply other mixins
                        stack.extend(nodes.iter().rev());
                        continue;
                    }
                }
            }
            if arena.flags.get(node) & EnumAstNodeStatus::HasChildren != 0 {
                let mut child = arena.last_child.get(node);
                while child != 0 {
                    stack.push(child);
                    child = arena.previous_sibling.get(child);
                }
            }
        }
    }
    // the custom function calls, including the calls of the evaluated mixins
    if !registry.definitions.is_empty() {
        evaluate_functions(arena, ast, &registry);
    }
    let kept = kept_definitions(arena, &state, &registry);
    let keep = options.keep_mixins == Some(true);
    finalize_definitions(arena, ast, "mixin", &kept, keep, &invalid_mixins);
    finalize_definitions(arena, ast, "function", &kept, keep, &[]);
}

/// evaluate the css mixins and the custom functions (`EvaluateMixinFeature`)
pub struct EvaluateMixinFeature;

const ACCEPT: [u8; 1] = [EnumToken::StyleSheetNodeType];

impl EvaluateMixinFeature {
    pub fn register(options: &ParserOptions, features: &mut Vec<SharedFeature>) {
        if options.evaluate_mixins == Some(true) {
            features.push(Rc::new(RefCell::new(EvaluateMixinFeature)));
        }
    }
}

impl MinifyFeature for EvaluateMixinFeature {
    fn accept(&self) -> Option<&[u8]> {
        Some(&ACCEPT)
    }

    fn ordering(&self) -> i32 {
        0
    }

    fn process_mode(&self) -> u32 {
        FeatureWalkMode::Pre
    }

    fn run(&mut self, arena: &AstArena, ast: u32, options: &ParserOptions, _parent: u32, _context: &mut MinifyContext, _mode: u32) -> FeatureResult {
        evaluate_mixins(arena, ast, options);
        FeatureResult::None
    }
}