accent_sass_compiler 0.16.0

Internal implementation of the accent-sass 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
use std::{
    collections::HashSet,
    fmt::{self, Display, Write},
    hash::{Hash, Hasher},
    sync::atomic::{AtomicU32, Ordering as AtomicOrdering},
};

use codemap::Span;

use crate::error::SassResult;

use super::{CompoundSelector, Pseudo, SelectorList, SimpleSelector, Specificity};

pub(crate) static COMPLEX_SELECTOR_UNIQUE_ID: AtomicU32 = AtomicU32::new(0);

#[derive(Clone, Debug)]
pub(crate) struct ComplexSelectorHashSet(HashSet<u32>);

impl ComplexSelectorHashSet {
    pub fn new() -> Self {
        Self(HashSet::new())
    }

    pub fn insert(&mut self, complex: &ComplexSelector) -> bool {
        self.0.insert(complex.unique_id)
    }

    pub fn contains(&self, complex: &ComplexSelector) -> bool {
        self.0.contains(&complex.unique_id)
    }

    pub fn extend<'a>(&mut self, complexes: impl Iterator<Item = &'a ComplexSelector>) {
        self.0.extend(complexes.map(|complex| complex.unique_id));
    }
}

/// A complex selector.
///
/// A complex selector is composed of `CompoundSelector`s separated by
/// `Combinator`s. It selects elements based on their parent selectors.
#[derive(Clone, Debug)]
pub(crate) struct ComplexSelector {
    /// The components of this selector.
    ///
    /// This is never empty.
    ///
    /// Descendant combinators aren't explicitly represented here. If two
    /// `CompoundSelector`s are adjacent to one another, there's an implicit
    /// descendant combinator between them.
    ///
    /// It's possible for multiple `Combinator`s to be adjacent to one another.
    /// This isn't valid CSS, but Sass supports it for CSS hack purposes.
    pub components: Vec<ComplexSelectorComponent>,

    /// Whether a line break should be emitted *before* this selector.
    pub line_break: bool,

    /// Where this selector was written, for a warning that points at it.
    ///
    /// Set by the parser and kept when a parent selector is resolved into it,
    /// so a nested `a >` points at `a >` even though the selector is now
    /// `.x a >`. `None` for a selector built some other way, such as by
    /// `@extend`. Not part of equality or hashing.
    pub span: Option<Span>,

    /// A unique identifier for this complex selector. Used to perform a pointer
    /// equality check, like would be done for objects in a language like JavaScript
    /// or dart
    unique_id: u32,
}

impl PartialEq for ComplexSelector {
    fn eq(&self, other: &Self) -> bool {
        self.components == other.components
    }
}

impl Eq for ComplexSelector {}

impl Hash for ComplexSelector {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.components.hash(state);
    }
}

impl fmt::Display for ComplexSelector {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut last_component = None;

        for component in &self.components {
            if let Some(c) = last_component
                && !omit_spaces_around(c)
                && !omit_spaces_around(component)
            {
                f.write_char(' ')?;
            }
            write!(f, "{}", component)?;
            last_component = Some(component);
        }
        Ok(())
    }
}

/// When `style` is `OutputStyle::compressed`, omit spaces around combinators.
fn omit_spaces_around(component: &ComplexSelectorComponent) -> bool {
    // todo: compressed
    let is_compressed = false;
    is_compressed && matches!(component, ComplexSelectorComponent::Combinator(..))
}

impl ComplexSelector {
    pub fn new(components: Vec<ComplexSelectorComponent>, line_break: bool) -> Self {
        Self {
            components,
            line_break,
            span: None,
            unique_id: COMPLEX_SELECTOR_UNIQUE_ID.fetch_add(1, AtomicOrdering::Relaxed),
        }
    }

    /// Returns this selector with `span` recorded as where it was written.
    #[must_use]
    pub fn with_span(mut self, span: Option<Span>) -> Self {
        self.span = span;
        self
    }

    /// Whether this selector starts with a combinator, as `> a` does.
    pub fn has_leading_combinator(&self) -> bool {
        self.components
            .first()
            .is_some_and(ComplexSelectorComponent::is_combinator)
    }

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

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

    pub fn specificity(&self) -> Specificity {
        let mut min = 0;
        let mut max = 0;
        for component in &self.components {
            if let ComplexSelectorComponent::Compound(compound) = component {
                min += compound.min_specificity();
                max += compound.max_specificity();
            }
        }
        Specificity::new(min, max)
    }

    /// Whether this selector should be left out of the generated CSS.
    ///
    /// That is the case when it contains a placeholder, or when its
    /// combinators are bogus in a way that nesting cannot repair: see
    /// [`Self::is_bogus_other_than_leading_combinator`]. A single leading
    /// combinator, as in `> .c`, stays visible.
    pub fn is_invisible(&self) -> bool {
        self.is_invisible_with(true)
    }

    /// Whether this selector would be invisible even if bogus combinators
    /// were allowed: that is, whether it contains a placeholder.
    ///
    /// dart-sass's `isInvisibleOtherThanBogusCombinators`. Printing a
    /// selector as a SassScript value uses it, because dart-sass hides bogus
    /// selectors only when writing CSS: `selector.parse(":is(.a > + .b)")`
    /// keeps its argument.
    pub fn is_invisible_other_than_bogus_combinators(&self) -> bool {
        self.is_invisible_with(false)
    }

    /// [`Self::is_invisible`], counting bogus combinators as invisible only
    /// when `include_bogus` is set, at every level of nesting.
    pub(crate) fn is_invisible_with(&self, include_bogus: bool) -> bool {
        self.components
            .iter()
            .any(|component| component.is_invisible_with(include_bogus))
            || (include_bogus && self.is_bogus_other_than_leading_combinator())
    }

    /// Whether this selector is not valid CSS because of its combinators.
    ///
    /// A port of dart-sass 1.104.0's `Selector.isBogus`. It covers selectors
    /// that are only useful for nesting, such as `> .a` and `.a >`, and ones
    /// that can never match, such as `.a + ~ .b`. A bogus selector inside a
    /// selector pseudo such as `:is()` makes the outer selector bogus too.
    pub fn is_bogus(&self) -> bool {
        components_are_bogus(&self.components, true)
    }

    /// Whether this selector is bogus for any reason other than a single
    /// leading combinator.
    ///
    /// A single leading combinator is legal CSS nesting, so `> .c` is printed
    /// as written. Anything else [`Self::is_bogus`] reports makes the selector
    /// invisible, including a trailing combinator: `.b >` is only meaningful
    /// as the parent of a nested rule, and its own declarations are dropped.
    pub fn is_bogus_other_than_leading_combinator(&self) -> bool {
        components_are_bogus(&self.components, false)
    }

    /// Whether this selector is bogus and cannot be turned into valid CSS by
    /// nesting or `@extend`.
    ///
    /// A port of dart-sass 1.104.0's `Selector.isUseless`: two combinators in
    /// a row, more than one leading combinator, or a bogus selector pseudo.
    /// A useless selector may not act as an extender.
    pub fn is_useless(&self) -> bool {
        components_are_useless(&self.components)
    }

    /// Returns whether `self` is a superselector of `other`.
    ///
    /// That is, whether `self` matches every element that `other` matches, as well
    /// as possibly additional elements.
    ///
    /// A port of dart-sass 1.103.1's `complexIsSuperselector`. The walk
    /// matches each compound of `self` against the earliest compound of
    /// `other` it is a superselector of, then checks the combinators on both
    /// sides of that match. Selectors with a leading or trailing combinator,
    /// or with two combinators in a row, are never superselectors of anything
    /// and never have one.
    pub fn is_super_selector(&self, other: &Self) -> bool {
        let (Some(steps1), Some(steps2)) = (
            SuperselectorStep::split(&self.components),
            SuperselectorStep::split(&other.components),
        ) else {
            return false;
        };

        // Selectors with trailing operators are neither superselectors nor
        // subselectors.
        match (steps1.last(), steps2.last()) {
            (Some(last1), Some(last2))
                if last1.combinators.is_empty() && last2.combinators.is_empty() => {}
            _ => return false,
        }

        // The components of `other` from step `from` up to, not including,
        // step `to`, with the combinators that follow each one: the parents a
        // selector pseudo in `self` may need to see. dart-sass passes them
        // only to compounds whose superselector semantics depend on them.
        let parents = |compound1: &CompoundSelector, from: usize, to: usize| {
            compound1
                .has_complicated_superselector_semantics()
                .then(|| other.components[steps2[from].start..steps2[to].start].to_vec())
        };

        let mut i1 = 0;
        let mut i2 = 0;
        let mut previous_combinator: Option<Combinator> = None;

        loop {
            let remaining1 = steps1.len() - i1;
            let remaining2 = steps2.len() - i2;
            if remaining1 == 0 || remaining2 == 0 {
                return false;
            }

            // More complex selectors are never superselectors of less complex
            // ones.
            if remaining1 > remaining2 {
                return false;
            }

            let component1 = &steps1[i1];
            if component1.combinators.len() > 1 {
                return false;
            }

            if remaining1 == 1 {
                if steps2.iter().any(|parent| parent.combinators.len() > 1) {
                    return false;
                }
                let last = steps2.len() - 1;
                return component1.compound.is_super_selector(
                    steps2[last].compound,
                    &parents(component1.compound, i2, last),
                );
            }

            // Find the first step `end` of `other` such that the steps from
            // `i2` through `end` are a subselector of `component1`.
            let mut end = i2;
            loop {
                let component2 = &steps2[end];
                if component2.combinators.len() > 1 {
                    return false;
                }
                if component1
                    .compound
                    .is_super_selector(component2.compound, &parents(component1.compound, i2, end))
                {
                    break;
                }

                end += 1;
                if end == steps2.len() - 1 {
                    // Stop before the superselector would encompass all of
                    // `other`: `self` has more than one step left, and
                    // consuming all of `other` would leave nothing for the
                    // rest of it to match.
                    return false;
                }
            }

            if !compatible_with_previous_combinator(previous_combinator, &steps2[i2..end]) {
                return false;
            }

            let combinator1 = component1.combinators.first().copied();
            let combinator2 = steps2[end].combinators.first().copied();
            if !is_supercombinator(combinator1, combinator2) {
                return false;
            }

            i1 += 1;
            i2 = end + 1;
            previous_combinator = combinator1;

            if steps1.len() - i1 == 1 {
                let rejected = match combinator1 {
                    // `.foo ~ .bar` is only a superselector of selectors that
                    // *exclusively* contain subcombinators of `~`.
                    Some(Combinator::FollowingSibling) => {
                        !steps2[i2..steps2.len() - 1].iter().all(|component| {
                            is_supercombinator(combinator1, component.combinators.first().copied())
                        })
                    }
                    // `.foo > .bar` and `.foo + .bar` aren't superselectors of
                    // any selectors with more than one combinator.
                    Some(_) => steps2.len() - i2 > 1,
                    None => false,
                };
                if rejected {
                    return false;
                }
            }
        }
    }

    pub fn contains_parent_selector(&self) -> bool {
        self.components.iter().any(|c| {
            if let ComplexSelectorComponent::Compound(compound) = c {
                compound.components.iter().any(|simple| {
                    if simple.is_parent() {
                        return true;
                    }
                    if let SimpleSelector::Pseudo(Pseudo {
                        selector: Some(sel),
                        ..
                    }) = simple
                    {
                        return sel.contains_parent_selector();
                    }
                    false
                })
            } else {
                false
            }
        })
    }

    /// Whether this contains a parent selector that carries a suffix, such as
    /// the `&--x` in `&--x .y`.
    ///
    /// A bare `&` can stand on its own with no parent -- the browser resolves
    /// it as the CSS nesting selector -- but a suffix has nothing to attach
    /// itself to, so dart-sass reports the two cases differently. Searches
    /// inside a pseudo-selector's argument as well, because `:is(&--x)` is an
    /// error too.
    pub fn contains_suffixed_parent_selector(&self) -> bool {
        self.components.iter().any(|c| {
            if let ComplexSelectorComponent::Compound(compound) = c {
                compound.components.iter().any(|simple| match simple {
                    SimpleSelector::Parent(suffix) => suffix.is_some(),
                    SimpleSelector::Pseudo(Pseudo {
                        selector: Some(sel),
                        ..
                    }) => sel.contains_suffixed_parent_selector(),
                    _ => false,
                })
            } else {
                false
            }
        })
    }
}

/// Whether the complex selector made of `components` is bogus.
///
/// Shared by [`ComplexSelector::is_bogus`] and
/// [`ComplexSelector::is_bogus_other_than_leading_combinator`], and taking a
/// slice so the extend machinery can ask about a selector it holds only as
/// components. With `include_leading_combinator` false, one leading
/// combinator is allowed; more than one is still bogus. A selector that is
/// nothing but combinators, such as `+`, is always bogus.
pub(crate) fn components_are_bogus(
    components: &[ComplexSelectorComponent],
    include_leading_combinator: bool,
) -> bool {
    let leading = components
        .iter()
        .take_while(|component| component.is_combinator())
        .count();
    if leading == components.len() {
        return leading > 0;
    }

    leading > usize::from(!include_leading_combinator)
        || components
            .last()
            .is_some_and(ComplexSelectorComponent::is_combinator)
        || has_adjacent_combinators(components)
        || has_bogus_simple(components)
}

/// Whether the complex selector made of `components` is useless: see
/// [`ComplexSelector::is_useless`].
///
/// More than one leading combinator is a pair of adjacent combinators, so
/// [`has_adjacent_combinators`] covers it along with a pair in the middle.
pub(crate) fn components_are_useless(components: &[ComplexSelectorComponent]) -> bool {
    has_adjacent_combinators(components) || has_bogus_simple(components)
}

/// Whether two combinators follow each other anywhere in `components`.
fn has_adjacent_combinators(components: &[ComplexSelectorComponent]) -> bool {
    components
        .windows(2)
        .any(|pair| pair[0].is_combinator() && pair[1].is_combinator())
}

/// Whether any compound in `components` holds a selector pseudo whose
/// argument is bogus.
fn has_bogus_simple(components: &[ComplexSelectorComponent]) -> bool {
    components.iter().any(|component| match component {
        ComplexSelectorComponent::Compound(compound) => {
            compound.components.iter().any(SimpleSelector::is_bogus)
        }
        ComplexSelectorComponent::Combinator(..) => false,
    })
}

/// One compound selector of a complex selector with the combinators written
/// after it.
///
/// This is the unit dart-sass's `ComplexSelectorComponent` holds, and the one
/// its superselector algorithm walks. This compiler stores compounds and
/// combinators interleaved instead, so [`ComplexSelector::is_super_selector`]
/// regroups them rather than rewriting the algorithm around the difference.
struct SuperselectorStep<'a> {
    compound: &'a CompoundSelector,
    combinators: Vec<Combinator>,
    /// The index of `compound` in the interleaved components, so a run of
    /// steps can be sliced back out of them.
    start: usize,
}

impl<'a> SuperselectorStep<'a> {
    /// Groups `components` into steps.
    ///
    /// Returns `None` when `components` begins with a combinator: dart-sass
    /// never treats a selector with leading combinators as a superselector or
    /// a subselector.
    fn split(components: &'a [ComplexSelectorComponent]) -> Option<Vec<Self>> {
        let mut steps: Vec<Self> = Vec::new();
        for (start, component) in components.iter().enumerate() {
            match component {
                ComplexSelectorComponent::Compound(compound) => steps.push(Self {
                    compound,
                    combinators: Vec::new(),
                    start,
                }),
                ComplexSelectorComponent::Combinator(combinator) => {
                    steps.last_mut()?.combinators.push(*combinator);
                }
            }
        }
        Some(steps)
    }
}

/// Whether a match that skipped the steps `parents` can follow a previous
/// match joined to it by `previous`.
///
/// The child and next-sibling combinators need the *immediately* following
/// compound to match, so nothing may be skipped after them. The following
/// sibling combinator allows skipped compounds, but only siblings.
fn compatible_with_previous_combinator(
    previous: Option<Combinator>,
    parents: &[SuperselectorStep<'_>],
) -> bool {
    if parents.is_empty() {
        return true;
    }
    match previous {
        None => true,
        Some(Combinator::FollowingSibling) => parents.iter().all(|component| {
            matches!(
                component.combinators.first(),
                Some(Combinator::FollowingSibling | Combinator::NextSibling)
            )
        }),
        Some(_) => false,
    }
}

/// Whether `combinator1` matches everything `combinator2` does, where `None`
/// is the descendant combinator.
fn is_supercombinator(combinator1: Option<Combinator>, combinator2: Option<Combinator>) -> bool {
    combinator1 == combinator2
        || (combinator1.is_none() && combinator2 == Some(Combinator::Child))
        || (combinator1 == Some(Combinator::FollowingSibling)
            && combinator2 == Some(Combinator::NextSibling))
}

#[derive(Clone, Debug, Eq, PartialEq, Copy, Hash)]
pub(crate) enum Combinator {
    /// Matches the right-hand selector if it's immediately adjacent to the
    /// left-hand selector in the DOM tree.
    ///
    /// `'+'`
    NextSibling,

    /// Matches the right-hand selector if it's a direct child of the left-hand
    /// selector in the DOM tree.
    ///
    /// `'>'`
    Child,

    /// Matches the right-hand selector if it comes after the left-hand selector
    /// in the DOM tree.
    ///
    /// `'~'`
    FollowingSibling,
}

impl Display for Combinator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_char(match self {
            Self::NextSibling => '+',
            Self::Child => '>',
            Self::FollowingSibling => '~',
        })
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub(crate) enum ComplexSelectorComponent {
    Combinator(Combinator),
    Compound(CompoundSelector),
}

impl ComplexSelectorComponent {
    /// Whether this component hides its complex selector: see
    /// [`ComplexSelector::is_invisible_with`]. A combinator never does.
    pub fn is_invisible_with(&self, include_bogus: bool) -> bool {
        match self {
            Self::Combinator(..) => false,
            Self::Compound(c) => c.is_invisible_with(include_bogus),
        }
    }

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

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

    pub fn resolve_parent_selectors(
        self,
        span: Span,
        parent: SelectorList,
    ) -> SassResult<Option<Vec<ComplexSelector>>> {
        match self {
            Self::Compound(c) => c.resolve_parent_selectors(span, parent),
            Self::Combinator(..) => todo!(),
        }
    }

    pub fn as_compound(&self) -> &CompoundSelector {
        match self {
            Self::Compound(c) => c,
            Self::Combinator(..) => unreachable!(),
        }
    }
}

impl Display for ComplexSelectorComponent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Compound(c) => write!(f, "{}", c),
            Self::Combinator(c) => write!(f, "{}", c),
        }
    }
}