/
SelectorChecker.cpp
1489 lines (1323 loc) · 65.7 KB
/
SelectorChecker.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
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
* Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
* Copyright (C) 2005-2016 Apple Inc. All rights reserved.
* Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
* Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
* Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
* Copyright (c) 2011, Code Aurora Forum. All rights reserved.
* Copyright (C) Research In Motion Limited 2011. All rights reserved.
* Copyright (C) 2014 Yusuke Suzuki <utatane.tea@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "SelectorChecker.h"
#include "CSSSelector.h"
#include "CSSSelectorList.h"
#include "CommonAtomStrings.h"
#include "Document.h"
#include "ElementInlines.h"
#include "ElementRareData.h"
#include "ElementTraversal.h"
#include "Frame.h"
#include "FrameSelection.h"
#include "HTMLDocument.h"
#include "HTMLNames.h"
#include "HTMLParserIdioms.h"
#include "HTMLSlotElement.h"
#include "InspectorInstrumentation.h"
#include "Page.h"
#include "RenderElement.h"
#include "RuleFeature.h"
#include "SelectorCheckerTestFunctions.h"
#include "ShadowRoot.h"
#include "StyleRule.h"
#include "StyleScope.h"
#include "Text.h"
#include "TypedElementDescendantIterator.h"
namespace WebCore {
using namespace HTMLNames;
enum class VisitedMatchType : unsigned char {
Disabled, Enabled
};
struct SelectorChecker::LocalContext {
LocalContext(const CSSSelector& selector, const Element& element, VisitedMatchType visitedMatchType, PseudoId pseudoId)
: selector(&selector)
, element(&element)
, visitedMatchType(visitedMatchType)
, firstSelectorOfTheFragment(&selector)
, pseudoId(pseudoId)
{ }
const CSSSelector* selector;
const Element* element;
VisitedMatchType visitedMatchType;
const CSSSelector* firstSelectorOfTheFragment;
PseudoId pseudoId;
bool isMatchElement { true };
bool isSubjectOrAdjacentElement { true };
bool inFunctionalPseudoClass { false };
bool pseudoElementEffective { true };
bool hasScrollbarPseudo { false };
bool hasSelectionPseudo { false };
bool mustMatchHostPseudoClass { false };
};
static inline void addStyleRelation(SelectorChecker::CheckingContext& checkingContext, const Element& element, Style::Relation::Type type, unsigned value = 1)
{
ASSERT(value == 1 || type == Style::Relation::NthChildIndex || type == Style::Relation::AffectedByEmpty);
if (checkingContext.resolvingMode != SelectorChecker::Mode::ResolvingStyle)
return;
if (type == Style::Relation::AffectsNextSibling && !checkingContext.styleRelations.isEmpty()) {
auto& last = checkingContext.styleRelations.last();
if (last.type == Style::Relation::AffectsNextSibling && last.element == element.nextElementSibling()) {
++last.value;
last.element = &element;
return;
}
}
checkingContext.styleRelations.append({ element, type, value });
}
static inline bool isFirstChildElement(const Element& element)
{
return !ElementTraversal::previousSibling(element);
}
static inline bool isLastChildElement(const Element& element)
{
return !ElementTraversal::nextSibling(element);
}
static inline bool isFirstOfType(const Element& element, const QualifiedName& type)
{
for (const Element* sibling = ElementTraversal::previousSibling(element); sibling; sibling = ElementTraversal::previousSibling(*sibling)) {
if (sibling->hasTagName(type))
return false;
}
return true;
}
static inline bool isLastOfType(const Element& element, const QualifiedName& type)
{
for (const Element* sibling = ElementTraversal::nextSibling(element); sibling; sibling = ElementTraversal::nextSibling(*sibling)) {
if (sibling->hasTagName(type))
return false;
}
return true;
}
static inline int countElementsBefore(const Element& element)
{
int count = 0;
for (const Element* sibling = ElementTraversal::previousSibling(element); sibling; sibling = ElementTraversal::previousSibling(*sibling)) {
unsigned index = sibling->childIndex();
if (index) {
count += index;
break;
}
count++;
}
return count;
}
static inline int countElementsOfTypeBefore(const Element& element, const QualifiedName& type)
{
int count = 0;
for (const Element* sibling = ElementTraversal::previousSibling(element); sibling; sibling = ElementTraversal::previousSibling(*sibling)) {
if (sibling->hasTagName(type))
++count;
}
return count;
}
static inline int countElementsAfter(const Element& element)
{
int count = 0;
for (const Element* sibling = ElementTraversal::nextSibling(element); sibling; sibling = ElementTraversal::nextSibling(*sibling))
++count;
return count;
}
static inline int countElementsOfTypeAfter(const Element& element, const QualifiedName& type)
{
int count = 0;
for (const Element* sibling = ElementTraversal::nextSibling(element); sibling; sibling = ElementTraversal::nextSibling(*sibling)) {
if (sibling->hasTagName(type))
++count;
}
return count;
}
SelectorChecker::SelectorChecker(Document& document)
: m_strictParsing(!document.inQuirksMode())
, m_documentIsHTML(document.isHTMLDocument())
{
}
bool SelectorChecker::match(const CSSSelector& selector, const Element& element, CheckingContext& checkingContext) const
{
LocalContext context(selector, element, checkingContext.resolvingMode == SelectorChecker::Mode::QueryingRules ? VisitedMatchType::Disabled : VisitedMatchType::Enabled, checkingContext.pseudoId);
if (checkingContext.styleScopeOrdinal == Style::ScopeOrdinal::Shadow) {
ASSERT(element.shadowRoot());
// Rules coming from the element's shadow tree must match :host pseudo class.
context.mustMatchHostPseudoClass = true;
}
PseudoIdSet pseudoIdSet;
MatchResult result = matchRecursively(checkingContext, context, pseudoIdSet);
if (result.match != Match::SelectorMatches)
return false;
if (checkingContext.pseudoId != PseudoId::None && !pseudoIdSet.has(checkingContext.pseudoId))
return false;
if (checkingContext.pseudoId == PseudoId::None && pseudoIdSet) {
PseudoIdSet publicPseudoIdSet = pseudoIdSet & PseudoIdSet::fromMask(static_cast<unsigned>(PseudoId::PublicPseudoIdMask));
if (checkingContext.resolvingMode == Mode::ResolvingStyle && publicPseudoIdSet)
checkingContext.pseudoIDSet = publicPseudoIdSet;
// When ignoring virtual pseudo elements, the context's pseudo should also be PseudoId::None but that does
// not cause a failure.
return checkingContext.resolvingMode == Mode::CollectingRulesIgnoringVirtualPseudoElements || result.matchType == MatchType::Element;
}
return true;
}
bool SelectorChecker::matchHostPseudoClass(const CSSSelector& selector, const Element& element, CheckingContext& checkingContext) const
{
if (!element.shadowRoot())
return false;
if (auto* selectorList = selector.selectorList()) {
LocalContext context(*selectorList->first(), element, VisitedMatchType::Enabled, PseudoId::None);
context.inFunctionalPseudoClass = true;
context.pseudoElementEffective = false;
PseudoIdSet ignoreDynamicPseudo;
if (matchRecursively(checkingContext, context, ignoreDynamicPseudo).match != Match::SelectorMatches)
return false;
}
return true;
}
inline static bool hasScrollbarPseudoElement(const PseudoIdSet& dynamicPseudoIdSet)
{
PseudoIdSet scrollbarIdSet = { PseudoId::Scrollbar, PseudoId::ScrollbarThumb, PseudoId::ScrollbarButton, PseudoId::ScrollbarTrack, PseudoId::ScrollbarTrackPiece, PseudoId::ScrollbarCorner };
if (dynamicPseudoIdSet & scrollbarIdSet)
return true;
// PseudoId::Resizer does not always have a scrollbar but it is a scrollbar-like pseudo element
// because it can have more than one pseudo element.
return dynamicPseudoIdSet.has(PseudoId::Resizer);
}
static SelectorChecker::LocalContext localContextForParent(const SelectorChecker::LocalContext& context)
{
SelectorChecker::LocalContext updatedContext(context);
// Disable :visited matching when we see the first link.
if (context.element->isLink())
updatedContext.visitedMatchType = VisitedMatchType::Disabled;
updatedContext.isMatchElement = false;
updatedContext.isSubjectOrAdjacentElement = false;
if (updatedContext.mustMatchHostPseudoClass) {
updatedContext.element = nullptr;
return updatedContext;
}
// Move to the shadow host if matching :host and the parent is the shadow root.
if (context.selector->match() == CSSSelector::PseudoClass && context.selector->pseudoClassType() == CSSSelector::PseudoClassHost && is<ShadowRoot>(context.element->parentNode())) {
updatedContext.element = downcast<ShadowRoot>(*context.element->parentNode()).host();
updatedContext.mustMatchHostPseudoClass = true;
return updatedContext;
}
updatedContext.element = context.element->parentElement();
return updatedContext;
}
// Recursive check of selectors and combinators
// It can return 4 different values:
// * SelectorMatches - the selector matches the element e
// * SelectorFailsLocally - the selector fails for the element e
// * SelectorFailsAllSiblings - the selector fails for e and any sibling of e
// * SelectorFailsCompletely - the selector fails for e and any sibling or ancestor of e
SelectorChecker::MatchResult SelectorChecker::matchRecursively(CheckingContext& checkingContext, const LocalContext& context, PseudoIdSet& dynamicPseudoIdSet) const
{
MatchType matchType = MatchType::Element;
// The first selector has to match.
if (!checkOne(checkingContext, context, matchType))
return MatchResult::fails(Match::SelectorFailsLocally);
if (context.selector->match() == CSSSelector::PseudoElement) {
if (context.selector->isCustomPseudoElement()) {
// In functional pseudo class, custom pseudo elements are always disabled.
// FIXME: We should accept custom pseudo elements inside :is()/:matches().
if (context.inFunctionalPseudoClass)
return MatchResult::fails(Match::SelectorFailsCompletely);
if (ShadowRoot* root = context.element->containingShadowRoot()) {
if (context.element->shadowPseudoId() != context.selector->value())
return MatchResult::fails(Match::SelectorFailsLocally);
if (context.selector->isWebKitCustomPseudoElement() && root->mode() != ShadowRootMode::UserAgent)
return MatchResult::fails(Match::SelectorFailsLocally);
} else
return MatchResult::fails(Match::SelectorFailsLocally);
} else {
if (!context.pseudoElementEffective)
return MatchResult::fails(Match::SelectorFailsCompletely);
if (checkingContext.resolvingMode == Mode::QueryingRules)
return MatchResult::fails(Match::SelectorFailsCompletely);
PseudoId pseudoId = CSSSelector::pseudoId(context.selector->pseudoElementType());
if (pseudoId != PseudoId::None)
dynamicPseudoIdSet.add(pseudoId);
matchType = MatchType::VirtualPseudoElementOnly;
}
}
// The rest of the selectors has to match
auto relation = context.selector->relation();
// Prepare next selector
const CSSSelector* leftSelector = context.selector->tagHistory();
if (!leftSelector)
return MatchResult::matches(matchType);
LocalContext nextContext(context);
nextContext.selector = leftSelector;
if (relation != CSSSelector::Subselector) {
// Bail-out if this selector is irrelevant for the pseudoId
if (context.pseudoId != PseudoId::None && !dynamicPseudoIdSet.has(context.pseudoId))
return MatchResult::fails(Match::SelectorFailsCompletely);
// Disable :visited matching when we try to match anything else than an ancestors.
if (!context.selector->hasDescendantOrChildRelation())
nextContext.visitedMatchType = VisitedMatchType::Disabled;
nextContext.pseudoId = PseudoId::None;
bool allowMultiplePseudoElements = relation == CSSSelector::ShadowDescendant;
// Virtual pseudo element is only effective in the rightmost fragment.
if (!allowMultiplePseudoElements)
nextContext.pseudoElementEffective = false;
nextContext.isMatchElement = false;
}
switch (relation) {
case CSSSelector::DescendantSpace:
nextContext = localContextForParent(nextContext);
nextContext.firstSelectorOfTheFragment = nextContext.selector;
for (; nextContext.element; nextContext = localContextForParent(nextContext)) {
PseudoIdSet ignoreDynamicPseudo;
MatchResult result = matchRecursively(checkingContext, nextContext, ignoreDynamicPseudo);
ASSERT(!nextContext.pseudoElementEffective && !ignoreDynamicPseudo);
if (result.match == Match::SelectorMatches || result.match == Match::SelectorFailsCompletely)
return MatchResult::updateWithMatchType(result, matchType);
}
return MatchResult::fails(Match::SelectorFailsCompletely);
case CSSSelector::Child:
{
nextContext = localContextForParent(nextContext);
if (!nextContext.element)
return MatchResult::fails(Match::SelectorFailsCompletely);
nextContext.firstSelectorOfTheFragment = nextContext.selector;
PseudoIdSet ignoreDynamicPseudo;
MatchResult result = matchRecursively(checkingContext, nextContext, ignoreDynamicPseudo);
ASSERT(!nextContext.pseudoElementEffective && !ignoreDynamicPseudo);
if (result.match == Match::SelectorMatches || result.match == Match::SelectorFailsCompletely)
return MatchResult::updateWithMatchType(result, matchType);
return MatchResult::fails(Match::SelectorFailsAllSiblings);
}
case CSSSelector::DirectAdjacent:
{
auto relation = context.isMatchElement ? Style::Relation::AffectedByPreviousSibling : Style::Relation::DescendantsAffectedByPreviousSibling;
addStyleRelation(checkingContext, *context.element, relation);
Element* previousElement = context.element->previousElementSibling();
if (!previousElement)
return MatchResult::fails(Match::SelectorFailsAllSiblings);
addStyleRelation(checkingContext, *previousElement, Style::Relation::AffectsNextSibling);
nextContext.element = previousElement;
nextContext.firstSelectorOfTheFragment = nextContext.selector;
PseudoIdSet ignoreDynamicPseudo;
MatchResult result = matchRecursively(checkingContext, nextContext, ignoreDynamicPseudo);
ASSERT(!nextContext.pseudoElementEffective && !ignoreDynamicPseudo);
return MatchResult::updateWithMatchType(result, matchType);
}
case CSSSelector::IndirectAdjacent: {
auto relation = context.isMatchElement ? Style::Relation::AffectedByPreviousSibling : Style::Relation::DescendantsAffectedByPreviousSibling;
addStyleRelation(checkingContext, *context.element, relation);
nextContext.element = context.element->previousElementSibling();
nextContext.firstSelectorOfTheFragment = nextContext.selector;
for (; nextContext.element; nextContext.element = nextContext.element->previousElementSibling()) {
addStyleRelation(checkingContext, *nextContext.element, Style::Relation::AffectsNextSibling);
PseudoIdSet ignoreDynamicPseudo;
MatchResult result = matchRecursively(checkingContext, nextContext, ignoreDynamicPseudo);
ASSERT(!nextContext.pseudoElementEffective && !ignoreDynamicPseudo);
if (result.match == Match::SelectorMatches || result.match == Match::SelectorFailsAllSiblings || result.match == Match::SelectorFailsCompletely)
return MatchResult::updateWithMatchType(result, matchType);
};
return MatchResult::fails(Match::SelectorFailsAllSiblings);
}
case CSSSelector::Subselector:
{
// a selector is invalid if something follows a pseudo-element
// We make an exception for scrollbar pseudo elements and allow a set of pseudo classes (but nothing else)
// to follow the pseudo elements.
nextContext.hasScrollbarPseudo = hasScrollbarPseudoElement(dynamicPseudoIdSet);
nextContext.hasSelectionPseudo = dynamicPseudoIdSet.has(PseudoId::Selection);
if ((context.isMatchElement || checkingContext.resolvingMode == Mode::CollectingRules) && dynamicPseudoIdSet
&& !nextContext.hasSelectionPseudo
&& !(nextContext.hasScrollbarPseudo && nextContext.selector->match() == CSSSelector::PseudoClass))
return MatchResult::fails(Match::SelectorFailsCompletely);
MatchResult result = matchRecursively(checkingContext, nextContext, dynamicPseudoIdSet);
return MatchResult::updateWithMatchType(result, matchType);
}
case CSSSelector::ShadowDescendant: {
auto* host = context.element->shadowHost();
if (!host)
return MatchResult::fails(Match::SelectorFailsCompletely);
nextContext.element = host;
nextContext.firstSelectorOfTheFragment = nextContext.selector;
nextContext.isSubjectOrAdjacentElement = false;
PseudoIdSet ignoreDynamicPseudo;
MatchResult result = matchRecursively(checkingContext, nextContext, ignoreDynamicPseudo);
return MatchResult::updateWithMatchType(result, matchType);
}
case CSSSelector::ShadowPartDescendant: {
// Continue matching in the scope where this rule came from.
auto* host = checkingContext.styleScopeOrdinal == Style::ScopeOrdinal::Element
? context.element->shadowHost()
: Style::hostForScopeOrdinal(*context.element, checkingContext.styleScopeOrdinal);
if (!host)
return MatchResult::fails(Match::SelectorFailsCompletely);
nextContext.element = host;
nextContext.firstSelectorOfTheFragment = nextContext.selector;
nextContext.isSubjectOrAdjacentElement = false;
// ::part rules from the element's own scope can only match if they apply to :host.
nextContext.mustMatchHostPseudoClass = checkingContext.styleScopeOrdinal == Style::ScopeOrdinal::Element;
PseudoIdSet ignoreDynamicPseudo;
MatchResult result = matchRecursively(checkingContext, nextContext, ignoreDynamicPseudo);
return MatchResult::updateWithMatchType(result, matchType);
}
case CSSSelector::ShadowSlotted: {
// We continue matching in the scope where this rule came from.
auto slot = Style::assignedSlotForScopeOrdinal(*context.element, checkingContext.styleScopeOrdinal);
if (!slot)
return MatchResult::fails(Match::SelectorFailsCompletely);
nextContext.element = slot;
nextContext.firstSelectorOfTheFragment = nextContext.selector;
nextContext.isSubjectOrAdjacentElement = false;
PseudoIdSet ignoreDynamicPseudo;
MatchResult result = matchRecursively(checkingContext, nextContext, ignoreDynamicPseudo);
return MatchResult::updateWithMatchType(result, matchType);
}
}
ASSERT_NOT_REACHED();
return MatchResult::fails(Match::SelectorFailsCompletely);
}
static bool attributeValueMatches(const Attribute& attribute, CSSSelector::Match match, const AtomString& selectorValue, bool caseSensitive)
{
const AtomString& value = attribute.value();
ASSERT(!value.isNull());
switch (match) {
case CSSSelector::Set:
break;
case CSSSelector::Exact:
if (caseSensitive ? selectorValue != value : !equalIgnoringASCIICase(selectorValue, value))
return false;
break;
case CSSSelector::List:
{
// Ignore empty selectors or selectors containing spaces.
if (selectorValue.isEmpty() || selectorValue.find(isHTMLSpace<UChar>) != notFound)
return false;
unsigned startSearchAt = 0;
while (true) {
size_t foundPos;
if (caseSensitive)
foundPos = value.find(selectorValue, startSearchAt);
else
foundPos = value.findIgnoringASCIICase(selectorValue, startSearchAt);
if (foundPos == notFound)
return false;
if (!foundPos || isHTMLSpace(value[foundPos - 1])) {
unsigned endStr = foundPos + selectorValue.length();
if (endStr == value.length() || isHTMLSpace(value[endStr]))
break; // We found a match.
}
// No match. Keep looking.
startSearchAt = foundPos + 1;
}
break;
}
case CSSSelector::Contain: {
bool valueContainsSelectorValue;
if (caseSensitive)
valueContainsSelectorValue = value.contains(selectorValue);
else
valueContainsSelectorValue = value.containsIgnoringASCIICase(selectorValue);
if (!valueContainsSelectorValue || selectorValue.isEmpty())
return false;
break;
}
case CSSSelector::Begin:
if (selectorValue.isEmpty())
return false;
if (caseSensitive) {
if (!value.startsWith(selectorValue))
return false;
} else {
if (!value.startsWithIgnoringASCIICase(selectorValue))
return false;
}
break;
case CSSSelector::End:
if (selectorValue.isEmpty())
return false;
if (caseSensitive) {
if (!value.endsWith(selectorValue))
return false;
} else {
if (!value.endsWithIgnoringASCIICase(selectorValue))
return false;
}
break;
case CSSSelector::Hyphen:
if (value.length() < selectorValue.length())
return false;
if (caseSensitive) {
if (!value.startsWith(selectorValue))
return false;
} else {
if (!value.startsWithIgnoringASCIICase(selectorValue))
return false;
}
// It they start the same, check for exact match or following '-':
if (value.length() != selectorValue.length() && value[selectorValue.length()] != '-')
return false;
break;
default:
ASSERT_NOT_REACHED();
return false;
}
return true;
}
static bool anyAttributeMatches(const Element& element, const CSSSelector& selector, const QualifiedName& selectorAttr, bool caseSensitive)
{
ASSERT(element.hasAttributesWithoutUpdate());
for (const Attribute& attribute : element.attributesIterator()) {
if (!attribute.matches(selectorAttr.prefix(), element.isHTMLElement() ? selector.attributeCanonicalLocalName() : selectorAttr.localName(), selectorAttr.namespaceURI()))
continue;
if (attributeValueMatches(attribute, selector.match(), selector.value(), caseSensitive))
return true;
}
return false;
}
bool SelectorChecker::attributeSelectorMatches(const Element& element, const QualifiedName& attributeName, const AtomString& attributeValue, const CSSSelector& selector)
{
ASSERT(selector.isAttributeSelector());
auto& selectorAttribute = selector.attribute();
auto& selectorName = element.isHTMLElement() ? selector.attributeCanonicalLocalName() : selectorAttribute.localName();
if (!Attribute::nameMatchesFilter(attributeName, selectorAttribute.prefix(), selectorName, selectorAttribute.namespaceURI()))
return false;
bool caseSensitive = true;
if (selector.attributeValueMatchingIsCaseInsensitive())
caseSensitive = false;
else if (element.document().isHTMLDocument() && element.isHTMLElement() && !HTMLDocument::isCaseSensitiveAttribute(selector.attribute()))
caseSensitive = false;
return attributeValueMatches(Attribute(attributeName, attributeValue), selector.match(), selector.value(), caseSensitive);
}
static bool canMatchHoverOrActiveInQuirksMode(const SelectorChecker::LocalContext& context)
{
// For quirks mode, follow this: http://quirks.spec.whatwg.org/#the-:active-and-:hover-quirk
// In quirks mode, a compound selector 'selector' that matches the following conditions must not match elements that would not also match the ':any-link' selector.
//
// selector uses the ':active' or ':hover' pseudo-classes.
// selector does not use a type selector.
// selector does not use an attribute selector.
// selector does not use an ID selector.
// selector does not use a class selector.
// selector does not use a pseudo-class selector other than ':active' and ':hover'.
// selector does not use a pseudo-element selector.
// selector is not part of an argument to a functional pseudo-class or pseudo-element.
if (context.inFunctionalPseudoClass)
return true;
for (const CSSSelector* selector = context.firstSelectorOfTheFragment; selector; selector = selector->tagHistory()) {
switch (selector->match()) {
case CSSSelector::Tag:
if (selector->tagQName() != anyQName())
return true;
break;
case CSSSelector::PseudoClass: {
CSSSelector::PseudoClassType pseudoClassType = selector->pseudoClassType();
if (pseudoClassType != CSSSelector::PseudoClassHover && pseudoClassType != CSSSelector::PseudoClassActive)
return true;
break;
}
case CSSSelector::Id:
case CSSSelector::Class:
case CSSSelector::Exact:
case CSSSelector::Set:
case CSSSelector::List:
case CSSSelector::Hyphen:
case CSSSelector::Contain:
case CSSSelector::Begin:
case CSSSelector::End:
case CSSSelector::PagePseudoClass:
case CSSSelector::PseudoElement:
return true;
case CSSSelector::Unknown:
ASSERT_NOT_REACHED();
break;
}
auto relation = selector->relation();
if (relation == CSSSelector::ShadowDescendant || relation == CSSSelector::ShadowPartDescendant)
return true;
if (relation != CSSSelector::Subselector)
return false;
}
return false;
}
static inline bool tagMatches(const Element& element, const CSSSelector& simpleSelector)
{
const QualifiedName& tagQName = simpleSelector.tagQName();
if (tagQName == anyQName())
return true;
const AtomString& localName = (element.isHTMLElement() && element.document().isHTMLDocument()) ? simpleSelector.tagLowercaseLocalName() : tagQName.localName();
if (localName != starAtom() && localName != element.localName())
return false;
const AtomString& namespaceURI = tagQName.namespaceURI();
return namespaceURI == starAtom() || namespaceURI == element.namespaceURI();
}
bool SelectorChecker::checkOne(CheckingContext& checkingContext, const LocalContext& context, MatchType& matchType) const
{
const Element& element = *context.element;
const CSSSelector& selector = *context.selector;
if (context.mustMatchHostPseudoClass) {
// :host doesn't combine with anything except pseudo elements.
bool isHostPseudoClass = selector.match() == CSSSelector::PseudoClass && selector.pseudoClassType() == CSSSelector::PseudoClassHost;
bool isPseudoElement = selector.match() == CSSSelector::PseudoElement;
if (!isHostPseudoClass && !isPseudoElement)
return false;
}
if (selector.match() == CSSSelector::Tag)
return tagMatches(element, selector);
if (selector.match() == CSSSelector::Class)
return element.hasClass() && element.classNames().contains(selector.value());
if (selector.match() == CSSSelector::Id) {
ASSERT(!selector.value().isNull());
return element.idForStyleResolution() == selector.value();
}
if (selector.isAttributeSelector()) {
if (!element.hasAttributes())
return false;
const QualifiedName& attr = selector.attribute();
bool caseSensitive = true;
if (selector.attributeValueMatchingIsCaseInsensitive())
caseSensitive = false;
else if (m_documentIsHTML && element.isHTMLElement() && !HTMLDocument::isCaseSensitiveAttribute(attr))
caseSensitive = false;
return anyAttributeMatches(element, selector, attr, caseSensitive);
}
if (selector.match() == CSSSelector::PseudoClass) {
// Handle :not up front.
if (selector.pseudoClassType() == CSSSelector::PseudoClassNot) {
const CSSSelectorList* selectorList = selector.selectorList();
for (const CSSSelector* subselector = selectorList->first(); subselector; subselector = CSSSelectorList::next(subselector)) {
LocalContext subcontext(context);
subcontext.inFunctionalPseudoClass = true;
subcontext.pseudoElementEffective = false;
subcontext.selector = subselector;
subcontext.firstSelectorOfTheFragment = selectorList->first();
PseudoIdSet ignoreDynamicPseudo;
if (matchRecursively(checkingContext, subcontext, ignoreDynamicPseudo).match == Match::SelectorMatches) {
ASSERT(!ignoreDynamicPseudo);
return false;
}
}
return true;
}
if (context.hasScrollbarPseudo) {
// CSS scrollbars match a specific subset of pseudo classes, and they have specialized rules for each
// (since there are no elements involved except with window-inactive).
return checkScrollbarPseudoClass(checkingContext, element, selector);
}
// Normal element pseudo class checking.
switch (selector.pseudoClassType()) {
// Pseudo classes:
case CSSSelector::PseudoClassNot:
break; // Already handled up above.
case CSSSelector::PseudoClassEmpty:
{
bool result = true;
for (Node* node = element.firstChild(); node; node = node->nextSibling()) {
if (is<Element>(*node)) {
result = false;
break;
}
if (is<Text>(*node)) {
Text& textNode = downcast<Text>(*node);
if (!textNode.data().isEmpty()) {
result = false;
break;
}
}
}
addStyleRelation(checkingContext, *context.element, Style::Relation::AffectedByEmpty, result);
return result;
}
case CSSSelector::PseudoClassFirstChild: {
// first-child matches the first child that is an element
bool isFirstChild = isFirstChildElement(element);
auto* parent = element.parentNode();
if (is<Element>(parent))
addStyleRelation(checkingContext, downcast<Element>(*parent), Style::Relation::ChildrenAffectedByFirstChildRules);
else if (!is<ShadowRoot>(parent))
break; // FIXME: Add the support for specifying relations on ShadowRoot.
if (!isFirstChild)
break;
addStyleRelation(checkingContext, element, Style::Relation::FirstChild);
return true;
}
case CSSSelector::PseudoClassFirstOfType: {
// first-of-type matches the first element of its type
auto* parent = element.parentNode();
if (is<Element>(parent)) {
auto relation = context.isSubjectOrAdjacentElement ? Style::Relation::ChildrenAffectedByForwardPositionalRules : Style::Relation::DescendantsAffectedByForwardPositionalRules;
addStyleRelation(checkingContext, downcast<Element>(*parent), relation);
} else if (!is<ShadowRoot>(parent))
break; // FIXME: Add the support for specifying relations on ShadowRoot.
return isFirstOfType(element, element.tagQName());
}
case CSSSelector::PseudoClassLastChild: {
// last-child matches the last child that is an element
auto* parent = element.parentNode();
bool isLastChild = isLastChildElement(element);
if (is<Element>(parent)) {
auto& parentElement = downcast<Element>(*parent);
if (!parentElement.isFinishedParsingChildren())
isLastChild = false;
addStyleRelation(checkingContext, parentElement, Style::Relation::ChildrenAffectedByLastChildRules);
} else if (!is<ShadowRoot>(parent))
break; // FIXME: Add the support for specifying relations on ShadowRoot.
if (!isLastChild)
break;
addStyleRelation(checkingContext, element, Style::Relation::LastChild);
return true;
}
case CSSSelector::PseudoClassLastOfType: {
// last-of-type matches the last element of its type
auto* parent = element.parentNode();
if (is<Element>(parent)) {
auto& parentElement = downcast<Element>(*parent);
auto relation = context.isSubjectOrAdjacentElement ? Style::Relation::ChildrenAffectedByBackwardPositionalRules : Style::Relation::DescendantsAffectedByBackwardPositionalRules;
addStyleRelation(checkingContext, parentElement, relation);
if (!parentElement.isFinishedParsingChildren())
return false;
} else if (!is<ShadowRoot>(parent))
break; // FIXME: Add the support for specifying relations on ShadowRoot.
return isLastOfType(element, element.tagQName());
}
case CSSSelector::PseudoClassOnlyChild: {
auto* parent = element.parentNode();
bool firstChild = isFirstChildElement(element);
bool onlyChild = firstChild && isLastChildElement(element);
if (is<Element>(parent)) {
auto& parentElement = downcast<Element>(*parent);
addStyleRelation(checkingContext, parentElement, Style::Relation::ChildrenAffectedByFirstChildRules);
addStyleRelation(checkingContext, parentElement, Style::Relation::ChildrenAffectedByLastChildRules);
if (!parentElement.isFinishedParsingChildren())
onlyChild = false;
} else if (!is<ShadowRoot>(parent))
break; // FIXME: Add the support for specifying relations on ShadowRoot.
if (firstChild)
addStyleRelation(checkingContext, element, Style::Relation::FirstChild);
if (onlyChild)
addStyleRelation(checkingContext, element, Style::Relation::LastChild);
return onlyChild;
}
case CSSSelector::PseudoClassOnlyOfType: {
// FIXME: This selector is very slow.
auto* parent = element.parentNode();
if (is<Element>(parent)) {
auto& parentElement = downcast<Element>(*parent);
auto forwardRelation = context.isSubjectOrAdjacentElement ? Style::Relation::ChildrenAffectedByForwardPositionalRules : Style::Relation::DescendantsAffectedByForwardPositionalRules;
addStyleRelation(checkingContext, parentElement, forwardRelation);
auto backwardRelation = context.isSubjectOrAdjacentElement ? Style::Relation::ChildrenAffectedByBackwardPositionalRules : Style::Relation::DescendantsAffectedByBackwardPositionalRules;
addStyleRelation(checkingContext, parentElement, backwardRelation);
if (!parentElement.isFinishedParsingChildren())
return false;
} else if (!is<ShadowRoot>(parent))
break; // FIXME: Add the support for specifying relations on ShadowRoot.
return isFirstOfType(element, element.tagQName()) && isLastOfType(element, element.tagQName());
}
case CSSSelector::PseudoClassIs:
case CSSSelector::PseudoClassWhere:
case CSSSelector::PseudoClassMatches:
case CSSSelector::PseudoClassAny:
{
bool hasMatchedAnything = false;
MatchType localMatchType = MatchType::VirtualPseudoElementOnly;
for (const CSSSelector* subselector = selector.selectorList()->first(); subselector; subselector = CSSSelectorList::next(subselector)) {
LocalContext subcontext(context);
subcontext.inFunctionalPseudoClass = true;
subcontext.pseudoElementEffective = context.pseudoElementEffective;
subcontext.selector = subselector;
subcontext.firstSelectorOfTheFragment = subselector;
subcontext.pseudoId = PseudoId::None;
PseudoIdSet localDynamicPseudoIdSet;
MatchResult result = matchRecursively(checkingContext, subcontext, localDynamicPseudoIdSet);
// Pseudo elements are not valid inside :is()/:matches()
if (localDynamicPseudoIdSet)
continue;
if (result.match == Match::SelectorMatches) {
if (result.matchType == MatchType::Element)
localMatchType = MatchType::Element;
hasMatchedAnything = true;
}
}
if (hasMatchedAnything)
matchType = localMatchType;
return hasMatchedAnything;
}
case CSSSelector::PseudoClassHas: {
for (auto* hasSelector = selector.selectorList()->first(); hasSelector; hasSelector = CSSSelectorList::next(hasSelector)) {
if (matchHasPseudoClass(checkingContext, element, *hasSelector))
return true;
}
return false;
}
case CSSSelector::PseudoClassPlaceholderShown:
if (is<HTMLTextFormControlElement>(element)) {
addStyleRelation(checkingContext, element, Style::Relation::Unique);
return downcast<HTMLTextFormControlElement>(element).isPlaceholderVisible();
}
return false;
case CSSSelector::PseudoClassNthChild: {
auto* parent = element.parentNode();
if (is<Element>(parent)) {
auto relation = context.isSubjectOrAdjacentElement ? Style::Relation::ChildrenAffectedByForwardPositionalRules : Style::Relation::DescendantsAffectedByForwardPositionalRules;
addStyleRelation(checkingContext, downcast<Element>(*parent), relation);
} else if (!is<ShadowRoot>(parent))
break; // FIXME: Add the support for specifying relations on ShadowRoot.
if (const CSSSelectorList* selectorList = selector.selectorList()) {
if (!matchSelectorList(checkingContext, context, element, *selectorList))
return false;
}
int count = 1;
if (const CSSSelectorList* selectorList = selector.selectorList()) {
for (Element* sibling = ElementTraversal::previousSibling(element); sibling; sibling = ElementTraversal::previousSibling(*sibling)) {
if (matchSelectorList(checkingContext, context, *sibling, *selectorList))
++count;
}
} else {
count += countElementsBefore(element);
addStyleRelation(checkingContext, element, Style::Relation::NthChildIndex, count);
}
if (selector.matchNth(count))
return true;
break;
}
case CSSSelector::PseudoClassNthOfType: {
auto* parent = element.parentNode();
if (is<Element>(parent)) {
auto relation = context.isSubjectOrAdjacentElement ? Style::Relation::ChildrenAffectedByForwardPositionalRules : Style::Relation::DescendantsAffectedByForwardPositionalRules;
addStyleRelation(checkingContext, downcast<Element>(*parent), relation);
} else if (!is<ShadowRoot>(parent))
break; // FIXME: Add the support for specifying relations on ShadowRoot.
int count = 1 + countElementsOfTypeBefore(element, element.tagQName());
if (selector.matchNth(count))
return true;
break;
}
case CSSSelector::PseudoClassNthLastChild: {
auto* parent = element.parentNode();
if (is<Element>(parent)) {
auto& parentElement = downcast<Element>(*parent);
if (const CSSSelectorList* selectorList = selector.selectorList()) {
if (!matchSelectorList(checkingContext, context, element, *selectorList))
return false;
addStyleRelation(checkingContext, parentElement, Style::Relation::ChildrenAffectedByPropertyBasedBackwardPositionalRules);
} else {
auto relation = context.isSubjectOrAdjacentElement ? Style::Relation::ChildrenAffectedByBackwardPositionalRules : Style::Relation::DescendantsAffectedByBackwardPositionalRules;
addStyleRelation(checkingContext, parentElement, relation);
}
if (!parentElement.isFinishedParsingChildren())
return false;
} else if (!is<ShadowRoot>(parent))
break; // FIXME: Add the support for specifying relations on ShadowRoot.
int count = 1;
if (const CSSSelectorList* selectorList = selector.selectorList()) {
for (Element* sibling = ElementTraversal::nextSibling(element); sibling; sibling = ElementTraversal::nextSibling(*sibling)) {
if (matchSelectorList(checkingContext, context, *sibling, *selectorList))
++count;
}
} else
count += countElementsAfter(element);
return selector.matchNth(count);
}
case CSSSelector::PseudoClassNthLastOfType: {
auto* parent = element.parentNode();
if (is<Element>(parent)) {
auto& parentElement = downcast<Element>(*parent);
auto relation = context.isSubjectOrAdjacentElement ? Style::Relation::ChildrenAffectedByBackwardPositionalRules : Style::Relation::DescendantsAffectedByBackwardPositionalRules;
addStyleRelation(checkingContext, parentElement, relation);
if (!parentElement.isFinishedParsingChildren())
return false;
} else if (!is<ShadowRoot>(parent))
break; // FIXME: Add the support for specifying relations on ShadowRoot.
int count = 1 + countElementsOfTypeAfter(element, element.tagQName());
return selector.matchNth(count);
}
case CSSSelector::PseudoClassTarget:
if (&element == element.document().cssTarget() || InspectorInstrumentation::forcePseudoState(element, CSSSelector::PseudoClassTarget))
return true;
break;
case CSSSelector::PseudoClassAutofill:
return isAutofilled(element);
case CSSSelector::PseudoClassAutofillAndObscured:
return isAutofilledAndObscured(element);
case CSSSelector::PseudoClassAutofillStrongPassword:
return isAutofilledStrongPassword(element);
case CSSSelector::PseudoClassAutofillStrongPasswordViewable:
return isAutofilledStrongPasswordViewable(element);
case CSSSelector::PseudoClassAnyLink:
case CSSSelector::PseudoClassAnyLinkDeprecated:
case CSSSelector::PseudoClassLink:
// :visited and :link matches are separated later when applying the style. Here both classes match all links...
return element.isLink();
case CSSSelector::PseudoClassVisited:
// ...except if :visited matching is disabled for ancestor/sibling matching.
// Inside functional pseudo class except for :not, :visited never matches.
if (context.inFunctionalPseudoClass)
return false;
return element.isLink() && context.visitedMatchType == VisitedMatchType::Enabled;
case CSSSelector::PseudoClassDrag:
return element.isBeingDragged();
case CSSSelector::PseudoClassFocus:
return matchesFocusPseudoClass(element);
case CSSSelector::PseudoClassFocusVisible:
return matchesFocusVisiblePseudoClass(element);
case CSSSelector::PseudoClassFocusWithin:
return matchesFocusWithinPseudoClass(element);
case CSSSelector::PseudoClassHover:
if (m_strictParsing || element.isLink() || canMatchHoverOrActiveInQuirksMode(context)) {
// See the comment in generateElementIsHovered() in SelectorCompiler.
if (checkingContext.resolvingMode == SelectorChecker::Mode::CollectingRulesIgnoringVirtualPseudoElements && !context.isMatchElement)
return true;