-
-
Notifications
You must be signed in to change notification settings - Fork 843
Expand file tree
/
Copy pathdependencies.rs
More file actions
4342 lines (4102 loc) 路 134 KB
/
Copy pathdependencies.rs
File metadata and controls
4342 lines (4102 loc) 路 134 KB
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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Dependency parser and lexer visitor implementation.
use rustc_hash::FxHashSet;
use smallvec::SmallVec;
use crate::{
HandleWarning, Lexer, Pos,
css_syntax::{
MAX_CSS_KEYWORD_LEN, dashed_ident_name, dashed_ident_name_start, decode_css_keyword,
is_css_modules_magic_comment, is_css_modules_pure_magic_comment, is_css_space_byte,
is_css_white_space_char, lowercase_ascii_keyword, strip_vendor_prefix, trim_css_whitespace,
},
dependency_types::{
Dependency, DependencyContext, Mode, Range, UrlRangeKind, ValueAtRuleImportItem, Warning,
WarningKind,
},
lexer::{LexerVisitor, Token, TokenFlags, TokenKind, TokenStream},
};
/// Collects dashed identifiers while the dependency parser is in local mode.
#[derive(Debug, Default)]
pub struct DashedIdentCollector {
occurrences: Vec<Range>,
enabled: bool,
}
impl DashedIdentCollector {
#[inline(always)]
fn set_enabled(&mut self, enabled: bool) {
self.enabled = enabled;
}
fn reserve(&mut self, additional: usize) {
self.occurrences.reserve(additional);
}
fn take(&mut self) -> Vec<Range> {
std::mem::take(&mut self.occurrences)
}
fn discard_last(&mut self, range: Range) {
if self.occurrences.last() == Some(&range) {
self.occurrences.pop();
}
}
}
impl LexerVisitor for DashedIdentCollector {
#[inline(always)]
fn visit_ident(&mut self, name: &str, range: Range) {
if self.enabled
&& let Some(name_start) = dashed_ident_name_start(name)
{
self
.occurrences
.push(Range::new(range.start + name_start as Pos, range.end));
}
}
}
type DependencyLexer<'s> = Lexer<'s, DashedIdentCollector>;
type DependencyTokenStream<'a, 's> = TokenStream<'a, 's, DashedIdentCollector>;
#[derive(Debug)]
enum Scope<'s> {
TopLevel,
InBlock,
InAtImport(ImportData<'s>),
AtImportInvalid,
AtNamespaceInvalid,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ScanContext {
TopLevel,
BlockItem,
Selector,
DeclarationName,
GenericValue,
SpecialValue(PropertyKind),
AtRule,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PropertyKind {
Generic,
Animation,
ListStyle,
FontPalette,
Container,
Grid,
Composes,
CustomProperty,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AtRuleKind {
Namespace,
Import,
Charset,
Value,
Keyframes,
Container,
Function,
Property,
CounterStyle,
FontPaletteValues,
Scope,
Other,
}
impl ScanContext {
fn for_property(property: PropertyKind) -> Self {
if property == PropertyKind::Generic {
Self::GenericValue
} else {
Self::SpecialValue(property)
}
}
}
#[derive(Debug)]
struct ImportData<'s> {
start: Pos,
magic_comments: Option<&'s str>,
prelude: ImportPrelude<'s>,
url: Option<&'s str>,
url_flags: TokenFlags,
url_range: Option<Range>,
supports: ImportDataSupports<'s>,
layer: ImportDataLayer<'s>,
}
impl ImportData<'_> {
pub fn new(start: Pos) -> Self {
Self {
start,
magic_comments: None,
prelude: ImportPrelude::default(),
url: None,
url_flags: TokenFlags::ascii(),
url_range: None,
supports: ImportDataSupports::None,
layer: ImportDataLayer::None,
}
}
pub fn in_supports(&self) -> bool {
matches!(self.supports, ImportDataSupports::InSupports { .. })
}
pub fn layer_range(&self) -> Option<&Range> {
let ImportDataLayer::EndLayer { range, .. } = &self.layer else {
return None;
};
Some(range)
}
pub fn supports_range(&self) -> Option<&Range> {
let ImportDataSupports::EndSupports { range, .. } = &self.supports else {
return None;
};
Some(range)
}
}
#[derive(Debug, Default)]
struct ImportPrelude<'s>(SmallVec<[ImportPreludeNode<'s>; 2]>);
impl<'s> ImportPrelude<'s> {
pub fn push(&mut self, node: ImportPreludeNode<'s>) {
self.0.push(node);
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn icss_import_url(&self) -> Option<(&'s str, &Range)> {
let [ImportPreludeNode::IcssUrlCandidate { name, range }] = self.0.as_slice() else {
return None;
};
Some((name, range))
}
pub fn first_non_url_before(&self, url_range: &Range) -> Option<&Range> {
self.0.iter().find_map(|node| {
let range = node.range();
if range.start >= url_range.start || matches!(node, ImportPreludeNode::Url { .. }) {
None
} else {
Some(range)
}
})
}
}
#[derive(Debug)]
enum ImportPreludeNode<'s> {
IcssUrlCandidate { name: &'s str, range: Range },
Url { range: Range },
Layer { range: Range },
Supports { range: Range },
Other { range: Range },
}
impl ImportPreludeNode<'_> {
fn range(&self) -> &Range {
match self {
Self::IcssUrlCandidate { range, .. }
| Self::Url { range }
| Self::Layer { range }
| Self::Supports { range }
| Self::Other { range } => range,
}
}
}
#[derive(Debug)]
enum ImportDataSupports<'s> {
None,
InSupports,
EndSupports { value: &'s str, range: Range },
}
#[derive(Debug)]
enum ImportDataLayer<'s> {
None,
EndLayer { value: &'s str, range: Range },
}
#[derive(Debug, Default)]
struct BalancedStack(SmallVec<[BalancedItem; 3]>);
impl BalancedStack {
pub fn len(&self) -> usize {
self.0.len()
}
pub fn last(&self) -> Option<&BalancedItem> {
self.0.last()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn push(&mut self, item: BalancedItem, mode_data: Option<&mut ModeData>) {
if let Some(mode_data) = mode_data {
if item.kind.is_mode_local() {
mode_data.set_current_mode(Mode::Local);
} else if item.kind.is_mode_global() {
mode_data.set_current_mode(Mode::Global);
}
if item.kind.is_mode_function() {
mode_data.inside_mode_function += 1;
} else if item.kind.is_mode_class() {
mode_data.inside_mode_class += 1;
}
}
self.0.push(item);
}
pub fn pop(&mut self, mode_data: Option<&mut ModeData>) -> Option<BalancedItem> {
let item = self.0.pop()?;
if let Some(mode_data) = mode_data {
if item.kind.is_mode_function() {
mode_data.inside_mode_function -= 1;
} else if item.kind.is_mode_class() {
mode_data.inside_mode_class -= 1;
}
self.update_current_mode(mode_data);
}
Some(item)
}
pub fn pop_without_moda_data(&mut self) -> Option<BalancedItem> {
self.0.pop()
}
pub fn pop_mode_pseudo_class(&mut self, mode_data: &mut ModeData) {
loop {
if let Some(last) = self.0.last()
&& matches!(
last.kind,
BalancedItemKind::LocalClass | BalancedItemKind::GlobalClass
)
{
mode_data.inside_mode_class -= 1;
self.0.pop();
continue;
}
break;
}
self.update_current_mode(mode_data);
}
pub fn update_current_mode(&self, mode_data: &mut ModeData) {
mode_data.set_current_mode(self.topmost_mode(mode_data));
}
pub fn update_property_mode(&self, mode_data: &mut ModeData) {
mode_data.set_property_mode(self.topmost_mode(mode_data));
}
fn topmost_mode(&self, mode_data: &ModeData) -> Mode {
let mut iter = self.0.iter();
loop {
if let Some(last) = iter.next_back() {
if matches!(
last.kind,
BalancedItemKind::LocalFn | BalancedItemKind::LocalClass
) {
return Mode::Local;
} else if matches!(
last.kind,
BalancedItemKind::GlobalFn | BalancedItemKind::GlobalClass
) {
return Mode::Global;
}
} else {
return mode_data.default_mode();
}
}
}
}
#[derive(Debug)]
struct BalancedItem {
kind: BalancedItemKind,
range: Range,
magic_comments: Option<Range>,
}
impl BalancedItem {
pub fn new(name: &str, flags: TokenFlags, start: Pos, end: Pos) -> Self {
let mut normalized = [0; MAX_CSS_KEYWORD_LEN];
let kind = if flags.has_escape() {
decode_css_keyword(name, &mut normalized)
.map_or(BalancedItemKind::Other, BalancedItemKind::new)
} else {
lowercase_ascii_keyword(name, &mut normalized)
.map_or(BalancedItemKind::Other, BalancedItemKind::new)
};
Self {
kind,
range: Range::new(start, end),
magic_comments: None,
}
}
pub fn new_normalized(name: &str, start: Pos, end: Pos) -> Self {
Self {
kind: BalancedItemKind::new(name),
range: Range::new(start, end),
magic_comments: None,
}
}
pub fn new_other(start: Pos, end: Pos) -> Self {
Self {
kind: BalancedItemKind::Other,
range: Range::new(start, end),
magic_comments: None,
}
}
pub fn new_curly(start: Pos, end: Pos) -> Self {
Self {
kind: BalancedItemKind::Curly,
range: Range::new(start, end),
magic_comments: None,
}
}
}
#[derive(Debug)]
enum BalancedItemKind {
Url,
ImageSet,
Layer,
Supports,
PaletteMix,
LocalFn,
GlobalFn,
LocalClass,
GlobalClass,
Curly,
Other,
}
impl BalancedItemKind {
pub fn new(name: &str) -> Self {
match name {
"url(" => Self::Url,
"image-set(" => Self::ImageSet,
_ if strip_vendor_prefix(name) == Some("image-set(") => Self::ImageSet,
"layer(" => Self::Layer,
"supports(" => Self::Supports,
"palette-mix(" => Self::PaletteMix,
":local(" => Self::LocalFn,
":global(" => Self::GlobalFn,
":local" => Self::LocalClass,
":global" => Self::GlobalClass,
_ => Self::Other,
}
}
pub fn is_mode_local(&self) -> bool {
matches!(self, Self::LocalFn | Self::LocalClass)
}
pub fn is_mode_global(&self) -> bool {
matches!(self, Self::GlobalFn | Self::GlobalClass)
}
pub fn is_mode_function(&self) -> bool {
matches!(self, Self::LocalFn | Self::GlobalFn)
}
pub fn is_mode_class(&self) -> bool {
matches!(self, Self::LocalClass | Self::GlobalClass)
}
}
fn preceding_comment_range(input: &str) -> Option<Range> {
let bytes = input.as_bytes();
let mut cursor = bytes.len();
let end = cursor as Pos;
let mut start = None;
loop {
while cursor > 0 && is_css_space_byte(bytes[cursor - 1]) {
cursor -= 1;
}
if cursor < 2 || &bytes[cursor - 2..cursor] != b"*/" {
break;
}
let Some(comment_start) = input[..cursor - 2].rfind("/*") else {
break;
};
start = Some(comment_start as Pos);
cursor = comment_start;
}
start.map(|start| Range::new(start, end))
}
fn trivia_only(input: &str) -> bool {
if input.is_empty() {
return false;
}
let bytes = input.as_bytes();
let mut position = 0;
while position < bytes.len() {
if is_css_space_byte(bytes[position]) {
position += 1;
continue;
}
if position + 1 < bytes.len() && bytes[position] == b'/' && bytes[position + 1] == b'*' {
position += 2;
while position + 1 < bytes.len() && !(bytes[position] == b'*' && bytes[position + 1] == b'/')
{
position += 1;
}
if position + 1 >= bytes.len() {
return false;
}
position += 2;
continue;
}
return false;
}
true
}
fn token_text(input: &str, token: Token) -> &str {
Lexer::slice_range(input, &token.range).unwrap_or("")
}
fn is_ascii_keyword(name: &str, expected: &str) -> bool {
name.eq_ignore_ascii_case(expected)
}
fn is_open_token(kind: TokenKind) -> bool {
matches!(
kind,
TokenKind::Function
| TokenKind::LeftParenthesis
| TokenKind::LeftSquareBracket
| TokenKind::LeftCurlyBracket
)
}
fn is_close_token(kind: TokenKind) -> bool {
matches!(
kind,
TokenKind::RightParenthesis | TokenKind::RightSquareBracket | TokenKind::RightCurlyBracket
)
}
fn ident_like_range(token: Token) -> Option<Range> {
match token.kind {
TokenKind::Ident => Some(token.range),
TokenKind::Function => Some(token.value_range),
_ => None,
}
}
/// Token-aligned split of an import item by a top-level colon or `as` ident.
/// Names are delimited by the surrounding significant tokens, so comments and
/// whitespace at the split points stay out of the names.
#[derive(Debug, Clone, Copy)]
struct ValueAtRuleSplit {
split: Pos,
end: Pos,
prev_end: Pos,
next_start: Option<Pos>,
}
/// Streaming state for a single `@value` at-rule. Tokens are consumed one at a
/// time; completed import items are written into the [`DependencyContext`] side
/// table immediately instead of collecting a token buffer first.
struct ValueAtRuleStream<'s> {
input: &'s str,
depth: u32,
params_end: Pos,
first_significant: Option<(Pos, Pos)>,
significant_count: u32,
first_colon: Option<ValueAtRuleSplit>,
first_colon_tokens_after: u32,
item_start: Option<Pos>,
item_end: Pos,
item_colon: Option<ValueAtRuleSplit>,
item_as: Option<ValueAtRuleSplit>,
last_significant: Option<Token>,
penultimate_significant: Option<Token>,
from_pos: Option<Pos>,
from_prev_end: Option<Pos>,
}
impl<'s> ValueAtRuleStream<'s> {
fn new(input: &'s str) -> Self {
Self {
input,
depth: 0,
params_end: 0,
first_significant: None,
significant_count: 0,
first_colon: None,
first_colon_tokens_after: 0,
item_start: None,
item_end: 0,
item_colon: None,
item_as: None,
last_significant: None,
penultimate_significant: None,
from_pos: None,
from_prev_end: None,
}
}
fn push(&mut self, context: &mut DependencyContext<'s>, token: Token) {
if matches!(token.kind, TokenKind::Comment | TokenKind::BadComment) {
self.params_end = token.range.end;
return;
}
self.params_end = token.range.end;
if self.first_significant.is_none() {
self.first_significant = Some((token.range.start, token.range.end));
}
self.significant_count += 1;
let had_first_colon = self.first_colon.is_some();
self.depth = (self.depth + u32::from(is_open_token(token.kind)))
.saturating_sub(u32::from(is_close_token(token.kind)));
let at_top = self.depth == 0;
let is_ident = token.kind == TokenKind::Ident;
let text = if is_ident {
self
.input
.get(token.range.start as usize..token.range.end as usize)
.unwrap_or("")
} else {
""
};
if at_top {
if token.kind == TokenKind::Colon {
let split = ValueAtRuleSplit {
split: token.range.start,
end: token.range.end,
prev_end: self
.last_significant
.map_or(token.range.start, |previous| previous.range.end),
next_start: None,
};
if self.first_colon.is_none() {
self.first_colon = Some(split);
}
if self.item_colon.is_none() {
self.item_colon = Some(split);
}
}
if is_ident && text.eq_ignore_ascii_case("as") {
self.item_as = Some(ValueAtRuleSplit {
split: token.range.start,
end: token.range.end,
prev_end: self
.last_significant
.map_or(token.range.start, |previous| previous.range.end),
next_start: None,
});
}
if is_ident
&& text.eq_ignore_ascii_case("from")
&& let Some(previous) = self.last_significant
{
let gap = self
.input
.get(previous.range.end as usize..token.range.start as usize)
.unwrap_or("");
if trivia_only(gap) {
self.from_pos = Some(token.range.start);
self.from_prev_end = Some(previous.range.end);
}
}
self.penultimate_significant = self.last_significant;
self.last_significant = Some(token);
}
if had_first_colon {
self.first_colon_tokens_after += 1;
}
if token.kind == TokenKind::Comma && at_top {
self.finish_item(context, self.item_end);
self.item_start = None;
self.item_colon = None;
self.item_as = None;
} else {
if self.item_start.is_none() {
self.item_start = Some(token.range.start);
}
self.item_end = token.range.end;
if let Some(split) = self.item_colon.as_mut()
&& split.next_start.is_none()
&& split.split != token.range.start
{
split.next_start = Some(token.range.start);
}
if let Some(split) = self.item_as.as_mut()
&& split.next_start.is_none()
&& split.split != token.range.start
{
split.next_start = Some(token.range.start);
}
}
}
fn finish_item(&mut self, context: &mut DependencyContext<'s>, end: Pos) {
let Some(item_start) = self.item_start else {
return;
};
if end.saturating_sub(item_start) >= 2
&& self.input.as_bytes()[item_start as usize] == b'('
&& self.input.as_bytes()[end as usize - 1] == b')'
{
self.parse_paren_items(context, item_start + 1, end - 1);
} else {
let item = self.build_item(item_start, end, self.item_colon, self.item_as);
if !item.local_name().is_empty() || !item.import_name().is_empty() {
context.push_value_at_rule_import_item(item);
}
}
}
fn build_item(
&self,
start: Pos,
end: Pos,
colon: Option<ValueAtRuleSplit>,
as_split: Option<ValueAtRuleSplit>,
) -> ValueAtRuleImportItem<'s> {
let slice = |a: Pos, b: Pos| -> &'s str {
if a >= b {
""
} else {
&self.input[a as usize..b as usize]
}
};
if let Some(split) = colon {
return ValueAtRuleImportItem::new(
slice(start, split.prev_end),
split
.next_start
.map_or("", |next_start| slice(next_start, end)),
);
}
if let Some(split) = as_split {
let import_name = slice(start, split.prev_end);
let local_name = split
.next_start
.map_or("", |next_start| slice(next_start, end));
if !import_name.is_empty() && !local_name.is_empty() {
return ValueAtRuleImportItem::new(local_name, import_name);
}
}
let value = slice(start, end);
ValueAtRuleImportItem::new(value, value)
}
/// Re-parses a parenthesized item: the inner content was not streamed
/// token-by-token, so it is tokenized once more and split at depth-zero
/// commas, mirroring the legacy aligned-token behavior.
fn parse_paren_items(&mut self, context: &mut DependencyContext<'s>, start: Pos, end: Pos) {
let slice = &self.input[start as usize..end as usize];
let mut lexer = Lexer::new(slice, ());
let mut tokens: SmallVec<[Token; 8]> = SmallVec::new();
loop {
let token = lexer.next_token();
if token.kind == TokenKind::Eof {
break;
}
if matches!(
token.kind,
TokenKind::Comment | TokenKind::BadComment | TokenKind::WhiteSpace
) {
continue;
}
tokens.push(token);
}
let mut item_start = 0;
let mut item_depth = 0u32;
for (index, token) in tokens.iter().copied().enumerate() {
if is_close_token(token.kind) {
item_depth = item_depth.saturating_sub(1);
}
if token.kind == TokenKind::Comma && item_depth == 0 {
self.push_parsed_item(context, &tokens, item_start, index, slice);
item_start = index + 1;
}
if is_open_token(token.kind) {
item_depth += 1;
}
}
self.push_parsed_item(context, &tokens, item_start, tokens.len(), slice);
}
fn push_parsed_item(
&mut self,
context: &mut DependencyContext<'s>,
tokens: &[Token],
start: usize,
end: usize,
slice: &'s str,
) {
let mut depth = 0u32;
let mut colon_index = None;
let mut as_index = None;
for (index, token) in tokens[start..end].iter().copied().enumerate() {
let index = start + index;
if is_close_token(token.kind) {
depth = depth.saturating_sub(1);
}
if depth == 0 {
if token.kind == TokenKind::Colon && colon_index.is_none() {
colon_index = Some(index);
}
if token.kind == TokenKind::Ident && token_text(slice, token).eq_ignore_ascii_case("as") {
as_index = Some(index);
}
}
if is_open_token(token.kind) {
depth += 1;
}
}
let span = |a: usize, b: usize| -> &'s str {
if a >= b {
""
} else {
&slice[tokens[a].range.start as usize..tokens[b - 1].range.end as usize]
}
};
let item = if let Some(index) = colon_index {
ValueAtRuleImportItem::new(span(start, index), span(index + 1, end))
} else if let Some(index) = as_index {
let import_name = span(start, index);
let local_name = span(index + 1, end);
if !import_name.is_empty() && !local_name.is_empty() {
ValueAtRuleImportItem::new(local_name, import_name)
} else {
ValueAtRuleImportItem::new("", "")
}
} else {
let value = span(start, end);
ValueAtRuleImportItem::new(value, value)
};
if !item.local_name().is_empty() || !item.import_name().is_empty() {
context.push_value_at_rule_import_item(item);
}
}
/// Returns the last two significant tokens, or `None` if there are fewer
/// than two.
fn last_two(&self) -> Option<(Token, Token)> {
Some((self.penultimate_significant?, self.last_significant?))
}
}
#[derive(Debug)]
pub struct ModeData<'s> {
default: Mode,
current: Mode,
property: Mode,
resulting_global: Option<Pos>,
pure_global: Option<Pos>,
pure_no_check: bool,
pure_ignore_pending: bool,
pure_ignored_block_nesting_level: Option<u32>,
composes_local_classes: ComposesLocalClasses<'s>,
inside_mode_function: u32,
inside_mode_class: u32,
}
impl ModeData<'_> {
pub fn new(default: Mode) -> Self {
Self {
default,
current: default,
property: default,
resulting_global: None,
pure_global: Some(0),
pure_no_check: false,
pure_ignore_pending: false,
pure_ignored_block_nesting_level: None,
composes_local_classes: ComposesLocalClasses::default(),
inside_mode_function: 0,
inside_mode_class: 0,
}
}
pub fn is_pure_mode(&self) -> bool {
matches!(self.default, Mode::Pure)
}
pub fn mark_pure_ignore(&mut self) {
if self.is_pure_mode() {
self.pure_ignore_pending = true;
}
}
pub fn mark_pure_no_check(&mut self) {
if self.is_pure_mode() {
self.pure_no_check = true;
}
}
pub fn is_pure_check_disabled(&self) -> bool {
self.pure_no_check
|| self.pure_ignore_pending
|| self.pure_ignored_block_nesting_level.is_some()
}
pub fn enter_block(&mut self, block_nesting_level: u32) {
if self.pure_ignore_pending {
self.pure_ignore_pending = false;
if self.pure_ignored_block_nesting_level.is_none() {
self.pure_ignored_block_nesting_level = Some(block_nesting_level);
}
}
}
pub fn clear_pure_ignore_pending(&mut self) {
self.pure_ignore_pending = false;
}
pub fn exit_block(&mut self, block_nesting_level: u32) {
if self
.pure_ignored_block_nesting_level
.is_some_and(|level| block_nesting_level < level)
{
self.pure_ignored_block_nesting_level = None;
}
}
pub fn is_current_local_mode(&self) -> bool {
match self.current {
Mode::Local | Mode::Pure => true,
Mode::Global | Mode::Css => false,
}
}
pub fn is_property_local_mode(&self) -> bool {
match self.property {
Mode::Local | Mode::Pure => true,
Mode::Global | Mode::Css => false,
}
}
pub fn default_mode(&self) -> Mode {
self.default
}
pub fn set_current_mode(&mut self, mode: Mode) {
self.current = mode;
}
pub fn set_property_mode(&mut self, mode: Mode) {
self.property = mode;
}
pub fn is_inside_mode_function(&self) -> bool {
self.inside_mode_function > 0
}
pub fn is_inside_mode_class(&self) -> bool {
self.inside_mode_class > 0
}
pub fn is_mode_explicit(&self) -> bool {
self.is_inside_mode_function() || self.is_inside_mode_class()
}
}
#[derive(Debug, Default, Clone)]
struct ComposesLocalClasses<'s> {
is_single: SingleLocalClass,
local_classes: SmallVec<[&'s str; 2]>,
}
impl<'s> ComposesLocalClasses<'s> {
pub fn get_valid_local_classes(
&mut self,
lexer: &DependencyLexer<'s>,
) -> Option<SmallVec<[&'s str; 2]>> {
if let SingleLocalClass::Single(range) = &self.is_single {
let mut local_classes = self.local_classes.clone();
local_classes.push(lexer.slice(range.start, range.end)?);
Some(local_classes)
} else {
self.reset_to_initial();
None
}
}
pub fn invalidate(&mut self) {
if !matches!(self.is_single, SingleLocalClass::AtKeyword) {
self.is_single = SingleLocalClass::Invalid;
self.local_classes.clear();
}
}
pub fn find_local_class(&mut self, start: Pos, end: Pos) {
match self.is_single {
SingleLocalClass::Initial => {
self.is_single = SingleLocalClass::Single(Range::new(start, end))
}
SingleLocalClass::Single(_) => {
self.is_single = SingleLocalClass::Invalid;
self.local_classes.clear();
}
_ => {}
};
}
pub fn find_at_keyword(&mut self) {
self.is_single = SingleLocalClass::AtKeyword;
self.local_classes.clear();
}
pub fn reset_to_initial(&mut self) {
self.is_single = SingleLocalClass::Initial;
self.local_classes.clear();
}
pub fn find_comma(&mut self, lexer: &DependencyLexer<'s>) -> Option<()> {
if let SingleLocalClass::Single(range) = &self.is_single {
self
.local_classes
.push(lexer.slice(range.start, range.end)?);
self.is_single = SingleLocalClass::Initial
} else {
self.is_single = SingleLocalClass::Invalid;
}
Some(())
}
}
#[derive(Debug, Default, Clone)]
enum SingleLocalClass {
#[default]
Initial,
Single(Range),
AtKeyword,
Invalid,
}
#[derive(Debug)]
struct InProperty<T: ReservedValues> {
reserved: T,