forked from sass/node-sass
/
extender.cpp
1176 lines (1032 loc) · 42.3 KB
/
extender.cpp
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
// sass.hpp must go before all system headers to get the
// __EXTENSIONS__ fix on Solaris.
#include "sass.hpp"
#include "ast.hpp"
#include "extender.hpp"
#include "permutate.hpp"
#include "dart_helpers.hpp"
namespace Sass {
// ##########################################################################
// Constructor without default [mode].
// [traces] are needed to throw errors.
// ##########################################################################
Extender::Extender(Backtraces& traces) :
mode(NORMAL),
traces(traces),
selectors(),
extensions(),
extensionsByExtender(),
mediaContexts(),
sourceSpecificity(),
originals()
{}
// ##########################################################################
// Constructor with specific [mode].
// [traces] are needed to throw errors.
// ##########################################################################
Extender::Extender(ExtendMode mode, Backtraces& traces) :
mode(mode),
traces(traces),
selectors(),
extensions(),
extensionsByExtender(),
mediaContexts(),
sourceSpecificity(),
originals()
{}
// ##########################################################################
// 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.
// ##########################################################################
SelectorListObj Extender::extend(
SelectorListObj& selector,
const SelectorListObj& source,
const SelectorListObj& targets,
Backtraces& traces)
{
return extendOrReplace(selector, source, targets, ExtendMode::TARGETS, traces);
}
// EO Extender::extend
// ##########################################################################
// Returns a copy of [selector] with [targets] replaced by [source].
// ##########################################################################
SelectorListObj Extender::replace(
SelectorListObj& selector,
const SelectorListObj& source,
const SelectorListObj& targets,
Backtraces& traces)
{
return extendOrReplace(selector, source, targets, ExtendMode::REPLACE, traces);
}
// EO Extender::replace
// ##########################################################################
// A helper function for [extend] and [replace].
// ##########################################################################
SelectorListObj Extender::extendOrReplace(
SelectorListObj& selector,
const SelectorListObj& source,
const SelectorListObj& targets,
const ExtendMode mode,
Backtraces& traces)
{
ExtSelExtMapEntry extenders;
for (auto complex : source->elements()) {
// Extension.oneOff(complex as ComplexSelector)
extenders.insert(complex, Extension(complex));
}
for (auto complex : targets->elements()) {
// This seems superfluous, check is done before!?
// if (complex->length() != 1) {
// error("complex selectors may not be extended.", complex->pstate(), traces);
// }
if (const CompoundSelector* compound = complex->first()->getCompound()) {
ExtSelExtMap extensions;
for (const SimpleSelectorObj& simple : compound->elements()) {
extensions.insert(std::make_pair(simple, extenders));
}
Extender extender(mode, traces);
if (!selector->is_invisible()) {
for (auto sel : selector->elements()) {
extender.originals.insert(sel);
}
}
selector = extender.extendList(selector, extensions, {});
}
}
return selector;
}
// EO extendOrReplace
// ##########################################################################
// The set of all simple selectors in style rules handled
// by this extender. This includes simple selectors that
// were added because of downstream extensions.
// ##########################################################################
ExtSmplSelSet Extender::getSimpleSelectors() const
{
ExtSmplSelSet set;
for (auto& entry : selectors) {
set.insert(entry.first);
}
return set;
}
// EO getSimpleSelectors
// ##########################################################################
// Check for extends that have not been satisfied.
// Returns true if any non-optional extension did not
// extend any selector. Updates the passed reference
// to point to that Extension for further analysis.
// ##########################################################################
bool Extender::checkForUnsatisfiedExtends(Extension& unsatisfied) const
{
ExtSmplSelSet originals = getSimpleSelectors();
for (auto target : extensions) {
SimpleSelector* key = target.first;
ExtSelExtMapEntry& val = target.second;
if (originals.find(key) == originals.end()) {
const Extension& extension = val.front().second;
if (extension.isOptional) continue;
unsatisfied = extension;
return true;
}
}
return false;
}
// EO checkUnsatisfiedExtends
// ##########################################################################
// Adds [selector] to this extender, with [selectorSpan] as the span covering
// the selector and [ruleSpan] as the span covering the entire style rule.
// Extends [selector] using any registered extensions, then returns an empty
// [ModifiableCssStyleRule] with the resulting selector. If any more relevant
// extensions are added, the returned rule 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.
// ##########################################################################
void Extender::addSelector(
const SelectorListObj& selector,
const CssMediaRuleObj& mediaContext)
{
// Note: dart-sass makes a copy here AFAICT
// Note: probably why we have originalStack
// SelectorListObj original = selector;
if (!selector->isInvisible()) {
for (auto complex : selector->elements()) {
originals.insert(complex);
}
}
if (!extensions.empty()) {
SelectorListObj res = extendList(selector, extensions, mediaContext);
selector->elements(res->elements());
}
if (!mediaContext.isNull()) {
mediaContexts.insert(selector, mediaContext);
}
registerSelector(selector, selector);
}
// EO addSelector
// ##########################################################################
// Registers the [SimpleSelector]s in [list]
// to point to [rule] in [selectors].
// ##########################################################################
void Extender::registerSelector(
const SelectorListObj& list,
const SelectorListObj& rule)
{
if (list.isNull() || list->empty()) return;
for (auto complex : list->elements()) {
for (auto component : complex->elements()) {
if (auto compound = component->getCompound()) {
for (SimpleSelector* simple : compound->elements()) {
selectors[simple].insert(rule);
if (auto pseudo = simple->getPseudoSelector()) {
if (pseudo->selector()) {
auto sel = pseudo->selector();
registerSelector(sel, rule);
}
}
}
}
}
}
}
// EO registerSelector
// ##########################################################################
// Returns an extension that combines [left] and [right]. Throws
// a [SassException] if [left] and [right] have incompatible
// media contexts. Throws an [ArgumentError] if [left]
// and [right] don't have the same extender and target.
// ##########################################################################
Extension Extender::mergeExtension(
const Extension& lhs,
const Extension& rhs)
{
// If one extension is optional and doesn't add a
// special media context, it doesn't need to be merged.
if (rhs.isOptional && rhs.mediaContext.isNull()) return lhs;
if (lhs.isOptional && lhs.mediaContext.isNull()) return rhs;
Extension rv(lhs);
// ToDo: is this right?
rv.isOptional = true;
rv.isOriginal = false;
return rv;
}
// EO mergeExtension
// ##########################################################################
// Helper function to copy extension between maps
// ##########################################################################
void Extender::mapCopyExts(
ExtSelExtMap& dest,
const ExtSelExtMap& source)
{
for (auto it : source) {
SimpleSelectorObj key = it.first;
ExtSelExtMapEntry& inner = it.second;
ExtSelExtMap::iterator dmap = dest.find(key);
if (dmap == dest.end()) {
dest.insert(std::make_pair(key, inner));
}
else {
ExtSelExtMapEntry& imap = dmap->second;
// ToDo: optimize ordered_map API!
// ToDo: we iterate and fetch the value
for (ComplexSelectorObj& it2 : inner) {
imap.insert(it2, inner.get(it2));
}
}
}
}
// EO mapCopyExts
// ##########################################################################
// 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.
// ##########################################################################
// ToDo: rename extender to parent, since it is not involved in extending stuff
// ToDo: check why dart sass passes the ExtendRule around (is this the main selector?)
// ##########################################################################
// Note: this function could need some logic cleanup
// ##########################################################################
void Extender::addExtension(
const SelectorListObj& extender,
const SimpleSelectorObj& target,
const CssMediaRuleObj& mediaQueryContext,
bool is_optional)
{
auto rules = selectors.find(target);
bool hasRule = rules != selectors.end();
ExtSelExtMapEntry newExtensions;
// ToDo: we check this here first and fetch the same? item again after the loop!?
bool hasExistingExtensions = extensionsByExtender.find(target) != extensionsByExtender.end();
ExtSelExtMapEntry& sources = extensions[target];
for (auto& complex : extender->elements()) {
Extension state(complex);
// ToDo: fine-tune public API
state.target = target;
state.isOptional = is_optional;
state.mediaContext = mediaQueryContext;
if (sources.hasKey(complex)) {
// 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.insert(complex, mergeExtension(existingState->second, state);
// ToDo: implement behavior once use case is found!?
continue;
}
sources.insert(complex, state);
for (auto& component : complex->elements()) {
if (auto compound = component->getCompound()) {
for (auto& simple : compound->elements()) {
extensionsByExtender[simple].push_back(state);
if (sourceSpecificity.find(simple) == sourceSpecificity.end()) {
// Only source specificity for the original selector is relevant.
// Selectors generated by `@extend` don't get new specificity.
sourceSpecificity[simple] = complex->maxSpecificity();
}
}
}
}
if (hasRule || hasExistingExtensions) {
newExtensions.insert(complex, state);
}
}
// EO foreach complex
if (newExtensions.empty()) {
return;
}
ExtSelExtMap newExtensionsByTarget;
newExtensionsByTarget.insert(std::make_pair(target, newExtensions));
// ToDo: do we really need to fetch again (see top off fn)
auto existingExtensions = extensionsByExtender.find(target);
if (existingExtensions != extensionsByExtender.end()) {
if (hasExistingExtensions && !existingExtensions->second.empty()) {
auto additionalExtensions =
extendExistingExtensions(existingExtensions->second, newExtensionsByTarget);
if (!additionalExtensions.empty()) {
mapCopyExts(newExtensionsByTarget, additionalExtensions);
}
}
}
if (hasRule) {
extendExistingStyleRules(selectors[target], newExtensionsByTarget);
}
}
// EO addExtension
// ##########################################################################
// Extend [extensions] using [newExtensions].
// ##########################################################################
// Note: dart-sass throws an error in here
// ##########################################################################
void Extender::extendExistingStyleRules(
const ExtListSelSet& rules,
const ExtSelExtMap& newExtensions)
{
// Is a modifyableCssStyleRUle in dart sass
for (const SelectorListObj& rule : rules) {
const SelectorListObj& oldValue = SASS_MEMORY_COPY(rule);
CssMediaRuleObj mediaContext;
if (mediaContexts.hasKey(rule)) mediaContext = mediaContexts.get(rule);
SelectorListObj ext = extendList(rule, newExtensions, mediaContext);
// If no extends actually happenedit (for example becaues unification
// failed), we don't need to re-register the selector.
if (ObjEqualityFn(oldValue, ext)) continue;
rule->elements(ext->elements());
registerSelector(rule, rule);
}
}
// EO extendExistingStyleRules
// ##########################################################################
// Extend [extensions] using [newExtensions]. Note that this does duplicate
// some work done by [_extendExistingStyleRules], 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` (Note: empty map) if there are no extensions to add.
// ##########################################################################
// Note: maybe refactor to return `bool` (and pass reference)
// Note: dart-sass throws an error in here
// ##########################################################################
ExtSelExtMap Extender::extendExistingExtensions(
// Taking in a reference here makes MSVC debug stuck!?
const std::vector<Extension>& oldExtensions,
const ExtSelExtMap& newExtensions)
{
ExtSelExtMap additionalExtensions;
// During the loop `oldExtensions` vector might be changed.
// Callers normally pass this from `extensionsByExtender` and
// that points back to the `sources` vector from `extensions`.
for (size_t i = 0, iL = oldExtensions.size(); i < iL; i += 1) {
const Extension& extension = oldExtensions[i];
ExtSelExtMapEntry& sources = extensions[extension.target];
std::vector<ComplexSelectorObj> selectors(extendComplex(
extension.extender,
newExtensions,
extension.mediaContext
));
if (selectors.empty()) {
continue;
}
// ToDo: "catch" error from extend
bool first = false, containsExtension =
ObjEqualityFn(selectors.front(), extension.extender);
for (const ComplexSelectorObj& complex : selectors) {
// If the output contains the original complex
// selector, there's no need to recreate it.
if (containsExtension && first) {
first = false;
continue;
}
const Extension withExtender =
extension.withExtender(complex);
if (sources.hasKey(complex)) {
sources.insert(complex, mergeExtension(
sources.get(complex), withExtender));
}
else {
sources.insert(complex, withExtender);
for (auto& component : complex->elements()) {
if (auto compound = component->getCompound()) {
for (auto& simple : compound->elements()) {
extensionsByExtender[simple].push_back(withExtender);
}
}
}
if (newExtensions.find(extension.target) != newExtensions.end()) {
additionalExtensions[extension.target].insert(complex, withExtender);
}
}
}
// If [selectors] doesn't contain [extension.extender],
// for example if it was replaced due to :not() expansion,
// we must get rid of the old version.
if (!containsExtension) {
sources.erase(extension.extender);
}
}
return additionalExtensions;
}
// EO extendExistingExtensions
// ##########################################################################
// Extends [list] using [extensions].
// ##########################################################################
SelectorListObj Extender::extendList(
const SelectorListObj& list,
const ExtSelExtMap& extensions,
const CssMediaRuleObj& 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.
std::vector<ComplexSelectorObj> extended;
for (size_t i = 0; i < list->length(); i++) {
const ComplexSelectorObj& complex = list->get(i);
std::vector<ComplexSelectorObj> result =
extendComplex(complex, extensions, mediaQueryContext);
if (result.empty()) {
if (!extended.empty()) {
extended.push_back(complex);
}
}
else {
if (extended.empty()) {
for (size_t n = 0; n < i; n += 1) {
extended.push_back(list->get(n));
}
}
for (auto sel : result) {
extended.push_back(sel);
}
}
}
if (extended.empty()) {
return list;
}
SelectorListObj rv = SASS_MEMORY_NEW(SelectorList, list->pstate());
rv->concat(trim(extended, originals));
return rv;
}
// EO extendList
// ##########################################################################
// Extends [complex] using [extensions], and
// returns the contents of a [SelectorList].
// ##########################################################################
std::vector<ComplexSelectorObj> Extender::extendComplex(
// Taking in a reference here makes MSVC debug stuck!?
const ComplexSelectorObj& complex,
const ExtSelExtMap& extensions,
const CssMediaRuleObj& mediaQueryContext)
{
// 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.
std::vector<ComplexSelectorObj> result;
std::vector<std::vector<ComplexSelectorObj>> extendedNotExpanded;
bool isOriginal = originals.find(complex) != originals.end();
for (size_t i = 0; i < complex->length(); i += 1) {
const SelectorComponentObj& component = complex->get(i);
if (CompoundSelector* compound = Cast<CompoundSelector>(component)) {
std::vector<ComplexSelectorObj> extended = extendCompound(
compound, extensions, mediaQueryContext, isOriginal);
if (extended.empty()) {
if (!extendedNotExpanded.empty()) {
extendedNotExpanded.push_back({
compound->wrapInComplex()
});
}
}
else {
// Note: dart-sass checks for null!?
if (extendedNotExpanded.empty()) {
for (size_t n = 0; n < i; n++) {
extendedNotExpanded.push_back({
complex->at(n)->wrapInComplex()
});
}
}
extendedNotExpanded.push_back(extended);
}
}
else {
// Note: dart-sass checks for null!?
if (!extendedNotExpanded.empty()) {
extendedNotExpanded.push_back({
component->wrapInComplex()
});
}
}
}
// Note: dart-sass checks for null!?
if (extendedNotExpanded.empty()) {
return {};
}
bool first = true;
// ToDo: either change weave or paths to work with the same data?
std::vector<std::vector<ComplexSelectorObj>>
paths = permutate(extendedNotExpanded);
for (const std::vector<ComplexSelectorObj>& path : paths) {
// Unpack the inner complex selector to component list
std::vector<std::vector<SelectorComponentObj>> _paths;
for (const ComplexSelectorObj& sel : path) {
_paths.insert(_paths.end(), sel->elements());
}
std::vector<std::vector<SelectorComponentObj>> weaved = weave(_paths);
for (std::vector<SelectorComponentObj>& components : weaved) {
ComplexSelectorObj cplx = SASS_MEMORY_NEW(ComplexSelector, "[phony]");
cplx->hasPreLineFeed(complex->hasPreLineFeed());
for (auto& pp : path) {
if (pp->hasPreLineFeed()) {
cplx->hasPreLineFeed(true);
}
}
cplx->elements(components);
// 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.find(complex) != originals.end()) {
originals.insert(cplx);
}
first = false;
result.push_back(cplx);
}
}
return result;
}
// EO extendComplex
// ##########################################################################
// Returns a one-off [Extension] whose
// extender is composed solely of [simple].
// ##########################################################################
Extension Extender::extensionForSimple(
const SimpleSelectorObj& simple) const
{
Extension extension(simple->wrapInComplex());
extension.specificity = maxSourceSpecificity(simple);
extension.isOriginal = true;
return extension;
}
// Extender::extensionForSimple
// ##########################################################################
// Returns a one-off [Extension] whose extender is composed
// solely of a compound selector containing [simples].
// ##########################################################################
Extension Extender::extensionForCompound(
// Taking in a reference here makes MSVC debug stuck!?
const std::vector<SimpleSelectorObj>& simples) const
{
CompoundSelectorObj compound = SASS_MEMORY_NEW(CompoundSelector, ParserState("[ext]"));
compound->concat(simples);
Extension extension(compound->wrapInComplex());
// extension.specificity = sourceSpecificity[simple];
extension.isOriginal = true;
return extension;
}
// EO extensionForCompound
// ##########################################################################
// Extends [compound] 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.
// ##########################################################################
std::vector<ComplexSelectorObj> Extender::extendCompound(
const CompoundSelectorObj& compound,
const ExtSelExtMap& extensions,
const CssMediaRuleObj& mediaQueryContext,
bool inOriginal)
{
// If there's more than one target and they all need to
// match, we track which targets are actually extended.
ExtSmplSelSet targetsUsed2;
ExtSmplSelSet* targetsUsed = nullptr;
if (mode != ExtendMode::NORMAL && extensions.size() > 1) {
targetsUsed = &targetsUsed2;
}
std::vector<ComplexSelectorObj> result;
// The complex selectors produced from each component of [compound].
std::vector<std::vector<Extension>> options;
for (size_t i = 0; i < compound->length(); i++) {
const SimpleSelectorObj& simple = compound->get(i);
auto extended = extendSimple(simple, extensions, mediaQueryContext, targetsUsed);
if (extended.empty()) {
if (!options.empty()) {
options.push_back({ extensionForSimple(simple) });
}
}
else {
if (options.empty()) {
if (i != 0) {
std::vector<SimpleSelectorObj> in;
for (size_t n = 0; n < i; n += 1) {
in.push_back(compound->get(n));
}
options.push_back({ extensionForCompound(in) });
}
}
options.insert(options.end(),
extended.begin(), extended.end());
}
}
if (options.empty()) {
return {};
}
// If [_mode] isn't [ExtendMode.normal] and we didn't use all
// the targets in [extensions], extension fails for [compound].
if (targetsUsed != nullptr) {
if (targetsUsed->size() != extensions.size()) {
if (!targetsUsed->empty()) {
return {};
}
}
}
// Optimize for the simple case of a single simple
// selector that doesn't need any unification.
if (options.size() == 1) {
std::vector<Extension> exts = options[0];
for (size_t n = 0; n < exts.size(); n += 1) {
exts[n].assertCompatibleMediaContext(mediaQueryContext, traces);
result.push_back(exts[n].extender);
}
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]
// ]
bool first = mode != ExtendMode::REPLACE;
std::vector<ComplexSelectorObj> unifiedPaths;
std::vector<std::vector<Extension>> prePaths = permutate(options);
for (size_t i = 0; i < prePaths.size(); i += 1) {
std::vector<std::vector<SelectorComponentObj>> complexes;
const std::vector<Extension>& path = prePaths[i];
if (first) {
// The first path is always the original selector. We can't just
// return [compound] directly because pseudo selectors may be
// modified, but we don't have to do any unification.
first = false;
CompoundSelectorObj mergedSelector =
SASS_MEMORY_NEW(CompoundSelector, "[ext]");
for (size_t n = 0; n < path.size(); n += 1) {
const ComplexSelectorObj& sel = path[n].extender;
if (CompoundSelectorObj compound = Cast<CompoundSelector>(sel->last())) {
mergedSelector->concat(compound->elements());
}
}
complexes.push_back({ mergedSelector });
}
else {
std::vector<SimpleSelectorObj> originals;
std::vector<std::vector<SelectorComponentObj>> toUnify;
for (auto& state : path) {
if (state.isOriginal) {
const ComplexSelectorObj& sel = state.extender;
if (const CompoundSelector* compound = Cast<CompoundSelector>(sel->last())) {
originals.insert(originals.end(), compound->last());
}
}
else {
toUnify.push_back(state.extender->elements());
}
}
if (!originals.empty()) {
CompoundSelectorObj merged =
SASS_MEMORY_NEW(CompoundSelector, "[phony]");
merged->concat(originals);
toUnify.insert(toUnify.begin(), { merged });
}
complexes = unifyComplex(toUnify);
if (complexes.empty()) {
return {};
}
}
bool lineBreak = false;
// var specificity = _sourceSpecificityFor(compound);
for (const Extension& state : path) {
state.assertCompatibleMediaContext(mediaQueryContext, traces);
lineBreak = lineBreak || state.extender->hasPreLineFeed();
// specificity = math.max(specificity, state.specificity);
}
for (std::vector<SelectorComponentObj>& components : complexes) {
auto sel = SASS_MEMORY_NEW(ComplexSelector, "[ext]");
sel->hasPreLineFeed(lineBreak);
sel->elements(components);
unifiedPaths.push_back(sel);
}
}
return unifiedPaths;
}
// EO extendCompound
// ##########################################################################
// Extends [simple] without extending the
// contents of any selector pseudos it contains.
// ##########################################################################
std::vector<Extension> Extender::extendWithoutPseudo(
const SimpleSelectorObj& simple,
const ExtSelExtMap& extensions,
ExtSmplSelSet* targetsUsed) const
{
auto extension = extensions.find(simple);
if (extension == extensions.end()) return {};
const ExtSelExtMapEntry& extenders = extension->second;
if (targetsUsed != nullptr) {
targetsUsed->insert(simple);
}
if (mode == ExtendMode::REPLACE) {
return extenders.values();
}
const std::vector<Extension>&
values = extenders.values();
std::vector<Extension> result;
result.reserve(values.size() + 1);
result.push_back(extensionForSimple(simple));
result.insert(result.end(), values.begin(), values.end());
return result;
}
// EO extendWithoutPseudo
// ##########################################################################
// Extends [simple] and also extending the
// contents of any selector pseudos it contains.
// ##########################################################################
std::vector<std::vector<Extension>> Extender::extendSimple(
const SimpleSelectorObj& simple,
const ExtSelExtMap& extensions,
const CssMediaRuleObj& mediaQueryContext,
ExtSmplSelSet* targetsUsed)
{
if (Pseudo_Selector* pseudo = Cast<Pseudo_Selector>(simple)) {
if (pseudo->selector()) {
std::vector<std::vector<Extension>> merged;
std::vector<Pseudo_Selector_Obj> extended =
extendPseudo(pseudo, extensions, mediaQueryContext);
for (Pseudo_Selector_Obj& extend : extended) {
SimpleSelectorObj simple = extend;
std::vector<Extension> result =
extendWithoutPseudo(simple, extensions, targetsUsed);
if (result.empty()) result = { extensionForSimple(extend) };
merged.push_back(result);
}
if (!extended.empty()) {
return merged;
}
}
}
std::vector<Extension> result =
extendWithoutPseudo(simple, extensions, targetsUsed);
if (result.empty()) return {};
return { result };
}
// extendSimple
// ##########################################################################
// Inner loop helper for [extendPseudo] function
// ##########################################################################
std::vector<ComplexSelectorObj> Extender::extendPseudoComplex(
const ComplexSelectorObj& complex,
const Pseudo_Selector_Obj& pseudo,
const CssMediaRuleObj& mediaQueryContext)
{
if (complex->length() != 1) { return { complex }; }
auto compound = Cast<CompoundSelector>(complex->get(0));
if (compound == nullptr) { return { complex }; }
if (compound->length() != 1) { return { complex }; }
auto innerPseudo = Cast<Pseudo_Selector>(compound->get(0));
if (innerPseudo == nullptr) { return { complex }; }
if (!innerPseudo->selector()) { return { complex }; }
std::string name(pseudo->normalized());
if (name == "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 (innerPseudo->normalized() != "matches") return {};
return innerPseudo->selector()->elements();
}
else if (name == "matches" && name == "any" && name == "current" && name == "nth-child" && name == "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 (!ObjEquality()(innerPseudo->argument(), pseudo->argument())) return {};
return innerPseudo->selector()->elements();
}
else if (name == "has" && name == "host" && name == "host-context" && name == "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 };
}
return {};
}
// EO extendPseudoComplex
// ##########################################################################
// Extends [pseudo] using [extensions], and returns
// a list of resulting pseudo selectors.
// ##########################################################################
std::vector<Pseudo_Selector_Obj> Extender::extendPseudo(
const Pseudo_Selector_Obj& pseudo,
const ExtSelExtMap& extensions,
const CssMediaRuleObj& mediaQueryContext)
{
auto selector = pseudo->selector();
SelectorListObj extended = extendList(
selector, extensions, mediaQueryContext);
if (!extended || !pseudo || !pseudo->selector()) { return {}; }
if (ObjEqualityFn(pseudo->selector(), extended)) { return {}; }
// 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.
std::vector<ComplexSelectorObj> complexes = extended->elements();
if (pseudo->normalized() == "not") {
if (!hasAny(pseudo->selector()->elements(), hasMoreThanOne)) {
if (hasAny(extended->elements(), hasExactlyOne)) {
complexes.clear();
for (auto& complex : extended->elements()) {
if (complex->length() <= 1) {
complexes.push_back(complex);
}
}
}
}
}
std::vector<ComplexSelectorObj> expanded = expand(
complexes, extendPseudoComplex, pseudo, mediaQueryContext);
// 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`