-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
selector_checker.cc
2052 lines (1880 loc) · 81.6 KB
/
selector_checker.cc
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, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 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.
*
* 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 "third_party/blink/renderer/core/css/selector_checker.h"
#include "base/auto_reset.h"
#include "third_party/blink/public/mojom/input/focus_type.mojom-blink.h"
#include "third_party/blink/renderer/core/css/check_pseudo_has_argument_context.h"
#include "third_party/blink/renderer/core/css/check_pseudo_has_cache_scope.h"
#include "third_party/blink/renderer/core/css/css_selector_list.h"
#include "third_party/blink/renderer/core/css/part_names.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/nth_index_cache.h"
#include "third_party/blink/renderer/core/dom/popup_data.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/dom/toggle.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/picture_in_picture_controller.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen.h"
#include "third_party/blink/renderer/core/html/custom/element_internals.h"
#include "third_party/blink/renderer/core/html/forms/html_form_control_element.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/forms/html_option_element.h"
#include "third_party/blink/renderer/core/html/forms/html_select_element.h"
#include "third_party/blink/renderer/core/html/html_dialog_element.h"
#include "third_party/blink/renderer/core/html/html_document.h"
#include "third_party/blink/renderer/core/html/html_frame_element_base.h"
#include "third_party/blink/renderer/core/html/html_slot_element.h"
#include "third_party/blink/renderer/core/html/media/html_video_element.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
#include "third_party/blink/renderer/core/html/shadow/shadow_element_names.h"
#include "third_party/blink/renderer/core/html/track/vtt/vtt_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/scrolling/fragment_anchor.h"
#include "third_party/blink/renderer/core/page/spatial_navigation.h"
#include "third_party/blink/renderer/core/page/spatial_navigation_controller.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
#include "third_party/blink/renderer/core/scroll/scrollbar_theme.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
static bool IsFrameFocused(const Element& element) {
return element.GetDocument().GetFrame() && element.GetDocument()
.GetFrame()
->Selection()
.FrameIsFocusedAndActive();
}
static bool MatchesSpatialNavigationFocusPseudoClass(const Element& element) {
auto* option_element = DynamicTo<HTMLOptionElement>(element);
return option_element && option_element->SpatialNavigationFocused() &&
IsFrameFocused(element);
}
static bool MatchesHasDatalistPseudoClass(const Element& element) {
auto* html_input_element = DynamicTo<HTMLInputElement>(element);
return html_input_element && html_input_element->list();
}
static bool MatchesListBoxPseudoClass(const Element& element) {
auto* html_select_element = DynamicTo<HTMLSelectElement>(element);
return html_select_element && !html_select_element->UsesMenuList();
}
static bool MatchesMultiSelectFocusPseudoClass(const Element& element) {
auto* option_element = DynamicTo<HTMLOptionElement>(element);
return option_element && option_element->IsMultiSelectFocused() &&
IsFrameFocused(element);
}
static bool MatchesTagName(const Element& element,
const QualifiedName& tag_q_name) {
if (tag_q_name == AnyQName())
return true;
const AtomicString& local_name = tag_q_name.LocalName();
if (local_name != CSSSelector::UniversalSelectorAtom() &&
local_name != element.localName()) {
if (element.IsHTMLElement() || !IsA<HTMLDocument>(element.GetDocument()))
return false;
// Non-html elements in html documents are normalized to their camel-cased
// version during parsing if applicable. Yet, type selectors are lower-cased
// for selectors in html documents. Compare the upper case converted names
// instead to allow matching SVG elements like foreignObject.
if (element.TagQName().LocalNameUpper() != tag_q_name.LocalNameUpper())
return false;
}
const AtomicString& namespace_uri = tag_q_name.NamespaceURI();
return namespace_uri == g_star_atom ||
namespace_uri == element.namespaceURI();
}
static Element* ParentElement(
const SelectorChecker::SelectorCheckingContext& context) {
// - If context.scope is a shadow root, we should walk up to its shadow host.
// - If context.scope is some element in some shadow tree and querySelector
// initialized the context, e.g. shadowRoot.querySelector(':host *'),
// (a) context.element has the same treescope as context.scope, need to walk
// up to its shadow host.
// (b) Otherwise, should not walk up from a shadow root to a shadow host.
if (context.scope &&
(context.scope == context.element->ContainingShadowRoot() ||
context.scope->GetTreeScope() == context.element->GetTreeScope()))
return context.element->ParentOrShadowHostElement();
return context.element->parentElement();
}
// If context has scope, return slot that matches the scope, otherwise return
// the assigned slot for scope-less matching of ::slotted pseudo element.
static const HTMLSlotElement* FindSlotElementInScope(
const SelectorChecker::SelectorCheckingContext& context) {
if (!context.scope)
return context.element->AssignedSlot();
for (const HTMLSlotElement* slot = context.element->AssignedSlot(); slot;
slot = slot->AssignedSlot()) {
if (slot->GetTreeScope() == context.scope->GetTreeScope())
return slot;
}
return nullptr;
}
static inline bool NextSelectorExceedsScope(
const SelectorChecker::SelectorCheckingContext& context) {
if (context.scope && context.scope->IsInShadowTree())
return context.element == context.scope->OwnerShadowHost();
return false;
}
static bool ShouldMatchHoverOrActive(
const SelectorChecker::SelectorCheckingContext& context) {
// If we're in quirks mode, then :hover and :active should never match anchors
// with no href and *:hover and *:active should not match anything. This is
// specified in https://quirks.spec.whatwg.org/#the-:active-and-:hover-quirk
if (!context.element->GetDocument().InQuirksMode())
return true;
if (context.is_sub_selector)
return true;
if (context.element->IsLink())
return true;
const CSSSelector* selector = context.selector;
while (selector->Relation() == CSSSelector::kSubSelector &&
selector->TagHistory()) {
selector = selector->TagHistory();
if (selector->Match() != CSSSelector::kPseudoClass)
return true;
if (selector->GetPseudoType() != CSSSelector::kPseudoHover &&
selector->GetPseudoType() != CSSSelector::kPseudoActive)
return true;
}
return false;
}
static bool IsFirstChild(const Element& element) {
return !ElementTraversal::PreviousSibling(element);
}
static bool IsLastChild(const Element& element) {
return !ElementTraversal::NextSibling(element);
}
static bool IsFirstOfType(const Element& element, const QualifiedName& type) {
return !ElementTraversal::PreviousSibling(element, HasTagName(type));
}
static bool IsLastOfType(const Element& element, const QualifiedName& type) {
return !ElementTraversal::NextSibling(element, HasTagName(type));
}
bool SelectorChecker::Match(const SelectorCheckingContext& context,
MatchResult& result) const {
DCHECK(context.selector);
#if DCHECK_IS_ON()
DCHECK(!inside_match_) << "Do not re-enter Match: use MatchSelector instead";
base::AutoReset<bool> reset_inside_match(&inside_match_, true);
#endif // DCHECK_IS_ON()
if (UNLIKELY(context.vtt_originating_element)) {
// A kUAShadow combinator is required for VTT matching.
if (context.selector->IsLastInTagHistory())
return false;
}
if (MatchSelector(context, result) != kSelectorMatches)
return false;
if (RuntimeEnabledFeatures::CSSScopeEnabled() &&
!CheckInStyleScope(context, result)) {
return false;
}
return true;
}
// 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::MatchStatus SelectorChecker::MatchSelector(
const SelectorCheckingContext& context,
MatchResult& result) const {
MatchResult sub_result;
if (!CheckOne(context, sub_result))
return kSelectorFailsLocally;
if (sub_result.dynamic_pseudo != kPseudoIdNone) {
result.dynamic_pseudo = sub_result.dynamic_pseudo;
result.custom_highlight_name = std::move(sub_result.custom_highlight_name);
}
if (context.selector->IsLastInTagHistory())
return kSelectorMatches;
MatchStatus match;
if (context.selector->Relation() != CSSSelector::kSubSelector) {
if (NextSelectorExceedsScope(context))
return kSelectorFailsCompletely;
if (context.pseudo_id != kPseudoIdNone &&
context.pseudo_id != result.dynamic_pseudo)
return kSelectorFailsCompletely;
base::AutoReset<PseudoId> dynamic_pseudo_scope(&result.dynamic_pseudo,
kPseudoIdNone);
match = MatchForRelation(context, result);
} else {
match = MatchForSubSelector(context, result);
}
return match;
}
static inline SelectorChecker::SelectorCheckingContext
PrepareNextContextForRelation(
const SelectorChecker::SelectorCheckingContext& context) {
SelectorChecker::SelectorCheckingContext next_context(context);
DCHECK(context.selector->TagHistory());
next_context.selector = context.selector->TagHistory();
return next_context;
}
SelectorChecker::MatchStatus SelectorChecker::MatchForSubSelector(
const SelectorCheckingContext& context,
MatchResult& result) const {
SelectorCheckingContext next_context = PrepareNextContextForRelation(context);
PseudoId dynamic_pseudo = result.dynamic_pseudo;
next_context.has_scrollbar_pseudo =
dynamic_pseudo != kPseudoIdNone &&
(scrollbar_ || dynamic_pseudo == kPseudoIdScrollbarCorner ||
dynamic_pseudo == kPseudoIdResizer);
// Only match pseudo classes following scrollbar pseudo elements while
// actually computing style for scrollbar pseudo elements. This is to
// avoid incorrectly setting affected-by flags on actual elements for
// cases like: div::-webkit-scrollbar-thumb:hover { }
if (context.in_rightmost_compound && dynamic_pseudo != kPseudoIdNone &&
dynamic_pseudo != kPseudoIdSelection &&
!next_context.has_scrollbar_pseudo) {
return kSelectorFailsCompletely;
}
next_context.has_selection_pseudo = dynamic_pseudo == kPseudoIdSelection;
next_context.is_sub_selector = true;
return MatchSelector(next_context, result);
}
SelectorChecker::MatchStatus SelectorChecker::MatchForRelation(
const SelectorCheckingContext& context,
MatchResult& result) const {
SelectorCheckingContext next_context = PrepareNextContextForRelation(context);
CSSSelector::RelationType relation = context.selector->Relation();
// Disable :visited matching when we see the first link or try to match
// anything else than an ancestor.
if ((!context.is_sub_selector || context.in_nested_complex_selector) &&
(context.element->IsLink() || (relation != CSSSelector::kDescendant &&
relation != CSSSelector::kChild)))
next_context.is_inside_visited_link = false;
next_context.in_rightmost_compound = false;
next_context.is_sub_selector = false;
next_context.previous_element = context.element;
next_context.pseudo_id = kPseudoIdNone;
switch (relation) {
case CSSSelector::kRelativeDescendant:
DCHECK(result.has_argument_leftmost_compound_matches);
result.has_argument_leftmost_compound_matches->push_back(context.element);
[[fallthrough]];
case CSSSelector::kDescendant:
if (next_context.selector->GetPseudoType() == CSSSelector::kPseudoScope) {
if (next_context.selector->IsLastInTagHistory()) {
if (context.scope->IsDocumentFragment())
return kSelectorMatches;
}
}
for (next_context.element = ParentElement(next_context);
next_context.element;
next_context.element = ParentElement(next_context)) {
MatchStatus match = MatchSelector(next_context, result);
if (match == kSelectorMatches || match == kSelectorFailsCompletely)
return match;
if (NextSelectorExceedsScope(next_context))
return kSelectorFailsCompletely;
if (next_context.element->IsLink())
next_context.is_inside_visited_link = false;
}
return kSelectorFailsCompletely;
case CSSSelector::kRelativeChild:
DCHECK(result.has_argument_leftmost_compound_matches);
result.has_argument_leftmost_compound_matches->push_back(context.element);
[[fallthrough]];
case CSSSelector::kChild: {
next_context.element = ParentElement(next_context);
if (!next_context.element)
return kSelectorFailsCompletely;
return MatchSelector(next_context, result);
}
case CSSSelector::kRelativeDirectAdjacent:
DCHECK(result.has_argument_leftmost_compound_matches);
result.has_argument_leftmost_compound_matches->push_back(context.element);
[[fallthrough]];
case CSSSelector::kDirectAdjacent:
if (mode_ == kResolvingStyle) {
if (ContainerNode* parent =
context.element->ParentElementOrShadowRoot())
parent->SetChildrenAffectedByDirectAdjacentRules();
}
next_context.element =
ElementTraversal::PreviousSibling(*context.element);
if (!next_context.element)
return kSelectorFailsAllSiblings;
return MatchSelector(next_context, result);
case CSSSelector::kRelativeIndirectAdjacent:
DCHECK(result.has_argument_leftmost_compound_matches);
result.has_argument_leftmost_compound_matches->push_back(context.element);
[[fallthrough]];
case CSSSelector::kIndirectAdjacent:
if (mode_ == kResolvingStyle) {
if (ContainerNode* parent =
context.element->ParentElementOrShadowRoot())
parent->SetChildrenAffectedByIndirectAdjacentRules();
}
next_context.element =
ElementTraversal::PreviousSibling(*context.element);
for (; next_context.element;
next_context.element =
ElementTraversal::PreviousSibling(*next_context.element)) {
MatchStatus match = MatchSelector(next_context, result);
if (match == kSelectorMatches || match == kSelectorFailsAllSiblings ||
match == kSelectorFailsCompletely)
return match;
}
return kSelectorFailsAllSiblings;
case CSSSelector::kUAShadow: {
// If we're in the same tree-scope as the scoping element, then following
// a kUAShadow combinator would escape that and thus the scope.
if (context.scope && context.scope->OwnerShadowHost() &&
context.scope->OwnerShadowHost()->GetTreeScope() ==
context.element->GetTreeScope())
return kSelectorFailsCompletely;
Element* shadow_host = context.element->OwnerShadowHost();
if (!shadow_host)
return kSelectorFailsCompletely;
// Match against featureless-like Element described by spec:
// https://w3c.github.io/webvtt/#obtaining-css-boxes
if (context.vtt_originating_element)
shadow_host = context.vtt_originating_element;
next_context.element = shadow_host;
return MatchSelector(next_context, result);
}
case CSSSelector::kShadowSlot: {
if (ToHTMLSlotElementIfSupportsAssignmentOrNull(*context.element))
return kSelectorFailsCompletely;
const HTMLSlotElement* slot = FindSlotElementInScope(context);
if (!slot)
return kSelectorFailsCompletely;
next_context.element = const_cast<HTMLSlotElement*>(slot);
return MatchSelector(next_context, result);
}
case CSSSelector::kShadowPart:
// We ascend through ancestor shadow host elements until we reach the host
// in the TreeScope associated with the style rule. We then match against
// that host.
while (next_context.element) {
next_context.element = next_context.element->OwnerShadowHost();
if (!next_context.element)
return kSelectorFailsCompletely;
// Generally a ::part() rule needs to be in the host’s tree scope, but
// if (and only if) we are preceded by :host or :host(), then the rule
// could also be in the same scope as the subject.
TreeScope& host_tree_scope =
next_context.selector->IsHostPseudoClass()
? *context.scope->GetTreeScope().ParentTreeScope()
: context.scope->GetTreeScope();
if (next_context.element->GetTreeScope() == host_tree_scope)
return MatchSelector(next_context, result);
}
return kSelectorFailsCompletely;
case CSSSelector::kSubSelector:
break;
}
NOTREACHED();
return kSelectorFailsCompletely;
}
static bool AttributeValueMatches(const Attribute& attribute_item,
CSSSelector::MatchType match,
const AtomicString& selector_value,
TextCaseSensitivity case_sensitivity) {
// TODO(esprehn): How do we get here with a null value?
const AtomicString& value = attribute_item.Value();
if (value.IsNull())
return false;
switch (match) {
case CSSSelector::kAttributeExact:
if (case_sensitivity == kTextCaseSensitive)
return selector_value == value;
return EqualIgnoringASCIICase(selector_value, value);
case CSSSelector::kAttributeSet:
return true;
case CSSSelector::kAttributeList: {
// Ignore empty selectors or selectors containing HTML spaces
if (selector_value.IsEmpty() ||
selector_value.Find(&IsHTMLSpace<UChar>) != kNotFound)
return false;
unsigned start_search_at = 0;
while (true) {
wtf_size_t found_pos =
value.Find(selector_value, start_search_at, case_sensitivity);
if (found_pos == kNotFound)
return false;
if (!found_pos || IsHTMLSpace<UChar>(value[found_pos - 1])) {
unsigned end_str = found_pos + selector_value.length();
if (end_str == value.length() || IsHTMLSpace<UChar>(value[end_str]))
break; // We found a match.
}
// No match. Keep looking.
start_search_at = found_pos + 1;
}
return true;
}
case CSSSelector::kAttributeContain:
if (selector_value.IsEmpty())
return false;
return value.Contains(selector_value, case_sensitivity);
case CSSSelector::kAttributeBegin:
if (selector_value.IsEmpty())
return false;
return value.StartsWith(selector_value, case_sensitivity);
case CSSSelector::kAttributeEnd:
if (selector_value.IsEmpty())
return false;
return value.EndsWith(selector_value, case_sensitivity);
case CSSSelector::kAttributeHyphen:
if (value.length() < selector_value.length())
return false;
if (!value.StartsWith(selector_value, case_sensitivity))
return false;
// It they start the same, check for exact match or following '-':
if (value.length() != selector_value.length() &&
value[selector_value.length()] != '-')
return false;
return true;
default:
NOTREACHED();
return false;
}
}
static bool AnyAttributeMatches(Element& element,
CSSSelector::MatchType match,
const CSSSelector& selector) {
const QualifiedName& selector_attr = selector.Attribute();
// Should not be possible from the CSS grammar.
DCHECK_NE(selector_attr.LocalName(), CSSSelector::UniversalSelectorAtom());
// Synchronize the attribute in case it is lazy-computed.
// Currently all lazy properties have a null namespace, so only pass
// localName().
element.SynchronizeAttribute(selector_attr.LocalName());
const AtomicString& selector_value = selector.Value();
TextCaseSensitivity case_sensitivity =
(selector.AttributeMatch() ==
CSSSelector::AttributeMatchType::kCaseInsensitive)
? kTextCaseASCIIInsensitive
: kTextCaseSensitive;
AttributeCollection attributes = element.AttributesWithoutUpdate();
for (const auto& attribute_item : attributes) {
if (!attribute_item.Matches(selector_attr)) {
if (element.IsHTMLElement() || !IsA<HTMLDocument>(element.GetDocument()))
continue;
// Non-html attributes in html documents are normalized to their camel-
// cased version during parsing if applicable. Yet, attribute selectors
// are lower-cased for selectors in html documents. Compare the selector
// and the attribute local name insensitively to e.g. allow matching SVG
// attributes like viewBox.
//
// NOTE: If changing this behavior, be sure to also update the bucketing
// in ElementRuleCollector::CollectMatchingRules() accordingly.
if (!attribute_item.MatchesCaseInsensitive(selector_attr))
continue;
}
if (AttributeValueMatches(attribute_item, match, selector_value,
case_sensitivity))
return true;
if (case_sensitivity == kTextCaseASCIIInsensitive) {
if (selector_attr.NamespaceURI() != g_star_atom)
return false;
continue;
}
// Legacy dictates that values of some attributes should be compared in
// a case-insensitive manner regardless of whether the case insensitive
// flag is set or not.
bool legacy_case_insensitive = IsA<HTMLDocument>(element.GetDocument()) &&
!selector.IsCaseSensitiveAttribute();
// If case-insensitive, re-check, and count if result differs.
// See http://code.google.com/p/chromium/issues/detail?id=327060
if (legacy_case_insensitive &&
AttributeValueMatches(attribute_item, match, selector_value,
kTextCaseASCIIInsensitive)) {
// If the `s` modifier is in the attribute selector, return false
// despite of legacy_case_insensitive.
if (selector.AttributeMatch() ==
CSSSelector::AttributeMatchType::kCaseSensitiveAlways) {
DCHECK(RuntimeEnabledFeatures::CSSCaseSensitiveSelectorEnabled());
return false;
}
UseCounter::Count(element.GetDocument(),
WebFeature::kCaseInsensitiveAttrSelectorMatch);
return true;
}
if (selector_attr.NamespaceURI() != g_star_atom)
return false;
}
return false;
}
bool SelectorChecker::CheckOne(const SelectorCheckingContext& context,
MatchResult& result) const {
DCHECK(context.element);
Element& element = *context.element;
DCHECK(context.selector);
const CSSSelector& selector = *context.selector;
// Only :host and :host-context() should match the host:
// http://drafts.csswg.org/css-scoping/#host-element
if (context.scope && context.scope->OwnerShadowHost() == element &&
(!selector.IsHostPseudoClass() &&
selector.GetPseudoType() != CSSSelector::kPseudoScope &&
!context.treat_shadow_host_as_normal_scope &&
selector.Match() != CSSSelector::kPseudoElement))
return false;
switch (selector.Match()) {
case CSSSelector::kTag:
return MatchesTagName(element, selector.TagQName());
case CSSSelector::kClass:
return element.HasClass() &&
element.ClassNames().Contains(selector.Value());
case CSSSelector::kId:
return element.HasID() &&
element.IdForStyleResolution() == selector.Value();
// Attribute selectors
case CSSSelector::kAttributeExact:
case CSSSelector::kAttributeSet:
case CSSSelector::kAttributeHyphen:
case CSSSelector::kAttributeList:
case CSSSelector::kAttributeContain:
case CSSSelector::kAttributeBegin:
case CSSSelector::kAttributeEnd:
return AnyAttributeMatches(element, selector.Match(), selector);
case CSSSelector::kPseudoClass:
return CheckPseudoClass(context, result);
case CSSSelector::kPseudoElement:
return CheckPseudoElement(context, result);
default:
NOTREACHED();
return false;
}
}
bool SelectorChecker::CheckPseudoNot(const SelectorCheckingContext& context,
MatchResult& result) const {
const CSSSelector& selector = *context.selector;
DCHECK(selector.SelectorList());
SelectorCheckingContext sub_context(context);
sub_context.is_sub_selector = true;
sub_context.in_nested_complex_selector = true;
sub_context.pseudo_id = kPseudoIdNone;
for (sub_context.selector = selector.SelectorList()->First();
sub_context.selector;
sub_context.selector = CSSSelectorList::Next(*sub_context.selector)) {
MatchResult sub_result;
if (MatchSelector(sub_context, sub_result) == kSelectorMatches)
return false;
}
return true;
}
namespace {
Element* TraverseToParent(Element* element) {
return element->parentElement();
}
Element* TraverseToPreviousSibling(Element* element) {
return ElementTraversal::PreviousSibling(*element);
}
inline bool CacheMatchedElementsAndReturnMatchedResultForIndirectRelation(
Element* has_anchor_element,
HeapVector<Member<Element>>& has_argument_leftmost_compound_matches,
CheckPseudoHasCacheScope::Context& cache_scope_context,
Element* (*next)(Element*)) {
if (cache_scope_context.CacheAllowed()) {
bool selector_matched = false;
for (auto leftmost : has_argument_leftmost_compound_matches) {
for (Element* has_matched_element = next(leftmost); has_matched_element;
has_matched_element = next(has_matched_element)) {
if (has_matched_element == has_anchor_element)
selector_matched = true;
uint8_t old_result =
cache_scope_context.SetMatchedAndGetOldResult(has_matched_element);
if (old_result == kNotCached)
continue;
if (old_result & kMatched)
break;
}
}
return selector_matched;
}
for (auto leftmost : has_argument_leftmost_compound_matches) {
for (Element* has_matched_element = next(leftmost); has_matched_element;
has_matched_element = next(has_matched_element)) {
if (has_matched_element == has_anchor_element)
return true;
}
}
return false;
}
inline bool CacheMatchedElementsAndReturnMatchedResultForDirectRelation(
Element* has_anchor_element,
HeapVector<Member<Element>>& has_argument_leftmost_compound_matches,
CheckPseudoHasCacheScope::Context& cache_scope_context,
Element* (*next)(Element*)) {
if (cache_scope_context.CacheAllowed()) {
bool selector_matched = false;
for (auto leftmost : has_argument_leftmost_compound_matches) {
if (Element* has_matched_element = next(leftmost)) {
cache_scope_context.SetMatchedAndGetOldResult(has_matched_element);
if (has_matched_element == has_anchor_element)
selector_matched = true;
}
}
return selector_matched;
}
for (auto leftmost : has_argument_leftmost_compound_matches) {
if (Element* has_matched_element = next(leftmost)) {
if (has_matched_element == has_anchor_element)
return true;
}
}
return false;
}
inline bool CacheMatchedElementsAndReturnMatchedResult(
CSSSelector::RelationType leftmost_relation,
Element* has_anchor_element,
HeapVector<Member<Element>>& has_argument_leftmost_compound_matches,
CheckPseudoHasCacheScope::Context& cache_scope_context) {
switch (leftmost_relation) {
case CSSSelector::kRelativeDescendant:
return CacheMatchedElementsAndReturnMatchedResultForIndirectRelation(
has_anchor_element, has_argument_leftmost_compound_matches,
cache_scope_context, TraverseToParent);
case CSSSelector::kRelativeChild:
return CacheMatchedElementsAndReturnMatchedResultForDirectRelation(
has_anchor_element, has_argument_leftmost_compound_matches,
cache_scope_context, TraverseToParent);
case CSSSelector::kRelativeDirectAdjacent:
return CacheMatchedElementsAndReturnMatchedResultForDirectRelation(
has_anchor_element, has_argument_leftmost_compound_matches,
cache_scope_context, TraverseToPreviousSibling);
case CSSSelector::kRelativeIndirectAdjacent:
return CacheMatchedElementsAndReturnMatchedResultForIndirectRelation(
has_anchor_element, has_argument_leftmost_compound_matches,
cache_scope_context, TraverseToPreviousSibling);
default:
NOTREACHED();
return false;
}
}
inline bool ContextForSubjectHasInMatchesArgument(
const SelectorChecker::SelectorCheckingContext& has_checking_context) {
return has_checking_context.element == has_checking_context.scope &&
has_checking_context.in_rightmost_compound;
}
uint8_t SetHasAnchorElementAsCheckedAndGetOldResult(
const SelectorChecker::SelectorCheckingContext& has_checking_context,
CheckPseudoHasCacheScope::Context& cache_scope_context) {
DCHECK_EQ(has_checking_context.selector->GetPseudoType(),
CSSSelector::kPseudoHas);
Element* has_anchor_element = has_checking_context.element;
uint8_t previous_result = cache_scope_context.GetResult(has_anchor_element);
if (previous_result & kChecked)
return previous_result;
// If the selector checking context is for the subject :has() in the argument
// of the JavaScript API 'matches()', skip to check whether the :has() anchor
// element was already checked or not.
if (!ContextForSubjectHasInMatchesArgument(has_checking_context) &&
cache_scope_context.AlreadyChecked(has_anchor_element)) {
// If the element already have cache item, set the element as checked.
// Otherwise, skip to set to prevent increasing unnecessary cache item.
if (previous_result != kNotCached)
cache_scope_context.SetChecked(has_anchor_element);
// If the :has() anchor element was already checked previously, return the
// previous result with the kChecked flag set.
return previous_result | kChecked;
}
cache_scope_context.SetChecked(has_anchor_element);
return previous_result;
}
void SetAffectedByHasFlagsForElementAtDepth(
CheckPseudoHasArgumentContext& argument_context,
Element* element,
int depth) {
if (depth > 0) {
element->SetAncestorsOrAncestorSiblingsAffectedByHas();
} else {
element->SetSiblingsAffectedByHasFlags(
argument_context.GetSiblingsAffectedByHasFlags());
}
}
void SetAffectedByHasFlagsForHasAnchorElement(
CheckPseudoHasArgumentContext& argument_context,
Element* has_anchor_element) {
switch (argument_context.LeftmostRelation()) {
case CSSSelector::kRelativeChild:
case CSSSelector::kRelativeDescendant:
has_anchor_element->SetAncestorsOrAncestorSiblingsAffectedByHas();
break;
case CSSSelector::kRelativeDirectAdjacent:
case CSSSelector::kRelativeIndirectAdjacent:
has_anchor_element->SetSiblingsAffectedByHasFlags(
argument_context.GetSiblingsAffectedByHasFlags());
break;
default:
NOTREACHED();
break;
}
}
void SetAffectedByHasFlagsForHasAnchorSiblings(
CheckPseudoHasArgumentContext& argument_context,
Element* has_anchor_element) {
if (argument_context.AdjacentDistanceLimit() == 0)
return;
int distance = 1;
for (Element* sibling = ElementTraversal::NextSibling(*has_anchor_element);
sibling && distance <= argument_context.AdjacentDistanceLimit();
sibling = ElementTraversal::NextSibling(*sibling), distance++) {
sibling->SetSiblingsAffectedByHasFlags(
argument_context.GetSiblingsAffectedByHasFlags());
}
}
void SetAffectedByHasForArgumentMatchedElement(
CheckPseudoHasArgumentContext& argument_context,
Element* has_anchor_element,
Element* argument_matched_element,
int argument_matched_depth) {
// Iterator class to traverse siblings, ancestors and ancestor siblings of the
// CheckPseudoHasArgumentTraversalIterator's current element until reach to
// the :has() anchor element to set the SiblingsAffectedByHasFlags or
// AncestorsOrAncestorSiblingsAffectedByHas flag.
class AffectedByHasIterator {
STACK_ALLOCATED();
public:
AffectedByHasIterator(CheckPseudoHasArgumentContext& argument_context,
Element* has_anchor_element,
Element* argument_matched_element,
int argument_matched_depth)
: argument_context_(argument_context),
has_anchor_element_(has_anchor_element),
argument_matched_depth_(argument_matched_depth),
current_depth_(argument_matched_depth),
current_element_(argument_matched_element) {
DCHECK_GE(current_depth_, 0);
// affected-by flags of the matched element were already set.
// So, this iterator traverses from the next of the matched element.
++*this;
}
Element* CurrentElement() const { return current_element_; }
bool AtEnd() const {
DCHECK_GE(current_depth_, 0);
return current_element_ == has_anchor_element_;
}
int CurrentDepth() const { return current_depth_; }
void operator++() {
DCHECK(current_element_);
if (current_depth_ == 0) {
current_element_ = ElementTraversal::PreviousSibling(*current_element_);
DCHECK(current_element_);
return;
}
Element* previous = nullptr;
if (NeedsTraverseSiblings() &&
(previous = ElementTraversal::PreviousSibling(*current_element_))) {
current_element_ = previous;
DCHECK(current_element_);
return;
}
DCHECK_GT(current_depth_, 0);
current_depth_--;
current_element_ = current_element_->parentElement();
DCHECK(current_element_);
}
private:
inline bool NeedsTraverseSiblings() {
// When the current element is at the same depth of the argument selector
// matched element, we can determine whether the sibling traversal is
// needed or not by checking whether the rightmost combinator is an
// adjacent combinator. When the current element is not at the same depth
// of the argument selector matched element, we can determine whether the
// sibling traversal is needed or not by checking whether an adjacent
// combinator is between child or descendant combinator.
DCHECK_LE(current_depth_, argument_matched_depth_);
return argument_matched_depth_ == current_depth_
? argument_context_.SiblingCombinatorAtRightmost()
: argument_context_
.SiblingCombinatorBetweenChildOrDescendantCombinator();
}
const CheckPseudoHasArgumentContext& argument_context_;
Element* has_anchor_element_;
const int argument_matched_depth_;
int current_depth_;
Element* current_element_;
} affected_by_has_iterator(argument_context, has_anchor_element,
argument_matched_element, argument_matched_depth);
// Set AncestorsOrAncestorSiblingsAffectedByHas flag on the elements at
// upward (previous siblings, ancestors, ancestors' previous siblings) of the
// argument matched element.
for (; !affected_by_has_iterator.AtEnd(); ++affected_by_has_iterator) {
SetAffectedByHasFlagsForElementAtDepth(
argument_context, affected_by_has_iterator.CurrentElement(),
affected_by_has_iterator.CurrentDepth());
}
}
bool SkipCheckingHasArgument(
CheckPseudoHasArgumentContext& context,
CheckPseudoHasArgumentTraversalIterator& iterator) {
// Siblings of the :has() anchor element cannot be a subject of :has()
// argument if the argument selector has child or descendant combinator.
if (context.DepthLimit() > 0 && iterator.CurrentDepth() == 0)
return true;
// The current element of the iterator cannot be a subject of :has() argument
// if the :has() argument selector only matches on the elements at a fixed
// depth and the current element of the iterator is not at the certain depth.
// (e.g. For the style rule '.a:has(> .b > .c) {}', a child of '.a' or a great
// grand child of '.a' cannot be a subject of the argument '> .b > .c'. Only
// the grand child of '.a' can be a subject of the argument)
if (context.DepthFixed() && (iterator.CurrentDepth() != context.DepthLimit()))
return true;
return false;
}
enum EarlyBreakOnHasArgumentChecking {
kBreakEarlyAndReturnAsMatched,
kBreakEarlyAndMoveToNextArgument,
kNoEarlyBreak,
};
EarlyBreakOnHasArgumentChecking CheckEarlyBreakForHasArgument(
const SelectorChecker::SelectorCheckingContext& context,
Element* has_anchor_element,
CheckPseudoHasArgumentContext& argument_context,
CheckPseudoHasCacheScope::Context& cache_scope_context,
bool update_affected_by_has_flags) {
if (!cache_scope_context.CacheAllowed())
return kNoEarlyBreak;
// Get the cached :has() checking result of the element to skip :has()
// argument checking.
// - If the element was already marked as matched, break :has() argument
// checking early and return as matched.
// - If the element was already checked but not matched, break :has()
// argument checking early and move to the next argument selector.
// - Otherwise, check :has() argument.
uint8_t previous_result =
SetHasAnchorElementAsCheckedAndGetOldResult(context, cache_scope_context);
if (previous_result & kChecked) {
if (update_affected_by_has_flags) {
SetAffectedByHasFlagsForHasAnchorSiblings(argument_context,
has_anchor_element);
}
return previous_result & kMatched ? kBreakEarlyAndReturnAsMatched
: kBreakEarlyAndMoveToNextArgument;
}
return kNoEarlyBreak;
}
} // namespace
bool SelectorChecker::CheckPseudoHas(const SelectorCheckingContext& context,
MatchResult& result) const {
CheckPseudoHasCacheScope check_pseudo_has_cache_scope(
&context.element->GetDocument());
Element* has_anchor_element = context.element;
Document& document = has_anchor_element->GetDocument();
DCHECK(document.GetCheckPseudoHasCacheScope());
SelectorCheckingContext sub_context(has_anchor_element);
sub_context.scope = context.scope;
// sub_context.is_inside_visited_link is false (by default) to disable
// :visited matching when it is in the :has argument
sub_context.is_inside_has_pseudo_class = true;