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
use std::{
collections::VecDeque,
fmt::{self, Write},
hash::{Hash, Hasher},
mem,
};
use codemap::Span;
use super::{ComplexSelector, ComplexSelectorComponent, unify_complex};
use crate::{
common::{Brackets, ListSeparator, QuoteKind},
error::SassResult,
value::Value,
};
/// A selector list.
///
/// A selector list is composed of `ComplexSelector`s. It matches an element
/// that matches any of the component selectors.
#[derive(Clone, Debug)]
pub(crate) struct SelectorList {
/// The components of this selector.
///
/// This is never empty.
pub components: Vec<ComplexSelector>,
pub span: Span,
}
impl PartialEq for SelectorList {
fn eq(&self, other: &SelectorList) -> bool {
self.components == other.components
}
}
impl Eq for SelectorList {}
impl Hash for SelectorList {
fn hash<H: Hasher>(&self, state: &mut H) {
self.components.hash(state);
}
}
impl fmt::Display for SelectorList {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// This prints selectors as SassScript values, such as the argument of
// `:is()` in `selector.parse()`'s result. dart-sass keeps a bogus
// selector there and drops it only from CSS, which the serializer
// writes, so only placeholders are left out.
let complexes = self
.components
.iter()
.filter(|c| !c.is_invisible_other_than_bogus_combinators());
let mut first = true;
for complex in complexes {
if first {
first = false;
} else {
f.write_char(',')?;
if complex.line_break {
f.write_char('\n')?;
} else {
f.write_char(' ')?;
}
}
write!(f, "{}", complex)?;
}
Ok(())
}
}
impl SelectorList {
pub fn is_invisible(&self) -> bool {
self.is_invisible_with(true)
}
/// Whether every complex selector in this list is invisible: see
/// [`ComplexSelector::is_invisible_with`].
pub(crate) fn is_invisible_with(&self, include_bogus: bool) -> bool {
self.components
.iter()
.all(|complex| complex.is_invisible_with(include_bogus))
}
/// Whether any complex selector in this list is bogus: see
/// [`ComplexSelector::is_bogus`].
pub fn is_bogus(&self) -> bool {
self.components.iter().any(ComplexSelector::is_bogus)
}
/// Whether any complex selector in this list is bogus for a reason other
/// than a single leading combinator: see
/// [`ComplexSelector::is_bogus_other_than_leading_combinator`].
pub fn is_bogus_other_than_leading_combinator(&self) -> bool {
self.components
.iter()
.any(ComplexSelector::is_bogus_other_than_leading_combinator)
}
pub fn contains_parent_selector(&self) -> bool {
self.components
.iter()
.any(ComplexSelector::contains_parent_selector)
}
/// Whether any selector in this list contains a parent selector with a
/// suffix. See `ComplexSelector::contains_suffixed_parent_selector`.
pub fn contains_suffixed_parent_selector(&self) -> bool {
self.components
.iter()
.any(ComplexSelector::contains_suffixed_parent_selector)
}
pub const fn new(span: Span) -> Self {
Self {
components: Vec::new(),
span,
}
}
pub fn is_empty(&self) -> bool {
self.components.is_empty()
}
/// Returns a `SassScript` list that represents this selector.
///
/// This has the same format as a list returned by `selector-parse()`.
pub fn to_sass_list(self) -> Value {
Value::List(
self.components
.into_iter()
.map(|complex| {
Value::List(
complex
.components
.into_iter()
.map(|complex_component| {
Value::String(complex_component.to_string(), QuoteKind::None)
})
.collect(),
ListSeparator::Space,
Brackets::None,
)
})
.collect(),
ListSeparator::Comma,
Brackets::None,
)
}
/// Returns a `SelectorList` that matches only elements that are matched by
/// both this and `other`.
///
/// If no such list can be produced, returns `None`.
pub fn unify(self, other: &Self) -> Option<Self> {
let contents: Vec<ComplexSelector> = self
.components
.into_iter()
.flat_map(|c1| {
other.clone().components.into_iter().flat_map(move |c2| {
let unified: Option<Vec<Vec<ComplexSelectorComponent>>> =
unify_complex(vec![c1.components.clone(), c2.components]);
if let Some(u) = unified {
u.into_iter()
.map(|c| ComplexSelector::new(c, false))
.collect()
} else {
Vec::new()
}
})
})
.collect();
if contents.is_empty() {
return None;
}
Some(Self {
components: contents,
span: self.span.merge(other.span),
})
}
/// Returns a new list with all `SimpleSelector::Parent`s replaced with `parent`.
///
/// If `implicit_parent` is true, this treats `ComplexSelector`s that don't
/// contain an explicit `SimpleSelector::Parent` as though they began with one.
///
/// If `preserve_parent_selectors` is true, `SimpleSelector::Parent`s are
/// left alone instead of being resolved, and every `ComplexSelector` is
/// treated as though it had none. This is how plain CSS is handled: there
/// `&` is the CSS nesting selector, which the browser resolves, so Sass
/// passes it through untouched.
///
/// The given `parent` may be `None`, indicating that this has no parents.
/// A `SimpleSelector::Parent` is then left in place: CSS nesting made `&`
/// meaningful to the browser, so dart-sass 1.103.1 passes a top-level one
/// through rather than rejecting it. A parent selector that carries a
/// suffix is still an error, because the suffix has nothing to attach to.
pub fn resolve_parent_selectors(
self,
parent: Option<Self>,
implicit_parent: bool,
preserve_parent_selectors: bool,
) -> SassResult<Self> {
let parent = match parent {
Some(p) => p,
None => {
if !preserve_parent_selectors && self.contains_suffixed_parent_selector() {
return Err((
"A top-level selector may not contain a parent selector with a suffix.",
self.span,
)
.into());
}
return Ok(self);
}
};
Ok(Self {
components: flatten_vertically(
self.components
.into_iter()
.map(|complex| {
if preserve_parent_selectors || !complex.contains_parent_selector() {
if !implicit_parent {
return Ok(vec![complex]);
}
return Ok(parent
.clone()
.components
.into_iter()
.map(move |parent_complex| {
let mut components = parent_complex.components;
components.append(&mut complex.components.clone());
ComplexSelector::new(
components,
complex.line_break || parent_complex.line_break,
)
.with_span(complex.span)
})
.collect());
}
// A resolved selector points where its nested part
// was written, as it does in dart-sass.
let span = complex.span;
let mut new_complexes: Vec<Vec<ComplexSelectorComponent>> =
vec![Vec::new()];
let mut line_breaks = vec![false];
for component in complex.components {
if component.is_compound() {
let resolved = match component
.clone()
.resolve_parent_selectors(self.span, parent.clone())?
{
Some(r) => r,
None => {
for new_complex in &mut new_complexes {
new_complex.push(component.clone());
}
continue;
}
};
let previous_complexes = mem::take(&mut new_complexes);
let previous_line_breaks = mem::take(&mut line_breaks);
for (i, new_complex) in previous_complexes.into_iter().enumerate() {
// todo: use .get(i)
let line_break = previous_line_breaks[i];
for mut resolved_complex in resolved.clone() {
let mut new_this_complex = new_complex.clone();
new_this_complex.append(&mut resolved_complex.components);
new_complexes.push(mem::take(&mut new_this_complex));
line_breaks.push(line_break || resolved_complex.line_break);
}
}
} else {
for new_complex in &mut new_complexes {
new_complex.push(component.clone());
}
}
}
let mut i = 0;
Ok(new_complexes
.into_iter()
.map(|new_complex| {
i += 1;
ComplexSelector::new(new_complex, line_breaks[i - 1])
.with_span(span)
})
.collect())
})
.collect::<SassResult<Vec<Vec<ComplexSelector>>>>()?,
),
span: self.span,
})
}
pub fn is_superselector(&self, other: &Self) -> bool {
other.components.iter().all(|complex1| {
self.components
.iter()
.any(|complex2| complex2.is_super_selector(complex1))
})
}
}
fn flatten_vertically<A: std::fmt::Debug>(iterable: Vec<Vec<A>>) -> Vec<A> {
let mut queues: Vec<VecDeque<A>> = iterable.into_iter().map(VecDeque::from).collect();
let mut result = Vec::new();
while !queues.is_empty() {
for queue in &mut queues {
if queue.is_empty() {
continue;
}
result.push(queue.pop_front().unwrap());
}
queues.retain(|queue| !queue.is_empty());
}
result
}