-
Notifications
You must be signed in to change notification settings - Fork 362
/
Copy pathextension_store.dart
1132 lines (1023 loc) · 38 KB
/
extension_store.dart
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
// Copyright 2016 Google Inc. Use of this source code is governed by an
// MIT-style license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'dart:math' as math;
import 'package:collection/collection.dart';
import 'package:source_span/source_span.dart';
import '../ast/css.dart';
import '../ast/selector.dart';
import '../ast/sass.dart';
import '../exception.dart';
import '../util/box.dart';
import '../util/map.dart';
import '../util/nullable.dart';
import '../utils.dart';
import 'empty_extension_store.dart';
import 'extension.dart';
import 'merged_extension.dart';
import 'functions.dart';
import 'mode.dart';
/// Tracks selectors and extensions, and applies the latter to the former.
class ExtensionStore {
/// An [ExtensionStore] that contains no extensions and can have no extensions
/// added.
static const empty = EmptyExtensionStore();
/// A map from all simple selectors in the stylesheet to the selector lists
/// that contain them.
///
/// This is used to find which selectors an `@extend` applies to and adjust
/// them.
final Map<SimpleSelector, Set<ModifiableBox<SelectorList>>> _selectors;
/// A map from all extended simple selectors to the sources of those
/// extensions.
final Map<SimpleSelector, Map<ComplexSelector, Extension>> _extensions;
/// A map from all simple selectors in extenders to the extensions that those
/// extenders define.
final Map<SimpleSelector, List<Extension>> _extensionsByExtender;
/// A map from CSS selectors to the media query contexts they're defined in.
///
/// This tracks the contexts in which each selector's style rule is defined.
/// If a rule is defined at the top level, it doesn't have an entry.
final Map<ModifiableBox<SelectorList>, List<CssMediaQuery>> _mediaContexts;
/// A map from [SimpleSelector]s to the specificity of their source
/// selectors.
///
/// This tracks the maximum specificity of the [ComplexSelector] that
/// originally contained each [SimpleSelector]. This allows us to ensure that
/// we don't trim any selectors that need to exist to satisfy the [second law
/// of extend][].
///
/// [second law of extend]: https://github.com/sass/sass/issues/324#issuecomment-4607184
final Map<SimpleSelector, int> _sourceSpecificity;
/// A set of [ComplexSelector]s that were originally part of
/// their component [SelectorList]s, as opposed to being added by `@extend`.
///
/// This allows us to ensure that we don't trim any selectors that need to
/// exist to satisfy the [first law of extend][].
///
/// [first law of extend]: https://github.com/sass/sass/issues/324#issuecomment-4607184
final Set<ComplexSelector> _originals;
/// The mode that controls this extender's behavior.
final ExtendMode _mode;
/// Whether this extender has no extensions.
bool get isEmpty => _extensions.isEmpty;
/// Extends [selector] with [source] extender and [targets] extendees.
///
/// This works as though `source {@extend target}` were written in the
/// stylesheet, with the exception that [target] can contain compound
/// selectors which must be extended as a unit.
static SelectorList extend(
SelectorList selector,
SelectorList source,
SelectorList targets,
FileSpan span,
) =>
_extendOrReplace(selector, source, targets, ExtendMode.allTargets, span);
/// Returns a copy of [selector] with [targets] replaced by [source].
static SelectorList replace(
SelectorList selector,
SelectorList source,
SelectorList targets,
FileSpan span,
) =>
_extendOrReplace(selector, source, targets, ExtendMode.replace, span);
/// A helper function for [extend] and [replace].
static SelectorList _extendOrReplace(
SelectorList selector,
SelectorList source,
SelectorList targets,
ExtendMode mode,
FileSpan span,
) {
var extender = ExtensionStore._mode(mode);
if (!selector.isInvisible) extender._originals.addAll(selector.components);
for (var complex in targets.components) {
var compound = complex.singleCompound;
if (compound == null) {
throw SassScriptException("Can't extend complex selector $complex.");
}
selector = extender._extendList(selector, {
for (var simple in compound.components)
simple: {
for (var complex in source.components)
complex: Extension(complex, simple, span, optional: true),
},
});
}
return selector;
}
/// The set of all simple selectors in selectors handled by this extender.
///
/// This includes simple selectors that were added because of downstream
/// extensions.
Set<SimpleSelector> get simpleSelectors => MapKeySet(_selectors);
ExtensionStore() : this._mode(ExtendMode.normal);
ExtensionStore._mode(this._mode)
: _selectors = {},
_extensions = {},
_extensionsByExtender = {},
_mediaContexts = {},
_sourceSpecificity = Map.identity(),
_originals = Set.identity();
ExtensionStore._(
this._selectors,
this._extensions,
this._extensionsByExtender,
this._mediaContexts,
this._sourceSpecificity,
this._originals,
) : _mode = ExtendMode.normal;
/// Returns all mandatory extensions in this extender for whose targets
/// [callback] returns `true`.
///
/// This un-merges any [MergedExtension] so only base [Extension]s are
/// returned.
Iterable<Extension> extensionsWhereTarget(
bool callback(SimpleSelector target),
) sync* {
for (var (simple, sources) in _extensions.pairs) {
if (!callback(simple)) continue;
for (var extension in sources.values) {
if (extension is MergedExtension) {
yield* extension.unmerge().where(
(extension) => !extension.isOptional,
);
} else if (!extension.isOptional) {
yield extension;
}
}
}
}
/// Adds [selector] to this extender.
///
/// Extends [selector] using any registered extensions, then returns a [Box]
/// containing the resulting selector. If any more relevant extensions are
/// added, the returned selector is automatically updated.
///
/// The [mediaContext] is the media query context in which the selector was
/// defined, or `null` if it was defined at the top level of the document.
Box<SelectorList> addSelector(
SelectorList selector, [
List<CssMediaQuery>? mediaContext,
]) {
var originalSelector = selector;
if (!originalSelector.isInvisible) {
_originals.addAll(originalSelector.components);
}
if (_extensions.isNotEmpty) {
try {
selector = _extendList(originalSelector, _extensions, mediaContext);
} on SassException catch (error, stackTrace) {
throwWithTrace(
SassException(
"From ${error.span.message('')}\n"
"${error.message}",
error.span,
),
error,
stackTrace,
);
}
}
var modifiableSelector = ModifiableBox(selector);
if (mediaContext != null) _mediaContexts[modifiableSelector] = mediaContext;
_registerSelector(selector, modifiableSelector);
return modifiableSelector.seal();
}
/// Registers the [SimpleSelector]s in [list] to point to [selector] in
/// [_selectors].
void _registerSelector(
SelectorList list,
ModifiableBox<SelectorList> selector,
) {
for (var complex in list.components) {
for (var component in complex.components) {
for (var simple in component.selector.components) {
_selectors.putIfAbsent(simple, () => {}).add(selector);
if (simple case PseudoSelector(selector: var selectorInPseudo?)) {
_registerSelector(selectorInPseudo, selector);
}
}
}
}
}
/// Adds an extension to this extender.
///
/// The [extender] is the selector for the style rule in which the extension
/// is defined, and [target] is the selector passed to `@extend`. The [extend]
/// provides the extend span and indicates whether the extension is optional.
///
/// The [mediaContext] defines the media query context in which the extension
/// is defined. It can only extend selectors within the same context. A `null`
/// context indicates no media queries.
void addExtension(
SelectorList extender,
SimpleSelector target,
ExtendRule extend, [
List<CssMediaQuery>? mediaContext,
]) {
var selectors = _selectors[target];
var existingExtensions = _extensionsByExtender[target];
Map<ComplexSelector, Extension>? newExtensions;
var sources = _extensions.putIfAbsent(target, () => {});
for (var complex in extender.components) {
if (complex.isUseless) continue;
var extension = Extension(
complex,
target,
extend.span,
mediaContext: mediaContext,
optional: extend.isOptional,
);
if (sources[complex] case var existingExtension?) {
// If there's already an extend from [extender] to [target], we don't need
// to re-run the extension. We may need to mark the extension as
// mandatory, though.
sources[complex] = MergedExtension.merge(existingExtension, extension);
continue;
}
sources[complex] = extension;
for (var simple in _simpleSelectors(complex)) {
_extensionsByExtender.putIfAbsent(simple, () => []).add(extension);
// Only source specificity for the original selector is relevant.
// Selectors generated by `@extend` don't get new specificity.
_sourceSpecificity.putIfAbsent(simple, () => complex.specificity);
}
if (selectors != null || existingExtensions != null) {
newExtensions ??= {};
newExtensions[complex] = extension;
}
}
if (newExtensions == null) return;
var newExtensionsByTarget = {target: newExtensions};
if (existingExtensions != null) {
var additionalExtensions = _extendExistingExtensions(
existingExtensions,
newExtensionsByTarget,
);
if (additionalExtensions != null) {
mapAddAll2(newExtensionsByTarget, additionalExtensions);
}
}
if (selectors != null) {
_extendExistingSelectors(selectors, newExtensionsByTarget);
}
}
/// Returns an iterable of all simple selectors in [complex]
Iterable<SimpleSelector> _simpleSelectors(ComplexSelector complex) sync* {
for (var component in complex.components) {
for (var simple in component.selector.components) {
yield simple;
if (simple case PseudoSelector(:var selector?)) {
for (var complex in selector.components) {
yield* _simpleSelectors(complex);
}
}
}
}
}
/// Extend [extensions] using [newExtensions].
///
/// Note that this does duplicate some work done by
/// [_extendExistingSelectors], but it's necessary to expand each extension's
/// extender separately without reference to the full selector list, so that
/// relevant results don't get trimmed too early.
///
/// Returns extensions that should be added to [newExtensions] before
/// extending selectors in order to properly handle extension loops such as:
///
/// .c {x: y; @extend .a}
/// .x.y.a {@extend .b}
/// .z.b {@extend .c}
///
/// Returns `null` if there are no extensions to add.
Map<SimpleSelector, Map<ComplexSelector, Extension>>?
_extendExistingExtensions(
List<Extension> extensions,
Map<SimpleSelector, Map<ComplexSelector, Extension>> newExtensions,
) {
Map<SimpleSelector, Map<ComplexSelector, Extension>>? additionalExtensions;
for (var extension in extensions.toList()) {
var sources = _extensions[extension.target]!;
Iterable<ComplexSelector>? selectors;
try {
selectors = _extendComplex(
extension.extender.selector,
newExtensions,
extension.mediaContext,
);
if (selectors == null) continue;
} on SassException catch (error, stackTrace) {
throwWithTrace(
error.withAdditionalSpan(
extension.extender.selector.span,
"target selector",
),
error,
stackTrace,
);
}
// If the output contains the original complex selector, there's no need
// to recreate it.
var containsExtension = selectors.first == extension.extender.selector;
if (containsExtension) selectors = selectors.skip(1);
for (var complex in selectors) {
var withExtender = extension.withExtender(complex);
if (sources[complex] case var existingExtension?) {
sources[complex] = MergedExtension.merge(
existingExtension,
withExtender,
);
} else {
sources[complex] = withExtender;
for (var component in complex.components) {
for (var simple in component.selector.components) {
_extensionsByExtender
.putIfAbsent(simple, () => [])
.add(withExtender);
}
}
if (newExtensions.containsKey(extension.target)) {
additionalExtensions ??= {};
var additionalSources = additionalExtensions.putIfAbsent(
extension.target,
() => {},
);
additionalSources[complex] = withExtender;
}
}
}
}
return additionalExtensions;
}
/// Extend [extensions] using [newExtensions].
void _extendExistingSelectors(
Set<ModifiableBox<SelectorList>> selectors,
Map<SimpleSelector, Map<ComplexSelector, Extension>> newExtensions,
) {
for (var selector in selectors) {
var oldValue = selector.value;
try {
selector.value = _extendList(
selector.value,
newExtensions,
_mediaContexts[selector],
);
} on SassException catch (error, stackTrace) {
// TODO(nweiz): Make this a MultiSpanSassException.
throwWithTrace(
SassException(
"From ${selector.value.span.message('')}\n"
"${error.message}",
error.span,
),
error,
stackTrace,
);
}
// If no extends actually happened (for example because unification
// failed), we don't need to re-register the selector.
if (identical(oldValue, selector.value)) continue;
_registerSelector(selector.value, selector);
}
}
/// Extends `this` with all the extensions in [extensions].
///
/// These extensions will extend all selectors already in `this`, but they
/// will *not* extend other extensions from [extensionStores].
void addExtensions(Iterable<ExtensionStore> extensionStores) {
// Extensions already in `this` whose extenders are extended by
// [extensions], and thus which need to be updated.
List<Extension>? extensionsToExtend;
// Selectors that contain simple selectors that are extended by
// [extensions], and thus which need to be extended themselves.
Set<ModifiableBox<SelectorList>>? selectorsToExtend;
// An extension map with the same structure as [_extensions] that only
// includes extensions from [extensionStores].
Map<SimpleSelector, Map<ComplexSelector, Extension>>? newExtensions;
for (var extensionStore in extensionStores) {
if (extensionStore.isEmpty) continue;
_sourceSpecificity.addAll(extensionStore._sourceSpecificity);
for (var (target, newSources) in extensionStore._extensions.pairs) {
// Private selectors can't be extended across module boundaries.
if (target case PlaceholderSelector(isPrivate: true)) continue;
// Find existing extensions to extend.
var extensionsForTarget = _extensionsByExtender[target];
if (extensionsForTarget != null) {
(extensionsToExtend ??= []).addAll(extensionsForTarget);
}
// Find existing selectors to extend.
var selectorsForTarget = _selectors[target];
if (selectorsForTarget != null) {
(selectorsToExtend ??= {}).addAll(selectorsForTarget);
}
// Add [newSources] to [_extensions].
if (_extensions[target] case var existingSources?) {
for (var (extender, extension) in newSources.pairs) {
extension = existingSources.putOrMerge(
extender,
extension,
MergedExtension.merge,
);
if (extensionsForTarget != null || selectorsForTarget != null) {
(newExtensions ??= {}).putIfAbsent(target, () => {})[extender] =
extension;
}
}
} else {
_extensions[target] = Map.of(newSources);
if (extensionsForTarget != null || selectorsForTarget != null) {
(newExtensions ??= {})[target] = Map.of(newSources);
}
}
}
}
if (newExtensions != null) {
// We can ignore the return value here because it's only useful for extend
// loops, which can't exist across module boundaries.
if (extensionsToExtend != null) {
_extendExistingExtensions(extensionsToExtend, newExtensions);
}
if (selectorsToExtend != null) {
_extendExistingSelectors(selectorsToExtend, newExtensions);
}
}
}
/// Extends [list] using [extensions].
SelectorList _extendList(
SelectorList list,
Map<SimpleSelector, Map<ComplexSelector, Extension>> extensions, [
List<CssMediaQuery>? mediaQueryContext,
]) {
// This could be written more simply using [List.map], but we want to avoid
// any allocations in the common case where no extends apply.
List<ComplexSelector>? extended;
for (var i = 0; i < list.components.length; i++) {
var complex = list.components[i];
var result = _extendComplex(complex, extensions, mediaQueryContext);
assert(
result?.isNotEmpty ?? true,
'_extendComplex($complex) should return null rather than [] if '
'extension fails',
);
if (result == null) {
extended?.add(complex);
} else {
extended ??= i == 0 ? [] : list.components.sublist(0, i).toList();
extended.addAll(result);
}
}
if (extended == null) return list;
return SelectorList(_trim(extended, _originals.contains), list.span);
}
/// Extends [complex] using [extensions], and returns the contents of a
/// [SelectorList].
List<ComplexSelector>? _extendComplex(
ComplexSelector complex,
Map<SimpleSelector, Map<ComplexSelector, Extension>> extensions,
List<CssMediaQuery>? mediaQueryContext,
) {
if (complex.leadingCombinators.length > 1) return null;
// The complex selectors that each compound selector in [complex.components]
// can expand to.
//
// For example, given
//
// .a .b {...}
// .x .y {@extend .b}
//
// this will contain
//
// [
// [.a],
// [.b, .x .y]
// ]
//
// This could be written more simply using [List.map], but we want to avoid
// any allocations in the common case where no extends apply.
List<List<ComplexSelector>>? extendedNotExpanded;
var isOriginal = _originals.contains(complex);
for (var i = 0; i < complex.components.length; i++) {
var component = complex.components[i];
var extended = _extendCompound(
component,
extensions,
mediaQueryContext,
inOriginal: isOriginal,
);
assert(
extended?.isNotEmpty ?? true,
'_extendCompound($component) should return null rather than [] if '
'extension fails',
);
if (extended == null) {
extendedNotExpanded?.add([
ComplexSelector(
const [],
[component],
complex.span,
lineBreak: complex.lineBreak,
),
]);
} else if (extendedNotExpanded != null) {
extendedNotExpanded.add(extended);
} else if (i != 0) {
extendedNotExpanded = [
[
ComplexSelector(
complex.leadingCombinators,
complex.components.take(i),
complex.span,
lineBreak: complex.lineBreak,
),
],
extended,
];
} else if (complex.leadingCombinators.isEmpty) {
extendedNotExpanded = [extended];
} else {
extendedNotExpanded = [
[
for (var newComplex in extended)
if (newComplex.leadingCombinators.isEmpty ||
listEquals(
complex.leadingCombinators,
newComplex.leadingCombinators,
))
ComplexSelector(
complex.leadingCombinators,
newComplex.components,
complex.span,
lineBreak: complex.lineBreak || newComplex.lineBreak,
),
],
];
}
}
if (extendedNotExpanded == null) return null;
var first = true;
return paths(extendedNotExpanded).expand((path) {
return weave(path, complex.span, forceLineBreak: complex.lineBreak).map((
outputComplex,
) {
// Make sure that copies of [complex] retain their status as "original"
// selectors. This includes selectors that are modified because a :not()
// was extended into.
if (first && _originals.contains(complex)) {
_originals.add(outputComplex);
}
first = false;
return outputComplex;
});
}).toList();
}
/// Extends [component] using [extensions], and returns the contents of a
/// [SelectorList].
///
/// The [inOriginal] parameter indicates whether this is in an original
/// complex selector, meaning that [compound] should not be trimmed out.
///
/// The [lineBreak] parameter indicates whether [component] appears in a
/// complex selector with a line break.
List<ComplexSelector>? _extendCompound(
ComplexSelectorComponent component,
Map<SimpleSelector, Map<ComplexSelector, Extension>> extensions,
List<CssMediaQuery>? mediaQueryContext, {
required bool inOriginal,
}) {
// If there's more than one target and they all need to match, we track
// which targets are actually extended.
var targetsUsed = _mode == ExtendMode.normal || extensions.length < 2
? null
: <SimpleSelector>{};
var simples = component.selector.components;
// The complex selectors produced from each simple selector in [compound].
List<List<Extender>>? options;
for (var i = 0; i < simples.length; i++) {
var simple = simples[i];
var extended = _extendSimple(
simple,
extensions,
mediaQueryContext,
targetsUsed,
);
assert(
extended?.isNotEmpty ?? true,
'_extendSimple($simple) should return null rather than [] if '
'extension fails',
);
if (extended == null) {
options?.add([_extenderForSimple(simple)]);
} else {
if (options == null) {
options = [];
if (i != 0) {
options.add([
_extenderForCompound(simples.take(i), component.span),
]);
}
}
options.addAll(extended);
}
}
if (options == null) return null;
// If [_mode] isn't [ExtendMode.normal] and we didn't use all the targets in
// [extensions], extension fails for [component].
if (targetsUsed != null && targetsUsed.length != extensions.length) {
return null;
}
// Optimize for the simple case of a single simple selector that doesn't
// need any unification.
if (options case [var extenders]) {
List<ComplexSelector>? result;
for (var extender in extenders) {
extender.assertCompatibleMediaContext(mediaQueryContext);
var complex = extender.selector.withAdditionalCombinators(
component.combinators,
);
if (complex.isUseless) continue;
result ??= [];
result.add(complex);
}
return result;
}
// Find all paths through [options]. In this case, each path represents a
// different unification of the base selector. For example, if we have:
//
// .a.b {...}
// .w .x {@extend .a}
// .y .z {@extend .b}
//
// then [options] is `[[.a, .w .x], [.b, .y .z]]` and `paths(options)` is
//
// [
// [.a, .b],
// [.a, .y .z],
// [.w .x, .b],
// [.w .x, .y .z]
// ]
//
// We then unify each path to get a list of complex selectors:
//
// [
// [.a.b],
// [.y .a.z],
// [.w .x.b],
// [.w .y .x.z, .y .w .x.z]
// ]
//
// And finally flatten them to get:
//
// [
// .a.b,
// .y .a.z,
// .w .x.b,
// .w .y .x.z,
// .y .w .x.z
// ]
var extenderPaths = paths(options);
var result = [
if (_mode != ExtendMode.replace)
// The first path is always the original selector. We can't just return
// [component] directly because selector pseudos may be modified, but we
// don't have to do any unification.
ComplexSelector(const [], [
ComplexSelectorComponent(
CompoundSelector(
extenderPaths.first.expand((extender) {
assert(extender.selector.components.length == 1);
return extender.selector.components.last.selector.components;
}),
component.selector.span,
),
component.combinators,
component.span,
),
], component.span),
];
for (var path in extenderPaths.skip(_mode == ExtendMode.replace ? 0 : 1)) {
var extended = _unifyExtenders(path, mediaQueryContext, component.span);
if (extended == null) continue;
for (var complex in extended) {
var withCombinators = complex.withAdditionalCombinators(
component.combinators,
);
if (!withCombinators.isUseless) result.add(withCombinators);
}
}
// If we're preserving the original selector, mark the first unification as
// such so [_trim] doesn't get rid of it.
var isOriginal = (ComplexSelector _) => false;
if (inOriginal && _mode != ExtendMode.replace) {
var original = result.first;
isOriginal = (complex) => complex == original;
}
return _trim(result, isOriginal);
}
/// Returns a list of [ComplexSelector]s that match the intersection of
/// elements matched by all of [extenders]' selectors.
///
/// The [span] will be used for the new selectors.
List<ComplexSelector>? _unifyExtenders(
List<Extender> extenders,
List<CssMediaQuery>? mediaQueryContext,
FileSpan span,
) {
var toUnify = QueueList<ComplexSelector>();
List<SimpleSelector>? originals;
var originalsLineBreak = false;
for (var extender in extenders) {
if (extender.isOriginal) {
originals ??= [];
var finalExtenderComponent = extender.selector.components.last;
assert(finalExtenderComponent.combinators.isEmpty);
originals.addAll(finalExtenderComponent.selector.components);
originalsLineBreak = originalsLineBreak || extender.selector.lineBreak;
} else if (extender.selector.isUseless) {
return null;
} else {
toUnify.add(extender.selector);
}
}
if (originals != null) {
toUnify.addFirst(
ComplexSelector(
const [],
[
ComplexSelectorComponent(
CompoundSelector(originals, span),
const [],
span,
),
],
span,
lineBreak: originalsLineBreak,
),
);
}
var complexes = unifyComplex(toUnify, span);
if (complexes == null) return null;
for (var extender in extenders) {
extender.assertCompatibleMediaContext(mediaQueryContext);
}
return complexes;
}
/// Returns the [Extender]s from [extensions] that that should replace
/// [simple], or `null` if it's not the target of an extension.
///
/// Each element of the returned iterable is a list of choices, which will be
/// combined using [paths].
Iterable<List<Extender>>? _extendSimple(
SimpleSelector simple,
Map<SimpleSelector, Map<ComplexSelector, Extension>> extensions,
List<CssMediaQuery>? mediaQueryContext,
Set<SimpleSelector>? targetsUsed,
) {
// Extends [simple] without extending the contents of any selector pseudos
// it contains.
List<Extender>? withoutPseudo(SimpleSelector simple) {
var extensionsForSimple = extensions[simple];
if (extensionsForSimple == null) return null;
targetsUsed?.add(simple);
return [
if (_mode != ExtendMode.replace) _extenderForSimple(simple),
for (var extension in extensionsForSimple.values) extension.extender,
];
}
if (simple case PseudoSelector(selector: _?)) {
if (_extendPseudo(simple, extensions, mediaQueryContext)
case var extended?) {
return extended.map(
(pseudo) => withoutPseudo(pseudo) ?? [_extenderForSimple(pseudo)],
);
}
}
return withoutPseudo(simple).andThen((result) => [result]);
}
/// Returns an [Extender] composed solely of a compound selector containing
/// [simples].
Extender _extenderForCompound(
Iterable<SimpleSelector> simples,
FileSpan span,
) {
var compound = CompoundSelector(simples, span);
return Extender(
ComplexSelector(const [], [
ComplexSelectorComponent(compound, const [], span),
], span),
specificity: _sourceSpecificityFor(compound),
original: true,
);
}
/// Returns an [Extender] composed solely of [simple].
Extender _extenderForSimple(SimpleSelector simple) => Extender(
ComplexSelector(const [], [
ComplexSelectorComponent(
CompoundSelector([simple], simple.span),
const [],
simple.span,
),
], simple.span),
specificity: _sourceSpecificity[simple] ?? 0,
original: true,
);
/// Extends [pseudo] using [extensions], and returns a list of resulting
/// pseudo selectors.
///
/// This requires that [pseudo] have a selector argument.
List<PseudoSelector>? _extendPseudo(
PseudoSelector pseudo,
Map<SimpleSelector, Map<ComplexSelector, Extension>> extensions,
List<CssMediaQuery>? mediaQueryContext,
) {
var selector = pseudo.selector;
if (selector == null) {
throw ArgumentError("Selector $pseudo must have a selector argument.");
}
var extended = _extendList(selector, extensions, mediaQueryContext);
if (identical(extended, selector)) return null;
// For `:not()`, we usually want to get rid of any complex selectors because
// that will cause the selector to fail to parse on all browsers at time of
// writing. We can keep them if either the original selector had a complex
// selector, or the result of extending has only complex selectors, because
// either way we aren't breaking anything that isn't already broken.
Iterable<ComplexSelector> complexes = extended.components;
if (pseudo.normalizedName == "not" &&
!selector.components.any((complex) => complex.components.length > 1) &&
extended.components.any((complex) => complex.components.length == 1)) {
complexes = extended.components.where(
(complex) => complex.components.length <= 1,
);
}
complexes = complexes.expand((complex) {
var innerPseudo = complex.singleCompound?.singleSimple;
if (innerPseudo is! PseudoSelector) return [complex];
var innerSelector = innerPseudo.selector;
if (innerSelector == null) return [complex];
switch (pseudo.normalizedName) {
case 'not':
// In theory, if there's a `:not` nested within another `:not`, the
// inner `:not`'s contents should be unified with the return value.
// For example, if `:not(.foo)` extends `.bar`, `:not(.bar)` should
// become `.foo:not(.bar)`. However, this is a narrow edge case and
// supporting it properly would make this code and the code calling it
// a lot more complicated, so it's not supported for now.
if (!const {
'is',
'matches',
'where',
}.contains(innerPseudo.normalizedName)) {
return [];
}
return innerSelector.components;
case 'is':
case 'matches':
case 'where':
case 'any':
case 'current':
case 'nth-child':
case 'nth-last-child':
// As above, we could theoretically support :not within :matches, but
// doing so would require this method and its callers to handle much
// more complex cases that likely aren't worth the pain.
if (innerPseudo.name != pseudo.name) return [];
if (innerPseudo.argument != pseudo.argument) return [];
return innerSelector.components;
case 'has':
case 'host':
case 'host-context':
case 'slotted':
// We can't expand nested selectors here, because each layer adds an
// additional layer of semantics. For example, `:has(:has(img))`
// doesn't match `<div><img></div>` but `:has(img)` does.
return [complex];
default:
return [];
}
});
// Older browsers support `:not`, but only with a single complex selector.
// In order to support those browsers, we break up the contents of a `:not`
// unless it originally contained a selector list.
if (pseudo.normalizedName == 'not' && selector.components.length == 1) {
var result = complexes
.map(
(complex) =>