grass_compiler 0.13.4

Internal implementation of the grass compiler
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
use std::{
    fmt::{self, Write},
    hash::{Hash, Hasher},
};

use codemap::Span;

use crate::{common::unvendor, error::SassResult};

use super::{
    Attribute, ComplexSelector, ComplexSelectorComponent, CompoundSelector, Namespace,
    QualifiedName, SelectorList, Specificity,
};

const SUBSELECTOR_PSEUDOS: [&str; 6] = [
    "matches",
    "where",
    "is",
    "any",
    "nth-child",
    "nth-last-child",
];

const BASE_SPECIFICITY: i32 = 1000;

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub(crate) enum SimpleSelector {
    /// *
    Universal(Namespace),

    /// A pseudo-class or pseudo-element selector.
    ///
    /// The semantics of a specific pseudo selector depends on its name. Some
    /// selectors take arguments, including other selectors. Sass manually encodes
    /// logic for each pseudo selector that takes a selector as an argument, to
    /// ensure that extension and other selector operations work properly.
    Pseudo(Pseudo),

    /// A type selector.
    ///
    /// This selects elements whose name equals the given name.
    Type(QualifiedName),

    /// A placeholder selector.
    ///
    /// This doesn't match any elements. It's intended to be extended using
    /// `@extend`. It's not a plain CSS selector—it should be removed before
    /// emitting a CSS document.
    Placeholder(String),

    /// A selector that matches the parent in the Sass stylesheet.
    /// `&`
    ///
    /// This is not a plain CSS selector—it should be removed before emitting a CSS
    /// document.
    ///
    /// The parameter is the suffix that will be added to the parent selector after
    /// it's been resolved.
    ///
    /// This is assumed to be a valid identifier suffix. It may be `None`,
    /// indicating that the parent selector will not be modified.
    Parent(Option<String>),

    Id(String),

    /// A class selector.
    ///
    /// This selects elements whose `class` attribute contains an identifier with
    /// the given name.
    Class(String),

    Attribute(Box<Attribute>),
}

impl fmt::Display for SimpleSelector {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Id(name) => write!(f, "#{}", name),
            Self::Class(name) => write!(f, ".{}", name),
            Self::Placeholder(name) => write!(f, "%{}", name),
            Self::Universal(namespace) => write!(f, "{}*", namespace),
            Self::Pseudo(pseudo) => write!(f, "{}", pseudo),
            Self::Type(name) => write!(f, "{}", name),
            Self::Attribute(attr) => write!(f, "{}", attr),
            Self::Parent(..) => unreachable!("It should not be possible to format `&`."),
        }
    }
}

impl SimpleSelector {
    /// The minimum possible specificity that this selector can have.
    ///
    /// Pseudo selectors that contain selectors, like `:not()` and `:matches()`,
    /// can have a range of possible specificities.
    ///
    /// Specifity is represented in base 1000. The spec says this should be
    /// "sufficiently high"; it's extremely unlikely that any single selector
    /// sequence will contain 1000 simple selectors.
    pub fn min_specificity(&self) -> i32 {
        match self {
            Self::Universal(..) => 0,
            Self::Type(..) => 1,
            Self::Pseudo(pseudo) => pseudo.min_specificity(),
            Self::Id(..) => BASE_SPECIFICITY.pow(2_u32),
            _ => BASE_SPECIFICITY,
        }
    }

    /// The maximum possible specificity that this selector can have.
    ///
    /// Pseudo selectors that contain selectors, like `:not()` and `:matches()`,
    /// can have a range of possible specificities.
    pub fn max_specificity(&self) -> i32 {
        match self {
            Self::Universal(..) => 0,
            Self::Pseudo(pseudo) => pseudo.max_specificity(),
            _ => self.min_specificity(),
        }
    }

    pub fn is_invisible(&self) -> bool {
        match self {
            Self::Universal(..)
            | Self::Type(..)
            | Self::Id(..)
            | Self::Class(..)
            | Self::Attribute(..) => false,
            Self::Pseudo(Pseudo { name, selector, .. }) => {
                name != "not" && selector.as_ref().map_or(false, |sel| sel.is_invisible())
            }
            Self::Placeholder(..) => true,
            Self::Parent(..) => unreachable!("parent selectors should be resolved at this point"),
        }
    }

    pub fn add_suffix(&mut self, suffix: &str, span: Span) -> SassResult<()> {
        match self {
            Self::Type(name) => name.ident.push_str(suffix),
            Self::Placeholder(name)
            | Self::Id(name)
            | Self::Class(name)
            | Self::Pseudo(Pseudo {
                name,
                argument: None,
                selector: None,
                ..
            }) => name.push_str(suffix),
            // todo: add test for this?
            _ => return Err((format!("Invalid parent selector \"{}\"", self), span).into()),
        };
        Ok(())
    }

    pub fn is_universal(&self) -> bool {
        matches!(self, Self::Universal(..))
    }

    pub fn is_pseudo(&self) -> bool {
        matches!(self, Self::Pseudo { .. })
    }

    pub fn is_parent(&self) -> bool {
        matches!(self, Self::Parent(..))
    }

    pub fn is_id(&self) -> bool {
        matches!(self, Self::Id(..))
    }

    pub fn is_type(&self) -> bool {
        matches!(self, Self::Type(..))
    }

    pub fn unify(self, compound: Vec<Self>) -> Option<Vec<Self>> {
        match self {
            Self::Type(..) => self.unify_type(compound),
            Self::Universal(..) => self.unify_universal(compound),
            Self::Pseudo { .. } => self.unify_pseudo(compound),
            Self::Id(..) => {
                if compound
                    .iter()
                    .any(|simple| simple.is_id() && simple != &self)
                {
                    return None;
                }

                self.unify_default(compound)
            }
            _ => self.unify_default(compound),
        }
    }

    /// Returns the components of a `CompoundSelector` that matches only elements
    /// matched by both this and `compound`.
    ///
    /// By default, this just returns a copy of `compound` with this selector
    /// added to the end, or returns the original array if this selector already
    /// exists in it.
    ///
    /// Returns `None` if unification is impossible—for example, if there are
    /// multiple ID selectors.
    fn unify_default(self, mut compound: Vec<Self>) -> Option<Vec<Self>> {
        if compound.len() == 1 && compound[0].is_universal() {
            return compound.swap_remove(0).unify(vec![self]);
        }
        if compound.contains(&self) {
            return Some(compound);
        }
        let mut result: Vec<SimpleSelector> = Vec::new();
        let mut added_this = false;
        for simple in compound {
            if !added_this && simple.is_pseudo() {
                result.push(self.clone());
                added_this = true;
            }
            result.push(simple);
        }

        if !added_this {
            result.push(self);
        }

        Some(result)
    }

    fn unify_universal(self, mut compound: Vec<Self>) -> Option<Vec<Self>> {
        if let Self::Universal(..) | Self::Type(..) = compound[0] {
            let mut unified = vec![self.unify_universal_and_element(&compound[0])?];
            unified.extend(compound.into_iter().skip(1));
            return Some(unified);
        }

        if self != Self::Universal(Namespace::Asterisk) && self != Self::Universal(Namespace::None)
        {
            let mut v = vec![self];
            v.append(&mut compound);
            return Some(v);
        }

        if !compound.is_empty() {
            return Some(compound);
        }

        Some(vec![self])
    }

    /// Returns a `SimpleSelector` that matches only elements that are matched by
    /// both `selector1` and `selector2`, which must both be either
    /// `SimpleSelector::Universal`s or `SimpleSelector::Type`s.
    ///
    /// If no such selector can be produced, returns `None`.
    fn unify_universal_and_element(&self, other: &Self) -> Option<Self> {
        let namespace1;
        let name1;
        if let SimpleSelector::Type(name) = self.clone() {
            namespace1 = name.namespace;
            name1 = name.ident;
        } else if let SimpleSelector::Universal(namespace) = self.clone() {
            namespace1 = namespace;
            name1 = String::new();
        } else {
            unreachable!("{:?} must be a universal selector or a type selector", self);
        }

        let namespace2;
        let mut name2 = String::new();

        if let SimpleSelector::Universal(namespace) = other {
            namespace2 = namespace.clone();
        } else if let SimpleSelector::Type(name) = other {
            namespace2 = name.namespace.clone();
            name2 = name.ident.clone();
        } else {
            unreachable!(
                "{:?} must be a universal selector or a type selector",
                other
            );
        }

        let namespace = if namespace1 == namespace2 || namespace2 == Namespace::Asterisk {
            namespace1
        } else if namespace1 == Namespace::Asterisk {
            namespace2
        } else {
            return None;
        };

        let name = if name1 == name2 || name2.is_empty() {
            name1
        } else if name1.is_empty() || name1 == "*" {
            name2
        } else {
            return None;
        };

        Some(if name.is_empty() {
            SimpleSelector::Universal(namespace)
        } else {
            SimpleSelector::Type(QualifiedName {
                namespace,
                ident: name,
            })
        })
    }

    fn unify_type(self, mut compound: Vec<Self>) -> Option<Vec<Self>> {
        if let Self::Universal(..) | Self::Type(..) = compound[0] {
            let mut unified = vec![self.unify_universal_and_element(&compound[0])?];
            unified.extend(compound.into_iter().skip(1));
            Some(unified)
        } else {
            let mut unified = vec![self];
            unified.append(&mut compound);
            Some(unified)
        }
    }

    fn unify_pseudo(self, mut compound: Vec<Self>) -> Option<Vec<Self>> {
        if compound.len() == 1 && compound[0].is_universal() {
            return compound.remove(0).unify(vec![self]);
        }
        if compound.contains(&self) {
            return Some(compound);
        }

        let mut result = Vec::new();

        let mut added_self = false;

        for simple in compound {
            if let Self::Pseudo(Pseudo {
                is_class: false, ..
            }) = simple
            {
                // A given compound selector may only contain one pseudo element. If
                // `compound` has a different one than `self`, unification fails.
                if let Self::Pseudo(Pseudo {
                    is_class: false, ..
                }) = self
                {
                    return None;
                }

                // Otherwise, this is a pseudo selector and should come before pseduo
                // elements.
                result.push(self.clone());
                added_self = true;
            }
            result.push(simple);
        }

        if !added_self {
            result.push(self);
        }

        Some(result)
    }

    pub fn is_super_selector_of_compound(&self, compound: &CompoundSelector) -> bool {
        compound.components.iter().any(|their_simple| {
            if self == their_simple {
                return true;
            }
            if let SimpleSelector::Pseudo(Pseudo {
                selector: Some(sel),
                name,
                ..
            }) = their_simple
            {
                if SUBSELECTOR_PSEUDOS.contains(&unvendor(name)) {
                    return sel.components.iter().all(|complex| {
                        if complex.components.len() != 1 {
                            return false;
                        };
                        complex
                            .components
                            .first()
                            .unwrap()
                            .as_compound()
                            .components
                            .contains(self)
                    });
                }
                false
            } else {
                false
            }
        })
    }
}

#[derive(Clone, Debug)]
pub(crate) struct Pseudo {
    /// The name of this selector.
    pub name: String,

    /// Whether this is a pseudo-class selector.
    ///
    /// If this is false, this is a pseudo-element selector
    pub is_class: bool,

    /// Whether this is syntactically a pseudo-class selector.
    ///
    /// This is the same as `is_class` unless this selector is a pseudo-element
    /// that was written syntactically as a pseudo-class (`:before`, `:after`,
    /// `:first-line`, or `:first-letter`).
    ///
    /// If this is false, it is syntactically a psuedo-element
    pub is_syntactic_class: bool,

    /// The non-selector argument passed to this selector.
    ///
    /// This is `None` if there's no argument. If `argument` and `selector` are
    /// both non-`None`, the selector follows the argument.
    pub argument: Option<Box<str>>,

    /// The selector argument passed to this selector.
    ///
    /// This is `None` if there's no selector. If `argument` and `selector` are
    /// both non-`None`, the selector follows the argument.
    pub selector: Option<Box<SelectorList>>,

    pub span: Span,
}

impl PartialEq for Pseudo {
    fn eq(&self, other: &Pseudo) -> bool {
        self.name == other.name
            && self.is_class == other.is_class
            && self.argument == other.argument
            && self.selector == other.selector
    }
}

impl Eq for Pseudo {}

impl Hash for Pseudo {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.is_class.hash(state);
        self.argument.hash(state);
        self.selector.hash(state);
    }
}

impl fmt::Display for Pseudo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(sel) = &self.selector {
            if self.name == "not" && sel.is_invisible() {
                return Ok(());
            }
        }

        f.write_char(':')?;

        if !self.is_syntactic_class {
            f.write_char(':')?;
        }

        f.write_str(&self.name)?;

        if self.argument.is_none() && self.selector.is_none() {
            return Ok(());
        }

        f.write_char('(')?;
        if let Some(arg) = &self.argument {
            f.write_str(arg)?;
            if self.selector.is_some() {
                f.write_char(' ')?;
            }
        }

        if let Some(sel) = &self.selector {
            write!(f, "{}", sel)?;
        }

        f.write_char(')')
    }
}

impl Pseudo {
    /// Returns whether `pseudo1` is a superselector of `compound2`.
    ///
    /// That is, whether `pseudo1` matches every element that `compound2` matches, as well
    /// as possibly additional elements.
    ///
    /// This assumes that `pseudo1`'s `selector` argument is not `None`.
    ///
    /// If `parents` is passed, it represents the parents of `compound`. This is
    /// relevant for pseudo selectors with selector arguments, where we may need to
    /// know if the parent selectors in the selector argument match `parents`.
    pub fn is_super_selector(
        &self,
        compound: &CompoundSelector,
        parents: Option<Vec<ComplexSelectorComponent>>,
    ) -> bool {
        debug_assert!(self.selector.is_some());
        match self.normalized_name() {
            "matches" | "is" | "any" | "where" => {
                selector_pseudos_named(compound.clone(), &self.name, true).any(move |pseudo2| {
                    self.selector
                        .as_ref()
                        .unwrap()
                        .is_superselector(&pseudo2.selector.unwrap())
                }) || self
                    .selector
                    .as_ref()
                    .unwrap()
                    .components
                    .iter()
                    .any(move |complex1| {
                        let mut components = parents.clone().unwrap_or_default();
                        components.push(ComplexSelectorComponent::Compound(compound.clone()));
                        complex1.is_super_selector(&ComplexSelector::new(components, false))
                    })
            }
            "has" | "host" | "host-context" => {
                selector_pseudos_named(compound.clone(), &self.name, true).any(|pseudo2| {
                    self.selector
                        .as_ref()
                        .unwrap()
                        .is_superselector(&pseudo2.selector.unwrap())
                })
            }
            "slotted" => {
                selector_pseudos_named(compound.clone(), &self.name, false).any(|pseudo2| {
                    self.selector
                        .as_ref()
                        .unwrap()
                        .is_superselector(pseudo2.selector.as_ref().unwrap())
                })
            }
            "not" => self
                .selector
                .as_ref()
                .unwrap()
                .components
                .iter()
                .all(|complex| {
                    compound.components.iter().any(|simple2| {
                        if let SimpleSelector::Type(..) = simple2 {
                            let compound1 = complex.components.last();
                            if let Some(ComplexSelectorComponent::Compound(c)) = compound1 {
                                c.components
                                    .iter()
                                    .any(|simple1| simple1.is_type() && simple1 != simple2)
                            } else {
                                false
                            }
                        } else if let SimpleSelector::Id(..) = simple2 {
                            let compound1 = complex.components.last();
                            if let Some(ComplexSelectorComponent::Compound(c)) = compound1 {
                                c.components
                                    .iter()
                                    .any(|simple1| simple1.is_id() && simple1 != simple2)
                            } else {
                                false
                            }
                        } else if let SimpleSelector::Pseudo(Pseudo {
                            selector: Some(sel),
                            name,
                            ..
                        }) = simple2
                        {
                            if name != &self.name {
                                return false;
                            }
                            sel.is_superselector(&SelectorList {
                                components: vec![complex.clone()],
                                span: self.span,
                            })
                        } else {
                            false
                        }
                    })
                }),
            "current" => selector_pseudos_named(compound.clone(), &self.name, self.is_class)
                .any(|pseudo2| self.selector == pseudo2.selector),
            "nth-child" | "nth-last-child" => compound.components.iter().any(|pseudo2| {
                if let SimpleSelector::Pseudo(
                    pseudo @ Pseudo {
                        selector: Some(..), ..
                    },
                ) = pseudo2
                {
                    pseudo.name == self.name
                        && pseudo.argument == self.argument
                        && self
                            .selector
                            .as_ref()
                            .unwrap()
                            .is_superselector(pseudo.selector.as_ref().unwrap())
                } else {
                    false
                }
            }),
            _ => unreachable!(),
        }
    }

    #[allow(clippy::missing_const_for_fn)]
    pub fn with_selector(self, selector: Option<Box<SelectorList>>) -> Self {
        Self { selector, ..self }
    }

    pub fn max_specificity(&self) -> i32 {
        self.specificity().max
    }

    pub fn min_specificity(&self) -> i32 {
        self.specificity().min
    }

    pub fn specificity(&self) -> Specificity {
        if !self.is_class {
            return Specificity { min: 1, max: 1 };
        }

        let selector = match &self.selector {
            Some(sel) => sel,
            None => {
                return Specificity {
                    min: BASE_SPECIFICITY,
                    max: BASE_SPECIFICITY,
                }
            }
        };

        if self.name == "not" {
            let mut min = 0;
            let mut max = 0;
            for complex in &selector.components {
                min = min.max(complex.min_specificity());
                max = max.max(complex.max_specificity());
            }
            Specificity { min, max }
        } else {
            // This is higher than any selector's specificity can actually be.
            let mut min = BASE_SPECIFICITY.pow(3_u32);
            let mut max = 0;
            for complex in &selector.components {
                min = min.min(complex.min_specificity());
                max = max.max(complex.max_specificity());
            }
            Specificity { min, max }
        }
    }

    /// Like `name`, but without any vendor prefixes.
    pub fn normalized_name(&self) -> &str {
        unvendor(&self.name)
    }
}

/// Returns all pseudo selectors in `compound` that have a selector argument,
/// and that have the given `name`.
fn selector_pseudos_named(
    compound: CompoundSelector,
    name: &str,
    is_class: bool,
) -> impl Iterator<Item = Pseudo> + '_ {
    compound
        .components
        .into_iter()
        .filter_map(|c| {
            if let SimpleSelector::Pseudo(p) = c {
                Some(p)
            } else {
                None
            }
        })
        .filter(move |p| p.is_class == is_class && p.selector.is_some() && p.name == name)
}