Unreviewed, rolling out r243037.
[WebKit-https.git] / Source / WebCore / dom / Node.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2001 Dirk Mueller (mueller@kde.org)
5  * Copyright (C) 2004-2017 Apple Inc. All rights reserved.
6  * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
7  * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public License
20  * along with this library; see the file COPYING.LIB.  If not, write to
21  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 #include "config.h"
26 #include "Node.h"
27
28 #include "AXObjectCache.h"
29 #include "Attr.h"
30 #include "BeforeLoadEvent.h"
31 #include "ChildListMutationScope.h"
32 #include "CommonVM.h"
33 #include "ComposedTreeAncestorIterator.h"
34 #include "ContainerNodeAlgorithms.h"
35 #include "ContextMenuController.h"
36 #include "DOMWindow.h"
37 #include "DataTransfer.h"
38 #include "DocumentType.h"
39 #include "ElementIterator.h"
40 #include "ElementRareData.h"
41 #include "ElementTraversal.h"
42 #include "EventDispatcher.h"
43 #include "EventHandler.h"
44 #include "FrameView.h"
45 #include "HTMLBodyElement.h"
46 #include "HTMLCollection.h"
47 #include "HTMLElement.h"
48 #include "HTMLImageElement.h"
49 #include "HTMLSlotElement.h"
50 #include "HTMLStyleElement.h"
51 #include "InputEvent.h"
52 #include "InspectorController.h"
53 #include "KeyboardEvent.h"
54 #include "Logging.h"
55 #include "MutationEvent.h"
56 #include "NodeRenderStyle.h"
57 #include "ProcessingInstruction.h"
58 #include "ProgressEvent.h"
59 #include "Range.h"
60 #include "RenderBlock.h"
61 #include "RenderBox.h"
62 #include "RenderTextControl.h"
63 #include "RenderView.h"
64 #include "ScopedEventQueue.h"
65 #include "ScriptDisallowedScope.h"
66 #include "StorageEvent.h"
67 #include "StyleResolver.h"
68 #include "StyleSheetContents.h"
69 #include "TemplateContentDocumentFragment.h"
70 #include "TextEvent.h"
71 #include "TouchEvent.h"
72 #include "WheelEvent.h"
73 #include "XMLNSNames.h"
74 #include "XMLNames.h"
75 #include <wtf/IsoMallocInlines.h>
76 #include <wtf/RefCountedLeakCounter.h>
77 #include <wtf/SHA1.h>
78 #include <wtf/Variant.h>
79 #include <wtf/text/CString.h>
80 #include <wtf/text/StringBuilder.h>
81
82 namespace WebCore {
83
84 WTF_MAKE_ISO_ALLOCATED_IMPL(Node);
85
86 using namespace HTMLNames;
87
88 #if DUMP_NODE_STATISTICS
89 static HashSet<Node*>& liveNodeSet()
90 {
91     static NeverDestroyed<HashSet<Node*>> liveNodes;
92     return liveNodes;
93 }
94
95 static const char* stringForRareDataUseType(NodeRareData::UseType useType)
96 {
97     switch (useType) {
98     case NodeRareData::UseType::ConnectedFrameCount:
99         return "ConnectedFrameCount";
100     case NodeRareData::UseType::NodeList:
101         return "NodeList";
102     case NodeRareData::UseType::MutationObserver:
103         return "MutationObserver";
104     case NodeRareData::UseType::TabIndex:
105         return "TabIndex";
106     case NodeRareData::UseType::StyleFlags:
107         return "StyleFlags";
108     case NodeRareData::UseType::MinimumSize:
109         return "MinimumSize";
110     case NodeRareData::UseType::ScrollingPosition:
111         return "ScrollingPosition";
112     case NodeRareData::UseType::ComputedStyle:
113         return "ComputedStyle";
114     case NodeRareData::UseType::Dataset:
115         return "Dataset";
116     case NodeRareData::UseType::ClassList:
117         return "ClassList";
118     case NodeRareData::UseType::ShadowRoot:
119         return "ShadowRoot";
120     case NodeRareData::UseType::CustomElementQueue:
121         return "CustomElementQueue";
122     case NodeRareData::UseType::AttributeMap:
123         return "AttributeMap";
124     case NodeRareData::UseType::InteractionObserver:
125         return "InteractionObserver";
126     case NodeRareData::UseType::PseudoElements:
127         return "PseudoElements";
128     }
129     return nullptr;
130 }
131
132 #endif
133
134 void Node::dumpStatistics()
135 {
136 #if DUMP_NODE_STATISTICS
137     size_t nodesWithRareData = 0;
138
139     size_t elementNodes = 0;
140     size_t attrNodes = 0;
141     size_t textNodes = 0;
142     size_t cdataNodes = 0;
143     size_t commentNodes = 0;
144     size_t piNodes = 0;
145     size_t documentNodes = 0;
146     size_t docTypeNodes = 0;
147     size_t fragmentNodes = 0;
148     size_t shadowRootNodes = 0;
149
150     HashMap<String, size_t> perTagCount;
151
152     size_t attributes = 0;
153     size_t attributesWithAttr = 0;
154     size_t elementsWithAttributeStorage = 0;
155     size_t elementsWithRareData = 0;
156     size_t elementsWithNamedNodeMap = 0;
157
158     HashMap<uint16_t, size_t> rareDataSingleUseTypeCounts;
159     size_t mixedRareDataUseCount = 0;
160
161     for (auto* node : liveNodeSet()) {
162         if (node->hasRareData()) {
163             ++nodesWithRareData;
164             if (is<Element>(*node)) {
165                 ++elementsWithRareData;
166                 if (downcast<Element>(*node).hasNamedNodeMap())
167                     ++elementsWithNamedNodeMap;
168             }
169             auto* rareData = node->rareData();
170             auto useTypes = is<Element>(node) ? static_cast<ElementRareData*>(rareData)->useTypes() : rareData->useTypes();
171             unsigned useTypeCount = 0;
172             for (auto type : useTypes) {
173                 UNUSED_PARAM(type);
174                 useTypeCount++;
175             }
176             if (useTypeCount == 1) {
177                 auto result = rareDataSingleUseTypeCounts.add(static_cast<uint16_t>(*useTypes.begin()), 0);
178                 result.iterator->value++;
179             } else
180                 mixedRareDataUseCount++;
181         }
182
183         switch (node->nodeType()) {
184             case ELEMENT_NODE: {
185                 ++elementNodes;
186
187                 // Tag stats
188                 Element& element = downcast<Element>(*node);
189                 HashMap<String, size_t>::AddResult result = perTagCount.add(element.tagName(), 1);
190                 if (!result.isNewEntry)
191                     result.iterator->value++;
192
193                 if (const ElementData* elementData = element.elementData()) {
194                     unsigned length = elementData->length();
195                     attributes += length;
196                     ++elementsWithAttributeStorage;
197                     for (unsigned i = 0; i < length; ++i) {
198                         const Attribute& attr = elementData->attributeAt(i);
199                         if (element.attrIfExists(attr.name()))
200                             ++attributesWithAttr;
201                     }
202                 }
203                 break;
204             }
205             case ATTRIBUTE_NODE: {
206                 ++attrNodes;
207                 break;
208             }
209             case TEXT_NODE: {
210                 ++textNodes;
211                 break;
212             }
213             case CDATA_SECTION_NODE: {
214                 ++cdataNodes;
215                 break;
216             }
217             case PROCESSING_INSTRUCTION_NODE: {
218                 ++piNodes;
219                 break;
220             }
221             case COMMENT_NODE: {
222                 ++commentNodes;
223                 break;
224             }
225             case DOCUMENT_NODE: {
226                 ++documentNodes;
227                 break;
228             }
229             case DOCUMENT_TYPE_NODE: {
230                 ++docTypeNodes;
231                 break;
232             }
233             case DOCUMENT_FRAGMENT_NODE: {
234                 if (node->isShadowRoot())
235                     ++shadowRootNodes;
236                 else
237                     ++fragmentNodes;
238                 break;
239             }
240         }
241     }
242
243     printf("Number of Nodes: %d\n\n", liveNodeSet().size());
244     printf("Number of Nodes with RareData: %zu\n", nodesWithRareData);
245     printf("  Mixed use: %zu\n", mixedRareDataUseCount);
246     for (auto it : rareDataSingleUseTypeCounts)
247         printf("  %s: %zu\n", stringForRareDataUseType(static_cast<NodeRareData::UseType>(it.key)), it.value);
248     printf("\n");
249
250
251     printf("NodeType distribution:\n");
252     printf("  Number of Element nodes: %zu\n", elementNodes);
253     printf("  Number of Attribute nodes: %zu\n", attrNodes);
254     printf("  Number of Text nodes: %zu\n", textNodes);
255     printf("  Number of CDATASection nodes: %zu\n", cdataNodes);
256     printf("  Number of Comment nodes: %zu\n", commentNodes);
257     printf("  Number of ProcessingInstruction nodes: %zu\n", piNodes);
258     printf("  Number of Document nodes: %zu\n", documentNodes);
259     printf("  Number of DocumentType nodes: %zu\n", docTypeNodes);
260     printf("  Number of DocumentFragment nodes: %zu\n", fragmentNodes);
261     printf("  Number of ShadowRoot nodes: %zu\n", shadowRootNodes);
262
263     printf("Element tag name distibution:\n");
264     for (auto& stringSizePair : perTagCount)
265         printf("  Number of <%s> tags: %zu\n", stringSizePair.key.utf8().data(), stringSizePair.value);
266
267     printf("Attributes:\n");
268     printf("  Number of Attributes (non-Node and Node): %zu [%zu]\n", attributes, sizeof(Attribute));
269     printf("  Number of Attributes with an Attr: %zu\n", attributesWithAttr);
270     printf("  Number of Elements with attribute storage: %zu [%zu]\n", elementsWithAttributeStorage, sizeof(ElementData));
271     printf("  Number of Elements with RareData: %zu\n", elementsWithRareData);
272     printf("  Number of Elements with NamedNodeMap: %zu [%zu]\n", elementsWithNamedNodeMap, sizeof(NamedNodeMap));
273 #endif
274 }
275
276 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, nodeCounter, ("WebCoreNode"));
277
278 #ifndef NDEBUG
279 static bool shouldIgnoreLeaks = false;
280
281 static HashSet<Node*>& ignoreSet()
282 {
283     static NeverDestroyed<HashSet<Node*>> ignore;
284
285     return ignore;
286 }
287
288 #endif
289
290 void Node::startIgnoringLeaks()
291 {
292 #ifndef NDEBUG
293     shouldIgnoreLeaks = true;
294 #endif
295 }
296
297 void Node::stopIgnoringLeaks()
298 {
299 #ifndef NDEBUG
300     shouldIgnoreLeaks = false;
301 #endif
302 }
303
304 void Node::trackForDebugging()
305 {
306 #ifndef NDEBUG
307     if (shouldIgnoreLeaks)
308         ignoreSet().add(this);
309     else
310         nodeCounter.increment();
311 #endif
312
313 #if DUMP_NODE_STATISTICS
314     liveNodeSet().add(this);
315 #endif
316 }
317
318 Node::Node(Document& document, ConstructionType type)
319     : m_refCount(1)
320     , m_nodeFlags(type)
321     , m_treeScope(&document)
322 {
323     ASSERT(isMainThread());
324
325     document.incrementReferencingNodeCount();
326
327 #if !defined(NDEBUG) || (defined(DUMP_NODE_STATISTICS) && DUMP_NODE_STATISTICS)
328     trackForDebugging();
329 #endif
330 }
331
332 Node::~Node()
333 {
334     ASSERT(isMainThread());
335     // We set m_refCount to 1 before calling delete to avoid double destruction through use of Ref<T>/RefPtr<T>.
336     // This is a security mitigation in case of programmer errorm (caught by a debug assertion).
337     ASSERT(m_refCount == 1);
338     ASSERT(m_deletionHasBegun);
339     ASSERT(!m_adoptionIsRequired);
340
341 #ifndef NDEBUG
342     if (!ignoreSet().remove(this))
343         nodeCounter.decrement();
344 #endif
345
346 #if DUMP_NODE_STATISTICS
347     liveNodeSet().remove(this);
348 #endif
349
350     RELEASE_ASSERT(!renderer());
351     ASSERT(!parentNode());
352     ASSERT(!m_previous);
353     ASSERT(!m_next);
354
355     if (hasRareData())
356         clearRareData();
357
358     if (!isContainerNode())
359         willBeDeletedFrom(document());
360
361     if (hasEventTargetData())
362         clearEventTargetData();
363
364     document().decrementReferencingNodeCount();
365
366 #if ENABLE(TOUCH_EVENTS) && PLATFORM(IOS_FAMILY) && (!ASSERT_DISABLED || ENABLE(SECURITY_ASSERTIONS))
367     for (auto* document : Document::allDocuments()) {
368         ASSERT_WITH_SECURITY_IMPLICATION(!document->touchEventListenersContain(*this));
369         ASSERT_WITH_SECURITY_IMPLICATION(!document->touchEventHandlersContain(*this));
370         ASSERT_WITH_SECURITY_IMPLICATION(!document->touchEventTargetsContain(*this));
371     }
372 #endif
373 }
374
375 void Node::willBeDeletedFrom(Document& document)
376 {
377     if (hasEventTargetData()) {
378         document.didRemoveWheelEventHandler(*this, EventHandlerRemoval::All);
379 #if ENABLE(TOUCH_EVENTS)
380 #if PLATFORM(IOS_FAMILY)
381         document.removeTouchEventListener(*this, EventHandlerRemoval::All);
382 #endif
383         document.didRemoveTouchEventHandler(*this, EventHandlerRemoval::All);
384 #endif
385     }
386
387 #if ENABLE(TOUCH_EVENTS) && PLATFORM(IOS_FAMILY)
388     document.removeTouchEventHandler(*this, EventHandlerRemoval::All);
389 #endif
390
391     if (auto* cache = document.existingAXObjectCache())
392         cache->remove(*this);
393 }
394
395 void Node::materializeRareData()
396 {
397     NodeRareData* data;
398     if (is<Element>(*this))
399         data = std::make_unique<ElementRareData>(downcast<RenderElement>(m_data.m_renderer)).release();
400     else
401         data = std::make_unique<NodeRareData>(m_data.m_renderer).release();
402     ASSERT(data);
403
404     m_data.m_rareData = data;
405     setFlag(HasRareDataFlag);
406 }
407
408 void Node::clearRareData()
409 {
410     ASSERT(hasRareData());
411     ASSERT(!transientMutationObserverRegistry() || transientMutationObserverRegistry()->isEmpty());
412
413     RenderObject* renderer = m_data.m_rareData->renderer();
414     if (isElementNode())
415         delete static_cast<ElementRareData*>(m_data.m_rareData);
416     else
417         delete static_cast<NodeRareData*>(m_data.m_rareData);
418     m_data.m_renderer = renderer;
419     clearFlag(HasRareDataFlag);
420 }
421
422 bool Node::isNode() const
423 {
424     return true;
425 }
426
427 String Node::nodeValue() const
428 {
429     return String();
430 }
431
432 ExceptionOr<void> Node::setNodeValue(const String&)
433 {
434     // By default, setting nodeValue has no effect.
435     return { };
436 }
437
438 RefPtr<NodeList> Node::childNodes()
439 {
440     if (is<ContainerNode>(*this))
441         return ensureRareData().ensureNodeLists().ensureChildNodeList(downcast<ContainerNode>(*this));
442     return ensureRareData().ensureNodeLists().ensureEmptyChildNodeList(*this);
443 }
444
445 Node *Node::lastDescendant() const
446 {
447     Node *n = const_cast<Node *>(this);
448     while (n && n->lastChild())
449         n = n->lastChild();
450     return n;
451 }
452
453 Node* Node::firstDescendant() const
454 {
455     Node *n = const_cast<Node *>(this);
456     while (n && n->firstChild())
457         n = n->firstChild();
458     return n;
459 }
460
461 Element* Node::previousElementSibling() const
462 {
463     return ElementTraversal::previousSibling(*this);
464 }
465
466 Element* Node::nextElementSibling() const
467 {
468     return ElementTraversal::nextSibling(*this);
469 }
470
471 ExceptionOr<void> Node::insertBefore(Node& newChild, Node* refChild)
472 {
473     if (!is<ContainerNode>(*this))
474         return Exception { HierarchyRequestError };
475     return downcast<ContainerNode>(*this).insertBefore(newChild, refChild);
476 }
477
478 ExceptionOr<void> Node::replaceChild(Node& newChild, Node& oldChild)
479 {
480     if (!is<ContainerNode>(*this))
481         return Exception { HierarchyRequestError };
482     return downcast<ContainerNode>(*this).replaceChild(newChild, oldChild);
483 }
484
485 ExceptionOr<void> Node::removeChild(Node& oldChild)
486 {
487     if (!is<ContainerNode>(*this))
488         return Exception { NotFoundError };
489     return downcast<ContainerNode>(*this).removeChild(oldChild);
490 }
491
492 ExceptionOr<void> Node::appendChild(Node& newChild)
493 {
494     if (!is<ContainerNode>(*this))
495         return Exception { HierarchyRequestError };
496     return downcast<ContainerNode>(*this).appendChild(newChild);
497 }
498
499 static HashSet<RefPtr<Node>> nodeSetPreTransformedFromNodeOrStringVector(const Vector<NodeOrString>& vector)
500 {
501     HashSet<RefPtr<Node>> nodeSet;
502     for (const auto& variant : vector) {
503         WTF::switchOn(variant,
504             [&] (const RefPtr<Node>& node) { nodeSet.add(const_cast<Node*>(node.get())); },
505             [] (const String&) { }
506         );
507     }
508     return nodeSet;
509 }
510
511 static RefPtr<Node> firstPrecedingSiblingNotInNodeSet(Node& context, const HashSet<RefPtr<Node>>& nodeSet)
512 {
513     for (auto* sibling = context.previousSibling(); sibling; sibling = sibling->previousSibling()) {
514         if (!nodeSet.contains(sibling))
515             return sibling;
516     }
517     return nullptr;
518 }
519
520 static RefPtr<Node> firstFollowingSiblingNotInNodeSet(Node& context, const HashSet<RefPtr<Node>>& nodeSet)
521 {
522     for (auto* sibling = context.nextSibling(); sibling; sibling = sibling->nextSibling()) {
523         if (!nodeSet.contains(sibling))
524             return sibling;
525     }
526     return nullptr;
527 }
528
529 ExceptionOr<RefPtr<Node>> Node::convertNodesOrStringsIntoNode(Vector<NodeOrString>&& nodeOrStringVector)
530 {
531     if (nodeOrStringVector.isEmpty())
532         return nullptr;
533
534     Vector<Ref<Node>> nodes;
535     nodes.reserveInitialCapacity(nodeOrStringVector.size());
536     for (auto& variant : nodeOrStringVector) {
537         WTF::switchOn(variant,
538             [&](RefPtr<Node>& node) { nodes.uncheckedAppend(*node.get()); },
539             [&](String& string) { nodes.uncheckedAppend(Text::create(document(), string)); }
540         );
541     }
542
543     if (nodes.size() == 1)
544         return RefPtr<Node> { WTFMove(nodes.first()) };
545
546     auto nodeToReturn = DocumentFragment::create(document());
547     for (auto& node : nodes) {
548         auto appendResult = nodeToReturn->appendChild(node);
549         if (appendResult.hasException())
550             return appendResult.releaseException();
551     }
552     return RefPtr<Node> { WTFMove(nodeToReturn) };
553 }
554
555 ExceptionOr<void> Node::before(Vector<NodeOrString>&& nodeOrStringVector)
556 {
557     RefPtr<ContainerNode> parent = parentNode();
558     if (!parent)
559         return { };
560
561     auto nodeSet = nodeSetPreTransformedFromNodeOrStringVector(nodeOrStringVector);
562     auto viablePreviousSibling = firstPrecedingSiblingNotInNodeSet(*this, nodeSet);
563
564     auto result = convertNodesOrStringsIntoNode(WTFMove(nodeOrStringVector));
565     if (result.hasException())
566         return result.releaseException();
567     auto node = result.releaseReturnValue();
568     if (!node)
569         return { };
570
571     if (viablePreviousSibling)
572         viablePreviousSibling = viablePreviousSibling->nextSibling();
573     else
574         viablePreviousSibling = parent->firstChild();
575
576     return parent->insertBefore(*node, viablePreviousSibling.get());
577 }
578
579 ExceptionOr<void> Node::after(Vector<NodeOrString>&& nodeOrStringVector)
580 {
581     RefPtr<ContainerNode> parent = parentNode();
582     if (!parent)
583         return { };
584
585     auto nodeSet = nodeSetPreTransformedFromNodeOrStringVector(nodeOrStringVector);
586     auto viableNextSibling = firstFollowingSiblingNotInNodeSet(*this, nodeSet);
587
588     auto result = convertNodesOrStringsIntoNode(WTFMove(nodeOrStringVector));
589     if (result.hasException())
590         return result.releaseException();
591     auto node = result.releaseReturnValue();
592     if (!node)
593         return { };
594
595     return parent->insertBefore(*node, viableNextSibling.get());
596 }
597
598 ExceptionOr<void> Node::replaceWith(Vector<NodeOrString>&& nodeOrStringVector)
599 {
600     RefPtr<ContainerNode> parent = parentNode();
601     if (!parent)
602         return { };
603
604     auto nodeSet = nodeSetPreTransformedFromNodeOrStringVector(nodeOrStringVector);
605     auto viableNextSibling = firstFollowingSiblingNotInNodeSet(*this, nodeSet);
606
607     auto result = convertNodesOrStringsIntoNode(WTFMove(nodeOrStringVector));
608     if (result.hasException())
609         return result.releaseException();
610
611     if (parentNode() == parent) {
612         if (auto node = result.releaseReturnValue())
613             return parent->replaceChild(*node, *this);
614         return parent->removeChild(*this);
615     }
616
617     if (auto node = result.releaseReturnValue())
618         return parent->insertBefore(*node, viableNextSibling.get());
619     return { };
620 }
621
622 ExceptionOr<void> Node::remove()
623 {
624     auto* parent = parentNode();
625     if (!parent)
626         return { };
627     return parent->removeChild(*this);
628 }
629
630 void Node::normalize()
631 {
632     // Go through the subtree beneath us, normalizing all nodes. This means that
633     // any two adjacent text nodes are merged and any empty text nodes are removed.
634
635     RefPtr<Node> node = this;
636     while (Node* firstChild = node->firstChild())
637         node = firstChild;
638     while (node) {
639         NodeType type = node->nodeType();
640         if (type == ELEMENT_NODE)
641             downcast<Element>(*node).normalizeAttributes();
642
643         if (node == this)
644             break;
645
646         if (type != TEXT_NODE) {
647             node = NodeTraversal::nextPostOrder(*node);
648             continue;
649         }
650
651         RefPtr<Text> text = downcast<Text>(node.get());
652
653         // Remove empty text nodes.
654         if (!text->length()) {
655             // Care must be taken to get the next node before removing the current node.
656             node = NodeTraversal::nextPostOrder(*node);
657             text->remove();
658             continue;
659         }
660
661         // Merge text nodes.
662         while (Node* nextSibling = node->nextSibling()) {
663             if (nextSibling->nodeType() != TEXT_NODE)
664                 break;
665             Ref<Text> nextText = downcast<Text>(*nextSibling);
666
667             // Remove empty text nodes.
668             if (!nextText->length()) {
669                 nextText->remove();
670                 continue;
671             }
672
673             // Both non-empty text nodes. Merge them.
674             unsigned offset = text->length();
675             text->appendData(nextText->data());
676             document().textNodesMerged(nextText, offset);
677             nextText->remove();
678         }
679
680         node = NodeTraversal::nextPostOrder(*node);
681     }
682 }
683
684 ExceptionOr<Ref<Node>> Node::cloneNodeForBindings(bool deep)
685 {
686     if (UNLIKELY(isShadowRoot()))
687         return Exception { NotSupportedError };
688     return cloneNode(deep);
689 }
690
691 const AtomicString& Node::prefix() const
692 {
693     // For nodes other than elements and attributes, the prefix is always null
694     return nullAtom();
695 }
696
697 ExceptionOr<void> Node::setPrefix(const AtomicString&)
698 {
699     // The spec says that for nodes other than elements and attributes, prefix is always null.
700     // It does not say what to do when the user tries to set the prefix on another type of
701     // node, however Mozilla throws a NamespaceError exception.
702     return Exception { NamespaceError };
703 }
704
705 const AtomicString& Node::localName() const
706 {
707     return nullAtom();
708 }
709
710 const AtomicString& Node::namespaceURI() const
711 {
712     return nullAtom();
713 }
714
715 bool Node::isContentEditable()
716 {
717     return computeEditability(UserSelectAllDoesNotAffectEditability, ShouldUpdateStyle::Update) != Editability::ReadOnly;
718 }
719
720 bool Node::isContentRichlyEditable()
721 {
722     return computeEditability(UserSelectAllIsAlwaysNonEditable, ShouldUpdateStyle::Update) == Editability::CanEditRichly;
723 }
724
725 void Node::inspect()
726 {
727     if (document().page())
728         document().page()->inspectorController().inspect(this);
729 }
730
731 static Node::Editability computeEditabilityFromComputedStyle(const Node& startNode, Node::UserSelectAllTreatment treatment)
732 {
733     // Ideally we'd call ASSERT(!needsStyleRecalc()) here, but
734     // ContainerNode::setFocus() calls invalidateStyleForSubtree(), so the assertion
735     // would fire in the middle of Document::setFocusedElement().
736
737     for (const Node* node = &startNode; node; node = node->parentNode()) {
738         auto* style = node->isDocumentNode() ? node->renderStyle() : const_cast<Node*>(node)->computedStyle();
739         if (!style)
740             continue;
741         if (style->display() == DisplayType::None)
742             continue;
743 #if ENABLE(USERSELECT_ALL)
744         // Elements with user-select: all style are considered atomic
745         // therefore non editable.
746         if (treatment == Node::UserSelectAllIsAlwaysNonEditable && style->userSelect() == UserSelect::All)
747             return Node::Editability::ReadOnly;
748 #else
749         UNUSED_PARAM(treatment);
750 #endif
751         switch (style->userModify()) {
752         case UserModify::ReadOnly:
753             return Node::Editability::ReadOnly;
754         case UserModify::ReadWrite:
755             return Node::Editability::CanEditRichly;
756         case UserModify::ReadWritePlaintextOnly:
757             return Node::Editability::CanEditPlainText;
758         }
759         ASSERT_NOT_REACHED();
760         return Node::Editability::ReadOnly;
761     }
762     return Node::Editability::ReadOnly;
763 }
764
765 Node::Editability Node::computeEditability(UserSelectAllTreatment treatment, ShouldUpdateStyle shouldUpdateStyle) const
766 {
767     if (!document().hasLivingRenderTree() || isPseudoElement())
768         return Editability::ReadOnly;
769
770     if (isInShadowTree())
771         return HTMLElement::editabilityFromContentEditableAttr(*this);
772
773     if (document().frame() && document().frame()->page() && document().frame()->page()->isEditable())
774         return Editability::CanEditRichly;
775
776     if (shouldUpdateStyle == ShouldUpdateStyle::Update && document().needsStyleRecalc()) {
777         if (!document().usesStyleBasedEditability())
778             return HTMLElement::editabilityFromContentEditableAttr(*this);
779         document().updateStyleIfNeeded();
780     }
781     return computeEditabilityFromComputedStyle(*this, treatment);
782 }
783
784 RenderBox* Node::renderBox() const
785 {
786     RenderObject* renderer = this->renderer();
787     return is<RenderBox>(renderer) ? downcast<RenderBox>(renderer) : nullptr;
788 }
789
790 RenderBoxModelObject* Node::renderBoxModelObject() const
791 {
792     RenderObject* renderer = this->renderer();
793     return is<RenderBoxModelObject>(renderer) ? downcast<RenderBoxModelObject>(renderer) : nullptr;
794 }
795     
796 LayoutRect Node::renderRect(bool* isReplaced)
797 {    
798     RenderObject* hitRenderer = this->renderer();
799     ASSERT(hitRenderer);
800     RenderObject* renderer = hitRenderer;
801     while (renderer && !renderer->isBody() && !renderer->isDocumentElementRenderer()) {
802         if (renderer->isRenderBlock() || renderer->isInlineBlockOrInlineTable() || renderer->isReplaced()) {
803             *isReplaced = renderer->isReplaced();
804             return renderer->absoluteBoundingBoxRect();
805         }
806         renderer = renderer->parent();
807     }
808     return LayoutRect();    
809 }
810
811 void Node::refEventTarget()
812 {
813     ref();
814 }
815
816 void Node::derefEventTarget()
817 {
818     deref();
819 }
820
821 void Node::adjustStyleValidity(Style::Validity validity, Style::InvalidationMode mode)
822 {
823     if (validity > styleValidity()) {
824         m_nodeFlags &= ~StyleValidityMask;
825         m_nodeFlags |= static_cast<unsigned>(validity) << StyleValidityShift;
826     }
827     if (mode == Style::InvalidationMode::RecompositeLayer)
828         setFlag(StyleResolutionShouldRecompositeLayerFlag);
829 }
830
831 inline void Node::updateAncestorsForStyleRecalc()
832 {
833     auto composedAncestors = composedTreeAncestors(*this);
834     auto it = composedAncestors.begin();
835     auto end = composedAncestors.end();
836     if (it != end) {
837         it->setDirectChildNeedsStyleRecalc();
838
839         for (; it != end; ++it) {
840             // Iterator skips over shadow roots.
841             if (auto* shadowRoot = it->shadowRoot())
842                 shadowRoot->setChildNeedsStyleRecalc();
843             if (it->childNeedsStyleRecalc())
844                 break;
845             it->setChildNeedsStyleRecalc();
846         }
847     }
848
849     auto* documentElement = document().documentElement();
850     if (!documentElement)
851         return;
852     if (!documentElement->childNeedsStyleRecalc() && !documentElement->needsStyleRecalc())
853         return;
854     document().setChildNeedsStyleRecalc();
855     document().scheduleStyleRecalc();
856 }
857
858 void Node::invalidateStyle(Style::Validity validity, Style::InvalidationMode mode)
859 {
860     ASSERT(validity != Style::Validity::Valid);
861     if (!inRenderedDocument())
862         return;
863
864     // FIXME: This should eventually be an ASSERT.
865     if (document().inRenderTreeUpdate())
866         return;
867
868     // FIXME: Why the second condition?
869     bool markAncestors = styleValidity() == Style::Validity::Valid || validity == Style::Validity::SubtreeAndRenderersInvalid;
870
871     adjustStyleValidity(validity, mode);
872
873     if (markAncestors)
874         updateAncestorsForStyleRecalc();
875 }
876
877 unsigned Node::computeNodeIndex() const
878 {
879     unsigned count = 0;
880     for (Node* sibling = previousSibling(); sibling; sibling = sibling->previousSibling())
881         ++count;
882     return count;
883 }
884
885 template<unsigned type>
886 bool shouldInvalidateNodeListCachesForAttr(const unsigned nodeListCounts[], const QualifiedName& attrName)
887 {
888     if (nodeListCounts[type] && shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
889         return true;
890     return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeListCounts, attrName);
891 }
892
893 template<>
894 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const unsigned[], const QualifiedName&)
895 {
896     return false;
897 }
898
899 inline bool Document::shouldInvalidateNodeListAndCollectionCaches() const
900 {
901     for (int type = 0; type < numNodeListInvalidationTypes; ++type) {
902         if (m_nodeListAndCollectionCounts[type])
903             return true;
904     }
905     return false;
906 }
907
908 inline bool Document::shouldInvalidateNodeListAndCollectionCachesForAttribute(const QualifiedName& attrName) const
909 {
910     return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeListAndCollectionCounts, attrName);
911 }
912
913 template <typename InvalidationFunction>
914 void Document::invalidateNodeListAndCollectionCaches(InvalidationFunction invalidate)
915 {
916     for (auto* list : copyToVectorSpecialization<Vector<LiveNodeList*, 8>>(m_listsInvalidatedAtDocument))
917         invalidate(*list);
918
919     for (auto* collection : copyToVectorSpecialization<Vector<HTMLCollection*, 8>>(m_collectionsInvalidatedAtDocument))
920         invalidate(*collection);
921 }
922
923 void Node::invalidateNodeListAndCollectionCachesInAncestors()
924 {
925     if (hasRareData()) {
926         if (auto* lists = rareData()->nodeLists())
927             lists->clearChildNodeListCache();
928     }
929
930     if (!document().shouldInvalidateNodeListAndCollectionCaches())
931         return;
932
933     document().invalidateNodeListAndCollectionCaches([](auto& list) {
934         list.invalidateCache();
935     });
936
937     for (auto* node = this; node; node = node->parentNode()) {
938         if (!node->hasRareData())
939             continue;
940
941         if (auto* lists = node->rareData()->nodeLists())
942             lists->invalidateCaches();
943     }
944 }
945
946 void Node::invalidateNodeListAndCollectionCachesInAncestorsForAttribute(const QualifiedName& attrName)
947 {
948     ASSERT(is<Element>(*this));
949
950     if (!document().shouldInvalidateNodeListAndCollectionCachesForAttribute(attrName))
951         return;
952
953     document().invalidateNodeListAndCollectionCaches([&attrName](auto& list) {
954         list.invalidateCacheForAttribute(attrName);
955     });
956
957     for (auto* node = this; node; node = node->parentNode()) {
958         if (!node->hasRareData())
959             continue;
960
961         if (auto* lists = node->rareData()->nodeLists())
962             lists->invalidateCachesForAttribute(attrName);
963     }
964 }
965
966 NodeListsNodeData* Node::nodeLists()
967 {
968     return hasRareData() ? rareData()->nodeLists() : nullptr;
969 }
970
971 void Node::clearNodeLists()
972 {
973     rareData()->clearNodeLists();
974 }
975
976 ExceptionOr<void> Node::checkSetPrefix(const AtomicString& prefix)
977 {
978     // Perform error checking as required by spec for setting Node.prefix. Used by
979     // Element::setPrefix() and Attr::setPrefix()
980
981     if (!prefix.isEmpty() && !Document::isValidName(prefix))
982         return Exception { InvalidCharacterError };
983
984     // FIXME: Raise NamespaceError if prefix is malformed per the Namespaces in XML specification.
985
986     auto& namespaceURI = this->namespaceURI();
987     if (namespaceURI.isEmpty() && !prefix.isEmpty())
988         return Exception { NamespaceError };
989     if (prefix == xmlAtom() && namespaceURI != XMLNames::xmlNamespaceURI)
990         return Exception { NamespaceError };
991
992     // Attribute-specific checks are in Attr::setPrefix().
993
994     return { };
995 }
996
997 bool Node::isDescendantOf(const Node& other) const
998 {
999     // Return true if other is an ancestor of this, otherwise false
1000     if (!other.hasChildNodes() || isConnected() != other.isConnected())
1001         return false;
1002     if (other.isDocumentNode())
1003         return &document() == &other && !isDocumentNode() && isConnected();
1004     for (const auto* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
1005         if (ancestor == &other)
1006             return true;
1007     }
1008     return false;
1009 }
1010
1011 bool Node::isDescendantOrShadowDescendantOf(const Node* other) const
1012 {
1013     // FIXME: This element's shadow tree's host could be inside another shadow tree.
1014     // This function doesn't handle that case correctly. Maybe share code with
1015     // the containsIncludingShadowDOM function?
1016     return other && (isDescendantOf(*other) || other->contains(shadowHost()));
1017 }
1018
1019 bool Node::contains(const Node* node) const
1020 {
1021     return this == node || (node && node->isDescendantOf(*this));
1022 }
1023
1024 bool Node::containsIncludingShadowDOM(const Node* node) const
1025 {
1026     for (; node; node = node->parentOrShadowHostNode()) {
1027         if (node == this)
1028             return true;
1029     }
1030     return false;
1031 }
1032
1033 bool Node::containsIncludingHostElements(const Node* node) const
1034 {
1035     while (node) {
1036         if (node == this)
1037             return true;
1038         if (is<DocumentFragment>(*node) && downcast<DocumentFragment>(*node).isTemplateContent())
1039             node = static_cast<const TemplateContentDocumentFragment*>(node)->host();
1040         else
1041             node = node->parentOrShadowHostNode();
1042     }
1043     return false;
1044 }
1045
1046 Node* Node::pseudoAwarePreviousSibling() const
1047 {
1048     Element* parentOrHost = is<PseudoElement>(*this) ? downcast<PseudoElement>(*this).hostElement() : parentElement();
1049     if (parentOrHost && !previousSibling()) {
1050         if (isAfterPseudoElement() && parentOrHost->lastChild())
1051             return parentOrHost->lastChild();
1052         if (!isBeforePseudoElement())
1053             return parentOrHost->beforePseudoElement();
1054     }
1055     return previousSibling();
1056 }
1057
1058 Node* Node::pseudoAwareNextSibling() const
1059 {
1060     Element* parentOrHost = is<PseudoElement>(*this) ? downcast<PseudoElement>(*this).hostElement() : parentElement();
1061     if (parentOrHost && !nextSibling()) {
1062         if (isBeforePseudoElement() && parentOrHost->firstChild())
1063             return parentOrHost->firstChild();
1064         if (!isAfterPseudoElement())
1065             return parentOrHost->afterPseudoElement();
1066     }
1067     return nextSibling();
1068 }
1069
1070 Node* Node::pseudoAwareFirstChild() const
1071 {
1072     if (is<Element>(*this)) {
1073         const Element& currentElement = downcast<Element>(*this);
1074         Node* first = currentElement.beforePseudoElement();
1075         if (first)
1076             return first;
1077         first = currentElement.firstChild();
1078         if (!first)
1079             first = currentElement.afterPseudoElement();
1080         return first;
1081     }
1082     return firstChild();
1083 }
1084
1085 Node* Node::pseudoAwareLastChild() const
1086 {
1087     if (is<Element>(*this)) {
1088         const Element& currentElement = downcast<Element>(*this);
1089         Node* last = currentElement.afterPseudoElement();
1090         if (last)
1091             return last;
1092         last = currentElement.lastChild();
1093         if (!last)
1094             last = currentElement.beforePseudoElement();
1095         return last;
1096     }
1097     return lastChild();
1098 }
1099
1100 const RenderStyle* Node::computedStyle(PseudoId pseudoElementSpecifier)
1101 {
1102     auto* composedParent = composedTreeAncestors(*this).first();
1103     if (!composedParent)
1104         return nullptr;
1105     return composedParent->computedStyle(pseudoElementSpecifier);
1106 }
1107
1108 int Node::maxCharacterOffset() const
1109 {
1110     ASSERT_NOT_REACHED();
1111     return 0;
1112 }
1113
1114 // FIXME: Shouldn't these functions be in the editing code?  Code that asks questions about HTML in the core DOM class
1115 // is obviously misplaced.
1116 bool Node::canStartSelection() const
1117 {
1118     if (hasEditableStyle())
1119         return true;
1120
1121     if (renderer()) {
1122         const RenderStyle& style = renderer()->style();
1123         // We allow selections to begin within an element that has -webkit-user-select: none set,
1124         // but if the element is draggable then dragging should take priority over selection.
1125         if (style.userDrag() == UserDrag::Element && style.userSelect() == UserSelect::None)
1126             return false;
1127     }
1128     return parentOrShadowHostNode() ? parentOrShadowHostNode()->canStartSelection() : true;
1129 }
1130
1131 Element* Node::shadowHost() const
1132 {
1133     if (ShadowRoot* root = containingShadowRoot())
1134         return root->host();
1135     return nullptr;
1136 }
1137
1138 ShadowRoot* Node::containingShadowRoot() const
1139 {
1140     ContainerNode& root = treeScope().rootNode();
1141     return is<ShadowRoot>(root) ? downcast<ShadowRoot>(&root) : nullptr;
1142 }
1143
1144 #if !ASSERT_DISABLED
1145 // https://dom.spec.whatwg.org/#concept-closed-shadow-hidden
1146 static bool isClosedShadowHiddenUsingSpecDefinition(const Node& A, const Node& B)
1147 {
1148     return A.isInShadowTree()
1149         && !A.rootNode().containsIncludingShadowDOM(&B)
1150         && (A.containingShadowRoot()->mode() != ShadowRootMode::Open || isClosedShadowHiddenUsingSpecDefinition(*A.shadowHost(), B));
1151 }
1152 #endif
1153
1154 // http://w3c.github.io/webcomponents/spec/shadow/#dfn-unclosed-node
1155 bool Node::isClosedShadowHidden(const Node& otherNode) const
1156 {
1157     // Use Vector instead of HashSet since we expect the number of ancestor tree scopes to be small.
1158     Vector<TreeScope*, 8> ancestorScopesOfThisNode;
1159
1160     for (auto* scope = &treeScope(); scope; scope = scope->parentTreeScope())
1161         ancestorScopesOfThisNode.append(scope);
1162
1163     for (auto* treeScopeThatCanAccessOtherNode = &otherNode.treeScope(); treeScopeThatCanAccessOtherNode; treeScopeThatCanAccessOtherNode = treeScopeThatCanAccessOtherNode->parentTreeScope()) {
1164         for (auto* scope : ancestorScopesOfThisNode) {
1165             if (scope == treeScopeThatCanAccessOtherNode) {
1166                 ASSERT(!isClosedShadowHiddenUsingSpecDefinition(otherNode, *this));
1167                 return false; // treeScopeThatCanAccessOtherNode is a shadow-including inclusive ancestor of this node.
1168             }
1169         }
1170         auto& root = treeScopeThatCanAccessOtherNode->rootNode();
1171         if (is<ShadowRoot>(root) && downcast<ShadowRoot>(root).mode() != ShadowRootMode::Open)
1172             break;
1173     }
1174
1175     ASSERT(isClosedShadowHiddenUsingSpecDefinition(otherNode, *this));
1176     return true;
1177 }
1178
1179 static inline ShadowRoot* parentShadowRoot(const Node& node)
1180 {
1181     if (auto* parent = node.parentElement())
1182         return parent->shadowRoot();
1183     return nullptr;
1184 }
1185
1186 HTMLSlotElement* Node::assignedSlot() const
1187 {
1188     if (auto* shadowRoot = parentShadowRoot(*this))
1189         return shadowRoot->findAssignedSlot(*this);
1190     return nullptr;
1191 }
1192
1193 HTMLSlotElement* Node::assignedSlotForBindings() const
1194 {
1195     auto* shadowRoot = parentShadowRoot(*this);
1196     if (shadowRoot && shadowRoot->mode() == ShadowRootMode::Open)
1197         return shadowRoot->findAssignedSlot(*this);
1198     return nullptr;
1199 }
1200
1201 ContainerNode* Node::parentInComposedTree() const
1202 {
1203     ASSERT(isMainThreadOrGCThread());
1204     if (auto* slot = assignedSlot())
1205         return slot;
1206     if (is<ShadowRoot>(*this))
1207         return downcast<ShadowRoot>(*this).host();
1208     return parentNode();
1209 }
1210
1211 Element* Node::parentElementInComposedTree() const
1212 {
1213     if (auto* slot = assignedSlot())
1214         return slot;
1215     if (is<PseudoElement>(*this))
1216         return downcast<PseudoElement>(*this).hostElement();
1217     if (auto* parent = parentNode()) {
1218         if (is<ShadowRoot>(*parent))
1219             return downcast<ShadowRoot>(*parent).host();
1220         if (is<Element>(*parent))
1221             return downcast<Element>(parent);
1222     }
1223     return nullptr;
1224 }
1225
1226 bool Node::isInUserAgentShadowTree() const
1227 {
1228     auto* shadowRoot = containingShadowRoot();
1229     return shadowRoot && shadowRoot->mode() == ShadowRootMode::UserAgent;
1230 }
1231
1232 Node* Node::nonBoundaryShadowTreeRootNode()
1233 {
1234     ASSERT(!isShadowRoot());
1235     Node* root = this;
1236     while (root) {
1237         if (root->isShadowRoot())
1238             return root;
1239         Node* parent = root->parentNodeGuaranteedHostFree();
1240         if (parent && parent->isShadowRoot())
1241             return root;
1242         root = parent;
1243     }
1244     return 0;
1245 }
1246
1247 ContainerNode* Node::nonShadowBoundaryParentNode() const
1248 {
1249     ContainerNode* parent = parentNode();
1250     return parent && !parent->isShadowRoot() ? parent : nullptr;
1251 }
1252
1253 Element* Node::parentOrShadowHostElement() const
1254 {
1255     ContainerNode* parent = parentOrShadowHostNode();
1256     if (!parent)
1257         return nullptr;
1258
1259     if (is<ShadowRoot>(*parent))
1260         return downcast<ShadowRoot>(*parent).host();
1261
1262     if (!is<Element>(*parent))
1263         return nullptr;
1264
1265     return downcast<Element>(parent);
1266 }
1267
1268 Node& Node::traverseToRootNode() const
1269 {
1270     Node* node = const_cast<Node*>(this);
1271     Node* highest = node;
1272     for (; node; node = node->parentNode())
1273         highest = node;
1274     return *highest;
1275 }
1276
1277 // https://dom.spec.whatwg.org/#concept-shadow-including-root
1278 Node& Node::shadowIncludingRoot() const
1279 {
1280     auto& root = rootNode();
1281     if (!is<ShadowRoot>(root))
1282         return root;
1283     auto* host = downcast<ShadowRoot>(root).host();
1284     return host ? host->shadowIncludingRoot() : root;
1285 }
1286
1287 Node& Node::getRootNode(const GetRootNodeOptions& options) const
1288 {
1289     return options.composed ? shadowIncludingRoot() : rootNode();
1290 }
1291
1292 Node::InsertedIntoAncestorResult Node::insertedIntoAncestor(InsertionType insertionType, ContainerNode& parentOfInsertedTree)
1293 {
1294     if (insertionType.connectedToDocument)
1295         setFlag(IsConnectedFlag);
1296     if (parentOfInsertedTree.isInShadowTree())
1297         setFlag(IsInShadowTreeFlag);
1298
1299     invalidateStyle(Style::Validity::SubtreeAndRenderersInvalid);
1300
1301     return InsertedIntoAncestorResult::Done;
1302 }
1303
1304 void Node::removedFromAncestor(RemovalType removalType, ContainerNode&)
1305 {
1306     if (removalType.disconnectedFromDocument)
1307         clearFlag(IsConnectedFlag);
1308     if (isInShadowTree() && !treeScope().rootNode().isShadowRoot())
1309         clearFlag(IsInShadowTreeFlag);
1310 }
1311
1312 bool Node::isRootEditableElement() const
1313 {
1314     return hasEditableStyle() && isElementNode() && (!parentNode() || !parentNode()->hasEditableStyle()
1315         || !parentNode()->isElementNode() || hasTagName(bodyTag));
1316 }
1317
1318 Element* Node::rootEditableElement() const
1319 {
1320     Element* result = nullptr;
1321     for (Node* node = const_cast<Node*>(this); node && node->hasEditableStyle(); node = node->parentNode()) {
1322         if (is<Element>(*node))
1323             result = downcast<Element>(node);
1324         if (is<HTMLBodyElement>(*node))
1325             break;
1326     }
1327     return result;
1328 }
1329
1330 // FIXME: End of obviously misplaced HTML editing functions.  Try to move these out of Node.
1331
1332 Document* Node::ownerDocument() const
1333 {
1334     Document* document = &this->document();
1335     return document == this ? nullptr : document;
1336 }
1337
1338 const URL& Node::baseURI() const
1339 {
1340     auto& url = document().baseURL();
1341     return url.isNull() ? WTF::blankURL() : url;
1342 }
1343
1344 bool Node::isEqualNode(Node* other) const
1345 {
1346     if (!other)
1347         return false;
1348     
1349     NodeType nodeType = this->nodeType();
1350     if (nodeType != other->nodeType())
1351         return false;
1352     
1353     switch (nodeType) {
1354     case Node::DOCUMENT_TYPE_NODE: {
1355         auto& thisDocType = downcast<DocumentType>(*this);
1356         auto& otherDocType = downcast<DocumentType>(*other);
1357         if (thisDocType.name() != otherDocType.name())
1358             return false;
1359         if (thisDocType.publicId() != otherDocType.publicId())
1360             return false;
1361         if (thisDocType.systemId() != otherDocType.systemId())
1362             return false;
1363         break;
1364         }
1365     case Node::ELEMENT_NODE: {
1366         auto& thisElement = downcast<Element>(*this);
1367         auto& otherElement = downcast<Element>(*other);
1368         if (thisElement.tagQName() != otherElement.tagQName())
1369             return false;
1370         if (!thisElement.hasEquivalentAttributes(otherElement))
1371             return false;
1372         break;
1373         }
1374     case Node::PROCESSING_INSTRUCTION_NODE: {
1375         auto& thisProcessingInstruction = downcast<ProcessingInstruction>(*this);
1376         auto& otherProcessingInstruction = downcast<ProcessingInstruction>(*other);
1377         if (thisProcessingInstruction.target() != otherProcessingInstruction.target())
1378             return false;
1379         if (thisProcessingInstruction.data() != otherProcessingInstruction.data())
1380             return false;
1381         break;
1382         }
1383     case Node::CDATA_SECTION_NODE:
1384     case Node::TEXT_NODE:
1385     case Node::COMMENT_NODE: {
1386         auto& thisCharacterData = downcast<CharacterData>(*this);
1387         auto& otherCharacterData = downcast<CharacterData>(*other);
1388         if (thisCharacterData.data() != otherCharacterData.data())
1389             return false;
1390         break;
1391         }
1392     case Node::ATTRIBUTE_NODE: {
1393         auto& thisAttribute = downcast<Attr>(*this);
1394         auto& otherAttribute = downcast<Attr>(*other);
1395         if (thisAttribute.qualifiedName() != otherAttribute.qualifiedName())
1396             return false;
1397         if (thisAttribute.value() != otherAttribute.value())
1398             return false;
1399         break;
1400         }
1401     case Node::DOCUMENT_NODE:
1402     case Node::DOCUMENT_FRAGMENT_NODE:
1403         break;
1404     }
1405     
1406     Node* child = firstChild();
1407     Node* otherChild = other->firstChild();
1408     
1409     while (child) {
1410         if (!child->isEqualNode(otherChild))
1411             return false;
1412         
1413         child = child->nextSibling();
1414         otherChild = otherChild->nextSibling();
1415     }
1416     
1417     if (otherChild)
1418         return false;
1419     
1420     return true;
1421 }
1422
1423 // https://dom.spec.whatwg.org/#locate-a-namespace
1424 static const AtomicString& locateDefaultNamespace(const Node& node, const AtomicString& prefix)
1425 {
1426     switch (node.nodeType()) {
1427     case Node::ELEMENT_NODE: {
1428         auto& element = downcast<Element>(node);
1429         auto& namespaceURI = element.namespaceURI();
1430         if (!namespaceURI.isNull() && element.prefix() == prefix)
1431             return namespaceURI;
1432
1433         if (element.hasAttributes()) {
1434             for (auto& attribute : element.attributesIterator()) {
1435                 if (attribute.namespaceURI() != XMLNSNames::xmlnsNamespaceURI)
1436                     continue;
1437
1438                 if ((prefix.isNull() && attribute.prefix().isNull() && attribute.localName() == xmlnsAtom()) || (attribute.prefix() == xmlnsAtom() && attribute.localName() == prefix)) {
1439                     auto& result = attribute.value();
1440                     return result.isEmpty() ? nullAtom() : result;
1441                 }
1442             }
1443         }
1444         auto* parent = node.parentElement();
1445         return parent ? locateDefaultNamespace(*parent, prefix) : nullAtom();
1446     }
1447     case Node::DOCUMENT_NODE:
1448         if (auto* documentElement = downcast<Document>(node).documentElement())
1449             return locateDefaultNamespace(*documentElement, prefix);
1450         return nullAtom();
1451     case Node::DOCUMENT_TYPE_NODE:
1452     case Node::DOCUMENT_FRAGMENT_NODE:
1453         return nullAtom();
1454     case Node::ATTRIBUTE_NODE:
1455         if (auto* ownerElement = downcast<Attr>(node).ownerElement())
1456             return locateDefaultNamespace(*ownerElement, prefix);
1457         return nullAtom();
1458     default:
1459         if (auto* parent = node.parentElement())
1460             return locateDefaultNamespace(*parent, prefix);
1461         return nullAtom();
1462     }
1463 }
1464
1465 // https://dom.spec.whatwg.org/#dom-node-isdefaultnamespace
1466 bool Node::isDefaultNamespace(const AtomicString& potentiallyEmptyNamespace) const
1467 {
1468     const AtomicString& namespaceURI = potentiallyEmptyNamespace.isEmpty() ? nullAtom() : potentiallyEmptyNamespace;
1469     return locateDefaultNamespace(*this, nullAtom()) == namespaceURI;
1470 }
1471
1472 // https://dom.spec.whatwg.org/#dom-node-lookupnamespaceuri
1473 const AtomicString& Node::lookupNamespaceURI(const AtomicString& potentiallyEmptyPrefix) const
1474 {
1475     const AtomicString& prefix = potentiallyEmptyPrefix.isEmpty() ? nullAtom() : potentiallyEmptyPrefix;
1476     return locateDefaultNamespace(*this, prefix);
1477 }
1478
1479 // https://dom.spec.whatwg.org/#locate-a-namespace-prefix
1480 static const AtomicString& locateNamespacePrefix(const Element& element, const AtomicString& namespaceURI)
1481 {
1482     if (element.namespaceURI() == namespaceURI)
1483         return element.prefix();
1484
1485     if (element.hasAttributes()) {
1486         for (auto& attribute : element.attributesIterator()) {
1487             if (attribute.prefix() == xmlnsAtom() && attribute.value() == namespaceURI)
1488                 return attribute.localName();
1489         }
1490     }
1491     auto* parent = element.parentElement();
1492     return parent ? locateNamespacePrefix(*parent, namespaceURI) : nullAtom();
1493 }
1494
1495 // https://dom.spec.whatwg.org/#dom-node-lookupprefix
1496 const AtomicString& Node::lookupPrefix(const AtomicString& namespaceURI) const
1497 {
1498     if (namespaceURI.isEmpty())
1499         return nullAtom();
1500     
1501     switch (nodeType()) {
1502     case ELEMENT_NODE:
1503         return locateNamespacePrefix(downcast<Element>(*this), namespaceURI);
1504     case DOCUMENT_NODE:
1505         if (auto* documentElement = downcast<Document>(*this).documentElement())
1506             return locateNamespacePrefix(*documentElement, namespaceURI);
1507         return nullAtom();
1508     case DOCUMENT_FRAGMENT_NODE:
1509     case DOCUMENT_TYPE_NODE:
1510         return nullAtom();
1511     case ATTRIBUTE_NODE:
1512         if (auto* ownerElement = downcast<Attr>(*this).ownerElement())
1513             return locateNamespacePrefix(*ownerElement, namespaceURI);
1514         return nullAtom();
1515     default:
1516         if (auto* parent = parentElement())
1517             return locateNamespacePrefix(*parent, namespaceURI);
1518         return nullAtom();
1519     }
1520 }
1521
1522 static void appendTextContent(const Node* node, bool convertBRsToNewlines, bool& isNullString, StringBuilder& content)
1523 {
1524     switch (node->nodeType()) {
1525     case Node::TEXT_NODE:
1526     case Node::CDATA_SECTION_NODE:
1527     case Node::COMMENT_NODE:
1528         isNullString = false;
1529         content.append(downcast<CharacterData>(*node).data());
1530         break;
1531
1532     case Node::PROCESSING_INSTRUCTION_NODE:
1533         isNullString = false;
1534         content.append(downcast<ProcessingInstruction>(*node).data());
1535         break;
1536     
1537     case Node::ATTRIBUTE_NODE:
1538         isNullString = false;
1539         content.append(downcast<Attr>(*node).value());
1540         break;
1541
1542     case Node::ELEMENT_NODE:
1543         if (node->hasTagName(brTag) && convertBRsToNewlines) {
1544             isNullString = false;
1545             content.append('\n');
1546             break;
1547         }
1548         FALLTHROUGH;
1549     case Node::DOCUMENT_FRAGMENT_NODE:
1550         isNullString = false;
1551         for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
1552             if (child->nodeType() == Node::COMMENT_NODE || child->nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
1553                 continue;
1554             appendTextContent(child, convertBRsToNewlines, isNullString, content);
1555         }
1556         break;
1557
1558     case Node::DOCUMENT_NODE:
1559     case Node::DOCUMENT_TYPE_NODE:
1560         break;
1561     }
1562 }
1563
1564 String Node::textContent(bool convertBRsToNewlines) const
1565 {
1566     StringBuilder content;
1567     bool isNullString = true;
1568     appendTextContent(this, convertBRsToNewlines, isNullString, content);
1569     return isNullString ? String() : content.toString();
1570 }
1571
1572 ExceptionOr<void> Node::setTextContent(const String& text)
1573 {           
1574     switch (nodeType()) {
1575     case ATTRIBUTE_NODE:
1576     case TEXT_NODE:
1577     case CDATA_SECTION_NODE:
1578     case COMMENT_NODE:
1579     case PROCESSING_INSTRUCTION_NODE:
1580         return setNodeValue(text);
1581     case ELEMENT_NODE:
1582     case DOCUMENT_FRAGMENT_NODE: {
1583         auto& container = downcast<ContainerNode>(*this);
1584         if (text.isEmpty())
1585             container.replaceAllChildren(nullptr);
1586         else
1587             container.replaceAllChildren(document().createTextNode(text));
1588         return { };
1589     }
1590     case DOCUMENT_NODE:
1591     case DOCUMENT_TYPE_NODE:
1592         // Do nothing.
1593         return { };
1594     }
1595     ASSERT_NOT_REACHED();
1596     return { };
1597 }
1598
1599 static SHA1::Digest hashPointer(void* pointer)
1600 {
1601     SHA1 sha1;
1602     sha1.addBytes(reinterpret_cast<const uint8_t*>(&pointer), sizeof(pointer));
1603     SHA1::Digest digest;
1604     sha1.computeHash(digest);
1605     return digest;
1606 }
1607
1608 static inline unsigned short compareDetachedElementsPosition(Node& firstNode, Node& secondNode)
1609 {
1610     // If the 2 nodes are not in the same tree, return the result of adding DOCUMENT_POSITION_DISCONNECTED,
1611     // DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, and either DOCUMENT_POSITION_PRECEDING or
1612     // DOCUMENT_POSITION_FOLLOWING, with the constraint that this is to be consistent. Whether to return
1613     // DOCUMENT_POSITION_PRECEDING or DOCUMENT_POSITION_FOLLOWING is implemented by comparing cryptographic
1614     // hashes of Node pointers.
1615     // See step 3 in https://dom.spec.whatwg.org/#dom-node-comparedocumentposition
1616     SHA1::Digest firstHash = hashPointer(&firstNode);
1617     SHA1::Digest secondHash = hashPointer(&secondNode);
1618
1619     unsigned short direction = memcmp(firstHash.data(), secondHash.data(), SHA1::hashSize) > 0 ? Node::DOCUMENT_POSITION_PRECEDING : Node::DOCUMENT_POSITION_FOLLOWING;
1620
1621     return Node::DOCUMENT_POSITION_DISCONNECTED | Node::DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | direction;
1622 }
1623
1624 unsigned short Node::compareDocumentPosition(Node& otherNode)
1625 {
1626     if (&otherNode == this)
1627         return DOCUMENT_POSITION_EQUIVALENT;
1628     
1629     Attr* attr1 = is<Attr>(*this) ? downcast<Attr>(this) : nullptr;
1630     Attr* attr2 = is<Attr>(otherNode) ? &downcast<Attr>(otherNode) : nullptr;
1631     
1632     Node* start1 = attr1 ? attr1->ownerElement() : this;
1633     Node* start2 = attr2 ? attr2->ownerElement() : &otherNode;
1634     
1635     // If either of start1 or start2 is null, then we are disconnected, since one of the nodes is
1636     // an orphaned attribute node.
1637     if (!start1 || !start2)
1638         return compareDetachedElementsPosition(*this, otherNode);
1639
1640     Vector<Node*, 16> chain1;
1641     Vector<Node*, 16> chain2;
1642     if (attr1)
1643         chain1.append(attr1);
1644     if (attr2)
1645         chain2.append(attr2);
1646     
1647     if (attr1 && attr2 && start1 == start2 && start1) {
1648         // We are comparing two attributes on the same node. Crawl our attribute map and see which one we hit first.
1649         Element* owner1 = attr1->ownerElement();
1650         owner1->synchronizeAllAttributes();
1651         for (const Attribute& attribute : owner1->attributesIterator()) {
1652             // If neither of the two determining nodes is a child node and nodeType is the same for both determining nodes, then an
1653             // implementation-dependent order between the determining nodes is returned. This order is stable as long as no nodes of
1654             // the same nodeType are inserted into or removed from the direct container. This would be the case, for example, 
1655             // when comparing two attributes of the same element, and inserting or removing additional attributes might change 
1656             // the order between existing attributes.
1657             if (attr1->qualifiedName() == attribute.name())
1658                 return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_FOLLOWING;
1659             if (attr2->qualifiedName() == attribute.name())
1660                 return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_PRECEDING;
1661         }
1662         
1663         ASSERT_NOT_REACHED();
1664         return DOCUMENT_POSITION_DISCONNECTED;
1665     }
1666
1667     // If one node is in the document and the other is not, we must be disconnected.
1668     // If the nodes have different owning documents, they must be disconnected.  Note that we avoid
1669     // comparing Attr nodes here, since they return false from isConnected() all the time (which seems like a bug).
1670     if (start1->isConnected() != start2->isConnected() || &start1->treeScope() != &start2->treeScope())
1671         return compareDetachedElementsPosition(*this, otherNode);
1672
1673     // We need to find a common ancestor container, and then compare the indices of the two immediate children.
1674     Node* current;
1675     for (current = start1; current; current = current->parentNode())
1676         chain1.append(current);
1677     for (current = start2; current; current = current->parentNode())
1678         chain2.append(current);
1679
1680     unsigned index1 = chain1.size();
1681     unsigned index2 = chain2.size();
1682
1683     // If the two elements don't have a common root, they're not in the same tree.
1684     if (chain1[index1 - 1] != chain2[index2 - 1])
1685         return compareDetachedElementsPosition(*this, otherNode);
1686
1687     // Walk the two chains backwards and look for the first difference.
1688     for (unsigned i = std::min(index1, index2); i; --i) {
1689         Node* child1 = chain1[--index1];
1690         Node* child2 = chain2[--index2];
1691         if (child1 != child2) {
1692             // If one of the children is an attribute, it wins.
1693             if (child1->nodeType() == ATTRIBUTE_NODE)
1694                 return DOCUMENT_POSITION_FOLLOWING;
1695             if (child2->nodeType() == ATTRIBUTE_NODE)
1696                 return DOCUMENT_POSITION_PRECEDING;
1697             
1698             if (!child2->nextSibling())
1699                 return DOCUMENT_POSITION_FOLLOWING;
1700             if (!child1->nextSibling())
1701                 return DOCUMENT_POSITION_PRECEDING;
1702
1703             // Otherwise we need to see which node occurs first.  Crawl backwards from child2 looking for child1.
1704             for (Node* child = child2->previousSibling(); child; child = child->previousSibling()) {
1705                 if (child == child1)
1706                     return DOCUMENT_POSITION_FOLLOWING;
1707             }
1708             return DOCUMENT_POSITION_PRECEDING;
1709         }
1710     }
1711     
1712     // There was no difference between the two parent chains, i.e., one was a subset of the other.  The shorter
1713     // chain is the ancestor.
1714     return index1 < index2 ? 
1715                DOCUMENT_POSITION_FOLLOWING | DOCUMENT_POSITION_CONTAINED_BY :
1716                DOCUMENT_POSITION_PRECEDING | DOCUMENT_POSITION_CONTAINS;
1717 }
1718
1719 FloatPoint Node::convertToPage(const FloatPoint& p) const
1720 {
1721     // If there is a renderer, just ask it to do the conversion
1722     if (renderer())
1723         return renderer()->localToAbsolute(p, UseTransforms);
1724     
1725     // Otherwise go up the tree looking for a renderer
1726     if (auto* parent = parentElement())
1727         return parent->convertToPage(p);
1728
1729     // No parent - no conversion needed
1730     return p;
1731 }
1732
1733 FloatPoint Node::convertFromPage(const FloatPoint& p) const
1734 {
1735     // If there is a renderer, just ask it to do the conversion
1736     if (renderer())
1737         return renderer()->absoluteToLocal(p, UseTransforms);
1738
1739     // Otherwise go up the tree looking for a renderer
1740     if (auto* parent = parentElement())
1741         return parent->convertFromPage(p);
1742
1743     // No parent - no conversion needed
1744     return p;
1745 }
1746
1747 #if ENABLE(TREE_DEBUGGING)
1748
1749 static void appendAttributeDesc(const Node* node, StringBuilder& stringBuilder, const QualifiedName& name, const char* attrDesc)
1750 {
1751     if (!is<Element>(*node))
1752         return;
1753
1754     const AtomicString& attr = downcast<Element>(*node).getAttribute(name);
1755     if (attr.isEmpty())
1756         return;
1757
1758     stringBuilder.append(attrDesc);
1759     stringBuilder.append(attr);
1760 }
1761
1762 void Node::showNode(const char* prefix) const
1763 {
1764     if (!prefix)
1765         prefix = "";
1766     if (isTextNode()) {
1767         String value = nodeValue();
1768         value.replaceWithLiteral('\\', "\\\\");
1769         value.replaceWithLiteral('\n', "\\n");
1770         fprintf(stderr, "%s%s\t%p \"%s\"\n", prefix, nodeName().utf8().data(), this, value.utf8().data());
1771     } else {
1772         StringBuilder attrs;
1773         appendAttributeDesc(this, attrs, classAttr, " CLASS=");
1774         appendAttributeDesc(this, attrs, styleAttr, " STYLE=");
1775         fprintf(stderr, "%s%s\t%p (renderer %p) %s%s%s\n", prefix, nodeName().utf8().data(), this, renderer(), attrs.toString().utf8().data(), needsStyleRecalc() ? " (needs style recalc)" : "", childNeedsStyleRecalc() ? " (child needs style recalc)" : "");
1776     }
1777 }
1778
1779 void Node::showTreeForThis() const
1780 {
1781     showTreeAndMark(this, "*");
1782 }
1783
1784 void Node::showNodePathForThis() const
1785 {
1786     Vector<const Node*, 16> chain;
1787     const Node* node = this;
1788     while (node->parentOrShadowHostNode()) {
1789         chain.append(node);
1790         node = node->parentOrShadowHostNode();
1791     }
1792     for (unsigned index = chain.size(); index > 0; --index) {
1793         const Node* node = chain[index - 1];
1794         if (is<ShadowRoot>(*node)) {
1795             int count = 0;
1796             for (const ShadowRoot* shadowRoot = downcast<ShadowRoot>(node); shadowRoot && shadowRoot != node; shadowRoot = shadowRoot->shadowRoot())
1797                 ++count;
1798             fprintf(stderr, "/#shadow-root[%d]", count);
1799             continue;
1800         }
1801
1802         switch (node->nodeType()) {
1803         case ELEMENT_NODE: {
1804             fprintf(stderr, "/%s", node->nodeName().utf8().data());
1805
1806             const Element& element = downcast<Element>(*node);
1807             const AtomicString& idattr = element.getIdAttribute();
1808             bool hasIdAttr = !idattr.isNull() && !idattr.isEmpty();
1809             if (node->previousSibling() || node->nextSibling()) {
1810                 int count = 0;
1811                 for (Node* previous = node->previousSibling(); previous; previous = previous->previousSibling())
1812                     if (previous->nodeName() == node->nodeName())
1813                         ++count;
1814                 if (hasIdAttr)
1815                     fprintf(stderr, "[@id=\"%s\" and position()=%d]", idattr.string().utf8().data(), count);
1816                 else
1817                     fprintf(stderr, "[%d]", count);
1818             } else if (hasIdAttr)
1819                 fprintf(stderr, "[@id=\"%s\"]", idattr.string().utf8().data());
1820             break;
1821         }
1822         case TEXT_NODE:
1823             fprintf(stderr, "/text()");
1824             break;
1825         case ATTRIBUTE_NODE:
1826             fprintf(stderr, "/@%s", node->nodeName().utf8().data());
1827             break;
1828         default:
1829             break;
1830         }
1831     }
1832     fprintf(stderr, "\n");
1833 }
1834
1835 static void traverseTreeAndMark(const String& baseIndent, const Node* rootNode, const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2)
1836 {
1837     for (const Node* node = rootNode; node; node = NodeTraversal::next(*node)) {
1838         if (node == markedNode1)
1839             fprintf(stderr, "%s", markedLabel1);
1840         if (node == markedNode2)
1841             fprintf(stderr, "%s", markedLabel2);
1842
1843         StringBuilder indent;
1844         indent.append(baseIndent);
1845         for (const Node* tmpNode = node; tmpNode && tmpNode != rootNode; tmpNode = tmpNode->parentOrShadowHostNode())
1846             indent.append('\t');
1847         fprintf(stderr, "%s", indent.toString().utf8().data());
1848         node->showNode();
1849         indent.append('\t');
1850         if (!node->isShadowRoot()) {
1851             if (ShadowRoot* shadowRoot = node->shadowRoot())
1852                 traverseTreeAndMark(indent.toString(), shadowRoot, markedNode1, markedLabel1, markedNode2, markedLabel2);
1853         }
1854     }
1855 }
1856
1857 void Node::showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2) const
1858 {
1859     const Node* rootNode;
1860     const Node* node = this;
1861     while (node->parentOrShadowHostNode() && !node->hasTagName(bodyTag))
1862         node = node->parentOrShadowHostNode();
1863     rootNode = node;
1864
1865     String startingIndent;
1866     traverseTreeAndMark(startingIndent, rootNode, markedNode1, markedLabel1, markedNode2, markedLabel2);
1867 }
1868
1869 void Node::formatForDebugger(char* buffer, unsigned length) const
1870 {
1871     String result;
1872     String s;
1873
1874     s = nodeName();
1875     if (s.isEmpty())
1876         result = "<none>";
1877     else
1878         result = s;
1879
1880     strncpy(buffer, result.utf8().data(), length - 1);
1881 }
1882
1883 static ContainerNode* parentOrShadowHostOrFrameOwner(const Node* node)
1884 {
1885     ContainerNode* parent = node->parentOrShadowHostNode();
1886     if (!parent && node->document().frame())
1887         parent = node->document().frame()->ownerElement();
1888     return parent;
1889 }
1890
1891 static void showSubTreeAcrossFrame(const Node* node, const Node* markedNode, const String& indent)
1892 {
1893     if (node == markedNode)
1894         fputs("*", stderr);
1895     fputs(indent.utf8().data(), stderr);
1896     node->showNode();
1897     if (!node->isShadowRoot()) {
1898         if (node->isFrameOwnerElement())
1899             showSubTreeAcrossFrame(static_cast<const HTMLFrameOwnerElement*>(node)->contentDocument(), markedNode, indent + "\t");
1900         if (ShadowRoot* shadowRoot = node->shadowRoot())
1901             showSubTreeAcrossFrame(shadowRoot, markedNode, indent + "\t");
1902     }
1903     for (Node* child = node->firstChild(); child; child = child->nextSibling())
1904         showSubTreeAcrossFrame(child, markedNode, indent + "\t");
1905 }
1906
1907 void Node::showTreeForThisAcrossFrame() const
1908 {
1909     Node* rootNode = const_cast<Node*>(this);
1910     while (parentOrShadowHostOrFrameOwner(rootNode))
1911         rootNode = parentOrShadowHostOrFrameOwner(rootNode);
1912     showSubTreeAcrossFrame(rootNode, this, "");
1913 }
1914
1915 #endif // ENABLE(TREE_DEBUGGING)
1916
1917 // --------
1918
1919 void NodeListsNodeData::invalidateCaches()
1920 {
1921     for (auto& atomicName : m_atomicNameCaches)
1922         atomicName.value->invalidateCache();
1923
1924     for (auto& collection : m_cachedCollections)
1925         collection.value->invalidateCache();
1926
1927     for (auto& tagCollection : m_tagCollectionNSCache)
1928         tagCollection.value->invalidateCache();
1929 }
1930
1931 void NodeListsNodeData::invalidateCachesForAttribute(const QualifiedName& attrName)
1932 {
1933     for (auto& atomicName : m_atomicNameCaches)
1934         atomicName.value->invalidateCacheForAttribute(attrName);
1935
1936     for (auto& collection : m_cachedCollections)
1937         collection.value->invalidateCacheForAttribute(attrName);
1938 }
1939
1940 void Node::getSubresourceURLs(ListHashSet<URL>& urls) const
1941 {
1942     addSubresourceAttributeURLs(urls);
1943 }
1944
1945 Element* Node::enclosingLinkEventParentOrSelf()
1946 {
1947     for (Node* node = this; node; node = node->parentInComposedTree()) {
1948         // For imagemaps, the enclosing link element is the associated area element not the image itself.
1949         // So we don't let images be the enclosing link element, even though isLink sometimes returns
1950         // true for them.
1951         if (node->isLink() && !is<HTMLImageElement>(*node))
1952             return downcast<Element>(node);
1953     }
1954
1955     return nullptr;
1956 }
1957
1958 EventTargetInterface Node::eventTargetInterface() const
1959 {
1960     return NodeEventTargetInterfaceType;
1961 }
1962
1963 template <typename MoveNodeFunction, typename MoveShadowRootFunction>
1964 static void traverseSubtreeToUpdateTreeScope(Node& root, MoveNodeFunction moveNode, MoveShadowRootFunction moveShadowRoot)
1965 {
1966     for (Node* node = &root; node; node = NodeTraversal::next(*node, &root)) {
1967         moveNode(*node);
1968
1969         if (!is<Element>(*node))
1970             continue;
1971         Element& element = downcast<Element>(*node);
1972
1973         if (element.hasSyntheticAttrChildNodes()) {
1974             for (auto& attr : element.attrNodeList())
1975                 moveNode(*attr);
1976         }
1977
1978         if (auto* shadow = element.shadowRoot())
1979             moveShadowRoot(*shadow);
1980     }
1981 }
1982
1983 inline void Node::moveShadowTreeToNewDocument(ShadowRoot& shadowRoot, Document& oldDocument, Document& newDocument)
1984 {
1985     traverseSubtreeToUpdateTreeScope(shadowRoot, [&oldDocument, &newDocument](Node& node) {
1986         node.moveNodeToNewDocument(oldDocument, newDocument);
1987     }, [&oldDocument, &newDocument](ShadowRoot& innerShadowRoot) {
1988         RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(&innerShadowRoot.document() == &oldDocument);
1989         innerShadowRoot.moveShadowRootToNewDocument(newDocument);
1990         moveShadowTreeToNewDocument(innerShadowRoot, oldDocument, newDocument);
1991     });
1992 }
1993
1994 void Node::moveTreeToNewScope(Node& root, TreeScope& oldScope, TreeScope& newScope)
1995 {
1996     ASSERT(&oldScope != &newScope);
1997
1998     Document& oldDocument = oldScope.documentScope();
1999     Document& newDocument = newScope.documentScope();
2000     if (&oldDocument != &newDocument) {
2001         oldDocument.incrementReferencingNodeCount();
2002         traverseSubtreeToUpdateTreeScope(root, [&](Node& node) {
2003             ASSERT(!node.isTreeScope());
2004             RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(&node.treeScope() == &oldScope);
2005             node.setTreeScope(newScope);
2006             node.moveNodeToNewDocument(oldDocument, newDocument);
2007         }, [&](ShadowRoot& shadowRoot) {
2008             ASSERT_WITH_SECURITY_IMPLICATION(&shadowRoot.document() == &oldDocument);
2009             shadowRoot.moveShadowRootToNewParentScope(newScope, newDocument);
2010             moveShadowTreeToNewDocument(shadowRoot, oldDocument, newDocument);
2011         });
2012         RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(&oldScope.documentScope() == &oldDocument && &newScope.documentScope() == &newDocument);
2013         oldDocument.decrementReferencingNodeCount();
2014     } else {
2015         traverseSubtreeToUpdateTreeScope(root, [&](Node& node) {
2016             ASSERT(!node.isTreeScope());
2017             RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(&node.treeScope() == &oldScope);
2018             node.setTreeScope(newScope);
2019             if (UNLIKELY(!node.hasRareData()))
2020                 return;
2021             if (auto* nodeLists = node.rareData()->nodeLists())
2022                 nodeLists->adoptTreeScope();
2023         }, [&newScope](ShadowRoot& shadowRoot) {
2024             shadowRoot.setParentTreeScope(newScope);
2025         });
2026     }
2027 }
2028
2029 void Node::moveNodeToNewDocument(Document& oldDocument, Document& newDocument)
2030 {
2031     newDocument.incrementReferencingNodeCount();
2032     oldDocument.decrementReferencingNodeCount();
2033
2034     if (hasRareData()) {
2035         if (auto* nodeLists = rareData()->nodeLists())
2036             nodeLists->adoptDocument(oldDocument, newDocument);
2037         if (auto* registry = mutationObserverRegistry()) {
2038             for (auto& registration : *registry)
2039                 newDocument.addMutationObserverTypes(registration->mutationTypes());
2040         }
2041         if (auto* transientRegistry = transientMutationObserverRegistry()) {
2042             for (auto& registration : *transientRegistry)
2043                 newDocument.addMutationObserverTypes(registration->mutationTypes());
2044         }
2045     } else {
2046         ASSERT(!mutationObserverRegistry());
2047         ASSERT(!transientMutationObserverRegistry());
2048     }
2049
2050     oldDocument.moveNodeIteratorsToNewDocument(*this, newDocument);
2051
2052     if (AXObjectCache::accessibilityEnabled()) {
2053         if (auto* cache = oldDocument.existingAXObjectCache())
2054             cache->remove(*this);
2055     }
2056
2057     if (auto* eventTargetData = this->eventTargetData()) {
2058         if (!eventTargetData->eventListenerMap.isEmpty()) {
2059             for (auto& type : eventTargetData->eventListenerMap.eventTypes())
2060                 newDocument.addListenerTypeIfNeeded(type);
2061         }
2062
2063         unsigned numWheelEventHandlers = eventListeners(eventNames().mousewheelEvent).size() + eventListeners(eventNames().wheelEvent).size();
2064         for (unsigned i = 0; i < numWheelEventHandlers; ++i) {
2065             oldDocument.didRemoveWheelEventHandler(*this);
2066             newDocument.didAddWheelEventHandler(*this);
2067         }
2068
2069         unsigned numTouchEventListeners = 0;
2070 #if ENABLE(TOUCH_EVENTS)
2071         if (RuntimeEnabledFeatures::sharedFeatures().mouseEventsSimulationEnabled()) {
2072             for (auto& name : eventNames().extendedTouchRelatedEventNames())
2073                 numTouchEventListeners += eventListeners(name).size();
2074         } else {
2075 #endif
2076             for (auto& name : eventNames().touchRelatedEventNames())
2077                 numTouchEventListeners += eventListeners(name).size();
2078 #if ENABLE(TOUCH_EVENTS)
2079         }
2080 #endif
2081
2082         for (unsigned i = 0; i < numTouchEventListeners; ++i) {
2083             oldDocument.didRemoveTouchEventHandler(*this);
2084             newDocument.didAddTouchEventHandler(*this);
2085 #if ENABLE(TOUCH_EVENTS) && PLATFORM(IOS_FAMILY)
2086             oldDocument.removeTouchEventListener(*this);
2087             newDocument.addTouchEventListener(*this);
2088 #endif
2089         }
2090
2091 #if ENABLE(TOUCH_EVENTS) && ENABLE(IOS_GESTURE_EVENTS)
2092         unsigned numGestureEventListeners = 0;
2093         for (auto& name : eventNames().gestureEventNames())
2094             numGestureEventListeners += eventListeners(name).size();
2095
2096         for (unsigned i = 0; i < numGestureEventListeners; ++i) {
2097             oldDocument.removeTouchEventHandler(*this);
2098             newDocument.addTouchEventHandler(*this);
2099         }
2100 #endif
2101     }
2102
2103 #if !ASSERT_DISABLED || ENABLE(SECURITY_ASSERTIONS)
2104 #if ENABLE(TOUCH_EVENTS) && PLATFORM(IOS_FAMILY)
2105     ASSERT_WITH_SECURITY_IMPLICATION(!oldDocument.touchEventListenersContain(*this));
2106     ASSERT_WITH_SECURITY_IMPLICATION(!oldDocument.touchEventHandlersContain(*this));
2107 #endif
2108 #if ENABLE(TOUCH_EVENTS) && ENABLE(IOS_GESTURE_EVENTS)
2109     ASSERT_WITH_SECURITY_IMPLICATION(!oldDocument.touchEventTargetsContain(*this));
2110 #endif
2111 #endif
2112
2113     if (is<Element>(*this))
2114         downcast<Element>(*this).didMoveToNewDocument(oldDocument, newDocument);
2115 }
2116
2117 static inline bool tryAddEventListener(Node* targetNode, const AtomicString& eventType, Ref<EventListener>&& listener, const EventTarget::AddEventListenerOptions& options)
2118 {
2119     if (!targetNode->EventTarget::addEventListener(eventType, listener.copyRef(), options))
2120         return false;
2121
2122     targetNode->document().addListenerTypeIfNeeded(eventType);
2123     if (eventNames().isWheelEventType(eventType))
2124         targetNode->document().didAddWheelEventHandler(*targetNode);
2125     else if (eventNames().isTouchRelatedEventType(eventType))
2126         targetNode->document().didAddTouchEventHandler(*targetNode);
2127
2128 #if PLATFORM(IOS_FAMILY)
2129     if (targetNode == &targetNode->document() && eventType == eventNames().scrollEvent)
2130         targetNode->document().domWindow()->incrementScrollEventListenersCount();
2131
2132     // FIXME: Would it be sufficient to special-case this code for <body> and <frameset>?
2133     //
2134     // This code was added to address <rdar://problem/5846492> Onorientationchange event not working for document.body.
2135     // Forward this call to addEventListener() to the window since these are window-only events.
2136     if (eventType == eventNames().orientationchangeEvent || eventType == eventNames().resizeEvent)
2137         targetNode->document().domWindow()->addEventListener(eventType, WTFMove(listener), options);
2138
2139 #if ENABLE(TOUCH_EVENTS)
2140     if (eventNames().isTouchRelatedEventType(eventType))
2141         targetNode->document().addTouchEventListener(*targetNode);
2142 #endif
2143 #endif // PLATFORM(IOS_FAMILY)
2144
2145 #if ENABLE(IOS_GESTURE_EVENTS) && ENABLE(TOUCH_EVENTS)
2146     if (eventNames().isGestureEventType(eventType))
2147         targetNode->document().addTouchEventHandler(*targetNode);
2148 #endif
2149
2150     return true;
2151 }
2152
2153 bool Node::addEventListener(const AtomicString& eventType, Ref<EventListener>&& listener, const AddEventListenerOptions& options)
2154 {
2155     return tryAddEventListener(this, eventType, WTFMove(listener), options);
2156 }
2157
2158 static inline bool tryRemoveEventListener(Node* targetNode, const AtomicString& eventType, EventListener& listener, const EventTarget::ListenerOptions& options)
2159 {
2160     if (!targetNode->EventTarget::removeEventListener(eventType, listener, options))
2161         return false;
2162
2163     // FIXME: Notify Document that the listener has vanished. We need to keep track of a number of
2164     // listeners for each type, not just a bool - see https://bugs.webkit.org/show_bug.cgi?id=33861
2165     if (eventNames().isWheelEventType(eventType))
2166         targetNode->document().didRemoveWheelEventHandler(*targetNode);
2167     else if (eventNames().isTouchRelatedEventType(eventType))
2168         targetNode->document().didRemoveTouchEventHandler(*targetNode);
2169
2170 #if PLATFORM(IOS_FAMILY)
2171     if (targetNode == &targetNode->document() && eventType == eventNames().scrollEvent)
2172         targetNode->document().domWindow()->decrementScrollEventListenersCount();
2173
2174     // FIXME: Would it be sufficient to special-case this code for <body> and <frameset>? See <rdar://problem/15647823>.
2175     // This code was added to address <rdar://problem/5846492> Onorientationchange event not working for document.body.
2176     // Forward this call to removeEventListener() to the window since these are window-only events.
2177     if (eventType == eventNames().orientationchangeEvent || eventType == eventNames().resizeEvent)
2178         targetNode->document().domWindow()->removeEventListener(eventType, listener, options);
2179
2180 #if ENABLE(TOUCH_EVENTS)
2181     if (eventNames().isTouchRelatedEventType(eventType))
2182         targetNode->document().removeTouchEventListener(*targetNode);
2183 #endif
2184 #endif // PLATFORM(IOS_FAMILY)
2185
2186 #if ENABLE(IOS_GESTURE_EVENTS) && ENABLE(TOUCH_EVENTS)
2187     if (eventNames().isGestureEventType(eventType))
2188         targetNode->document().removeTouchEventHandler(*targetNode);
2189 #endif
2190
2191     return true;
2192 }
2193
2194 bool Node::removeEventListener(const AtomicString& eventType, EventListener& listener, const ListenerOptions& options)
2195 {
2196     return tryRemoveEventListener(this, eventType, listener, options);
2197 }
2198
2199 typedef HashMap<Node*, std::unique_ptr<EventTargetData>> EventTargetDataMap;
2200
2201 static EventTargetDataMap& eventTargetDataMap()
2202 {
2203     static NeverDestroyed<EventTargetDataMap> map;
2204
2205     return map;
2206 }
2207
2208 static Lock s_eventTargetDataMapLock;
2209
2210 EventTargetData* Node::eventTargetData()
2211 {
2212     return hasEventTargetData() ? eventTargetDataMap().get(this) : nullptr;
2213 }
2214
2215 EventTargetData* Node::eventTargetDataConcurrently()
2216 {
2217     // Not holding the lock when the world is stopped accelerates parallel constraint solving, which
2218     // calls this function from many threads. Parallel constraint solving can happen with the world
2219     // running or stopped, but if we do it with a running world, then we're usually mixing constraint
2220     // solving with other work. Therefore, the most likely time for contention on this lock is when the
2221     // world is stopped. We don't have to hold the lock when the world is stopped, because a stopped world
2222     // means that we will never mutate the event target data map.
2223     JSC::VM* vm = commonVMOrNull();
2224     auto locker = holdLockIf(s_eventTargetDataMapLock, vm && vm->heap.worldIsRunning());
2225     return hasEventTargetData() ? eventTargetDataMap().get(this) : nullptr;
2226 }
2227
2228 EventTargetData& Node::ensureEventTargetData()
2229 {
2230     if (hasEventTargetData())
2231         return *eventTargetDataMap().get(this);
2232
2233     JSC::VM* vm = commonVMOrNull();
2234     RELEASE_ASSERT(!vm || vm->heap.worldIsRunning());
2235
2236     auto locker = holdLock(s_eventTargetDataMapLock);
2237     setHasEventTargetData(true);
2238     return *eventTargetDataMap().add(this, std::make_unique<EventTargetData>()).iterator->value;
2239 }
2240
2241 void Node::clearEventTargetData()
2242 {
2243     JSC::VM* vm = commonVMOrNull();
2244     RELEASE_ASSERT(!vm || vm->heap.worldIsRunning());
2245     auto locker = holdLock(s_eventTargetDataMapLock);
2246     eventTargetDataMap().remove(this);
2247 }
2248
2249 Vector<std::unique_ptr<MutationObserverRegistration>>* Node::mutationObserverRegistry()
2250 {
2251     if (!hasRareData())
2252         return nullptr;
2253     auto* data = rareData()->mutationObserverData();
2254     if (!data)
2255         return nullptr;
2256     return &data->registry;
2257 }
2258
2259 HashSet<MutationObserverRegistration*>* Node::transientMutationObserverRegistry()
2260 {
2261     if (!hasRareData())
2262         return nullptr;
2263     auto* data = rareData()->mutationObserverData();
2264     if (!data)
2265         return nullptr;
2266     return &data->transientRegistry;
2267 }
2268
2269 template<typename Registry> static inline void collectMatchingObserversForMutation(HashMap<Ref<MutationObserver>, MutationRecordDeliveryOptions>& observers, Registry* registry, Node& target, MutationObserver::MutationType type, const QualifiedName* attributeName)
2270 {
2271     if (!registry)
2272         return;
2273
2274     for (auto& registration : *registry) {
2275         if (registration->shouldReceiveMutationFrom(target, type, attributeName)) {
2276             auto deliveryOptions = registration->deliveryOptions();
2277             auto result = observers.add(registration->observer(), deliveryOptions);
2278             if (!result.isNewEntry)
2279                 result.iterator->value |= deliveryOptions;
2280         }
2281     }
2282 }
2283
2284 HashMap<Ref<MutationObserver>, MutationRecordDeliveryOptions> Node::registeredMutationObservers(MutationObserver::MutationType type, const QualifiedName* attributeName)
2285 {
2286     HashMap<Ref<MutationObserver>, MutationRecordDeliveryOptions> result;
2287     ASSERT((type == MutationObserver::Attributes && attributeName) || !attributeName);
2288     collectMatchingObserversForMutation(result, mutationObserverRegistry(), *this, type, attributeName);
2289     collectMatchingObserversForMutation(result, transientMutationObserverRegistry(), *this, type, attributeName);
2290     for (Node* node = parentNode(); node; node = node->parentNode()) {
2291         collectMatchingObserversForMutation(result, node->mutationObserverRegistry(), *this, type, attributeName);
2292         collectMatchingObserversForMutation(result, node->transientMutationObserverRegistry(), *this, type, attributeName);
2293     }
2294     return result;
2295 }
2296
2297 void Node::registerMutationObserver(MutationObserver& observer, MutationObserverOptions options, const HashSet<AtomicString>& attributeFilter)
2298 {
2299     MutationObserverRegistration* registration = nullptr;
2300     auto& registry = ensureRareData().ensureMutationObserverData().registry;
2301
2302     for (auto& candidateRegistration : registry) {
2303         if (&candidateRegistration->observer() == &observer) {
2304             registration = candidateRegistration.get();
2305             registration->resetObservation(options, attributeFilter);
2306         }
2307     }
2308
2309     if (!registration) {
2310         registry.append(std::make_unique<MutationObserverRegistration>(observer, *this, options, attributeFilter));
2311         registration = registry.last().get();
2312     }
2313
2314     document().addMutationObserverTypes(registration->mutationTypes());
2315 }
2316
2317 void Node::unregisterMutationObserver(MutationObserverRegistration& registration)
2318 {
2319     auto* registry = mutationObserverRegistry();
2320     ASSERT(registry);
2321     if (!registry)
2322         return;
2323
2324     registry->removeFirstMatching([&registration] (auto& current) {
2325         return current.get() == &registration;
2326     });
2327 }
2328
2329 void Node::registerTransientMutationObserver(MutationObserverRegistration& registration)
2330 {
2331     ensureRareData().ensureMutationObserverData().transientRegistry.add(&registration);
2332 }
2333
2334 void Node::unregisterTransientMutationObserver(MutationObserverRegistration& registration)
2335 {
2336     auto* transientRegistry = transientMutationObserverRegistry();
2337     ASSERT(transientRegistry);
2338     if (!transientRegistry)
2339         return;
2340
2341     ASSERT(transientRegistry->contains(&registration));
2342     transientRegistry->remove(&registration);
2343 }
2344
2345 void Node::notifyMutationObserversNodeWillDetach()
2346 {
2347     if (!document().hasMutationObservers())
2348         return;
2349
2350     for (Node* node = parentNode(); node; node = node->parentNode()) {
2351         if (auto* registry = node->mutationObserverRegistry()) {
2352             for (auto& registration : *registry)
2353                 registration->observedSubtreeNodeWillDetach(*this);
2354         }
2355         if (auto* transientRegistry = node->transientMutationObserverRegistry()) {
2356             for (auto* registration : *transientRegistry)
2357                 registration->observedSubtreeNodeWillDetach(*this);
2358         }
2359     }
2360 }
2361
2362 void Node::handleLocalEvents(Event& event, EventInvokePhase phase)
2363 {
2364     if (!hasEventTargetData())
2365         return;
2366
2367     // FIXME: Should we deliver wheel events to disabled form controls or not?
2368     if (is<Element>(*this) && downcast<Element>(*this).isDisabledFormControl() && event.isMouseEvent() && !event.isWheelEvent())
2369         return;
2370
2371     fireEventListeners(event, phase);
2372 }
2373
2374 void Node::dispatchScopedEvent(Event& event)
2375 {
2376     EventDispatcher::dispatchScopedEvent(*this, event);
2377 }
2378
2379 void Node::dispatchEvent(Event& event)
2380 {
2381     EventDispatcher::dispatchEvent(*this, event);
2382 }
2383
2384 void Node::dispatchSubtreeModifiedEvent()
2385 {
2386     if (isInShadowTree())
2387         return;
2388
2389     ASSERT_WITH_SECURITY_IMPLICATION(ScriptDisallowedScope::InMainThread::isEventDispatchAllowedInSubtree(*this));
2390
2391     if (!document().hasListenerType(Document::DOMSUBTREEMODIFIED_LISTENER))
2392         return;
2393     const AtomicString& subtreeModifiedEventName = eventNames().DOMSubtreeModifiedEvent;
2394     if (!parentNode() && !hasEventListeners(subtreeModifiedEventName))
2395         return;
2396
2397     dispatchScopedEvent(MutationEvent::create(subtreeModifiedEventName, Event::CanBubble::Yes));
2398 }
2399
2400 void Node::dispatchDOMActivateEvent(Event& underlyingClickEvent)
2401 {
2402     ASSERT_WITH_SECURITY_IMPLICATION(ScriptDisallowedScope::InMainThread::isScriptAllowed());
2403     int detail = is<UIEvent>(underlyingClickEvent) ? downcast<UIEvent>(underlyingClickEvent).detail() : 0;
2404     auto event = UIEvent::create(eventNames().DOMActivateEvent, Event::CanBubble::Yes, Event::IsCancelable::Yes, Event::IsComposed::Yes, document().windowProxy(), detail);
2405     event->setUnderlyingEvent(&underlyingClickEvent);
2406     dispatchScopedEvent(event);
2407     if (event->defaultHandled())
2408         underlyingClickEvent.setDefaultHandled();
2409 }
2410
2411 bool Node::dispatchBeforeLoadEvent(const String& sourceURL)
2412 {
2413     if (!document().hasListenerType(Document::BEFORELOAD_LISTENER))
2414         return true;
2415
2416     Ref<Node> protectedThis(*this);
2417     auto event = BeforeLoadEvent::create(sourceURL);
2418     dispatchEvent(event);
2419     return !event->defaultPrevented();
2420 }
2421
2422 void Node::dispatchInputEvent()
2423 {
2424     dispatchScopedEvent(Event::create(eventNames().inputEvent, Event::CanBubble::Yes, Event::IsCancelable::No, Event::IsComposed::Yes));
2425 }
2426
2427 void Node::defaultEventHandler(Event& event)
2428 {
2429     if (event.target() != this)
2430         return;
2431     const AtomicString& eventType = event.type();
2432     if (eventType == eventNames().keydownEvent || eventType == eventNames().keypressEvent) {
2433         if (is<KeyboardEvent>(event)) {
2434             if (Frame* frame = document().frame())
2435                 frame->eventHandler().defaultKeyboardEventHandler(downcast<KeyboardEvent>(event));
2436         }
2437     } else if (eventType == eventNames().clickEvent) {
2438         dispatchDOMActivateEvent(event);
2439 #if ENABLE(CONTEXT_MENUS)
2440     } else if (eventType == eventNames().contextmenuEvent) {
2441         if (Frame* frame = document().frame())
2442             if (Page* page = frame->page())
2443                 page->contextMenuController().handleContextMenuEvent(event);
2444 #endif
2445     } else if (eventType == eventNames().textInputEvent) {
2446         if (is<TextEvent>(event)) {
2447             if (Frame* frame = document().frame())
2448                 frame->eventHandler().defaultTextInputEventHandler(downcast<TextEvent>(event));
2449         }
2450 #if ENABLE(PAN_SCROLLING)
2451     } else if (eventType == eventNames().mousedownEvent && is<MouseEvent>(event)) {
2452         if (downcast<MouseEvent>(event).button() == MiddleButton) {
2453             if (enclosingLinkEventParentOrSelf())
2454                 return;
2455
2456             RenderObject* renderer = this->renderer();
2457             while (renderer && (!is<RenderBox>(*renderer) || !downcast<RenderBox>(*renderer).canBeScrolledAndHasScrollableArea()))
2458                 renderer = renderer->parent();
2459
2460             if (renderer) {
2461                 if (Frame* frame = document().frame())
2462                     frame->eventHandler().startPanScrolling(downcast<RenderBox>(*renderer));
2463             }
2464         }
2465 #endif
2466     } else if (eventNames().isWheelEventType(eventType) && is<WheelEvent>(event)) {
2467         // If we don't have a renderer, send the wheel event to the first node we find with a renderer.
2468         // This is needed for <option> and <optgroup> elements so that <select>s get a wheel scroll.
2469         Node* startNode = this;
2470         while (startNode && !startNode->renderer())
2471             startNode = startNode->parentOrShadowHostNode();
2472         
2473         if (startNode && startNode->renderer())
2474             if (Frame* frame = document().frame())
2475                 frame->eventHandler().defaultWheelEventHandler(startNode, downcast<WheelEvent>(event));
2476 #if ENABLE(TOUCH_EVENTS) && PLATFORM(IOS_FAMILY)
2477     } else if (is<TouchEvent>(event) && eventNames().isTouchRelatedEventType(eventType)) {
2478         RenderObject* renderer = this->renderer();
2479         while (renderer && (!is<RenderBox>(*renderer) || !downcast<RenderBox>(*renderer).canBeScrolledAndHasScrollableArea()))
2480             renderer = renderer->parent();
2481
2482         if (renderer && renderer->node()) {
2483             if (Frame* frame = document().frame())
2484                 frame->eventHandler().defaultTouchEventHandler(*renderer->node(), downcast<TouchEvent>(event));
2485         }
2486 #endif
2487     }
2488 }
2489
2490 bool Node::willRespondToMouseMoveEvents()
2491 {
2492     // FIXME: Why is the iOS code path different from the non-iOS code path?
2493 #if !PLATFORM(IOS_FAMILY)
2494     if (!is<Element>(*this))
2495         return false;
2496     if (downcast<Element>(*this).isDisabledFormControl())
2497         return false;
2498 #endif
2499     return hasEventListeners(eventNames().mousemoveEvent) || hasEventListeners(eventNames().mouseoverEvent) || hasEventListeners(eventNames().mouseoutEvent);
2500 }
2501
2502 bool Node::willRespondToMouseClickEvents()
2503 {
2504     // FIXME: Why is the iOS code path different from the non-iOS code path?
2505 #if PLATFORM(IOS_FAMILY)
2506     return isContentEditable() || hasEventListeners(eventNames().mouseupEvent) || hasEventListeners(eventNames().mousedownEvent) || hasEventListeners(eventNames().clickEvent);
2507 #else
2508     if (!is<Element>(*this))
2509         return false;
2510     if (downcast<Element>(*this).isDisabledFormControl())
2511         return false;
2512     return computeEditability(UserSelectAllIsAlwaysNonEditable, ShouldUpdateStyle::Update) != Editability::ReadOnly
2513         || hasEventListeners(eventNames().mouseupEvent) || hasEventListeners(eventNames().mousedownEvent) || hasEventListeners(eventNames().clickEvent) || hasEventListeners(eventNames().DOMActivateEvent);
2514 #endif
2515 }
2516
2517 bool Node::willRespondToMouseWheelEvents()
2518 {
2519     return hasEventListeners(eventNames().mousewheelEvent);
2520 }
2521
2522 // It's important not to inline removedLastRef, because we don't want to inline the code to
2523 // delete a Node at each deref call site.
2524 void Node::removedLastRef()
2525 {
2526     // An explicit check for Document here is better than a virtual function since it is
2527     // faster for non-Document nodes, and because the call to removedLastRef that is inlined
2528     // at all deref call sites is smaller if it's a non-virtual function.
2529     if (is<Document>(*this)) {
2530         downcast<Document>(*this).removedLastRef();
2531         return;
2532     }
2533
2534 #ifndef NDEBUG
2535     m_deletionHasBegun = true;
2536 #endif
2537     m_refCount = 1; // Avoid double destruction through use of RefPtr<T>. (This is a security mitigation in case of programmer error. It will ASSERT in debug builds.)
2538     delete this;
2539 }
2540
2541 void Node::textRects(Vector<IntRect>& rects) const
2542 {
2543     auto range = Range::create(document());
2544     range->selectNodeContents(const_cast<Node&>(*this));
2545     range->absoluteTextRects(rects);
2546 }
2547
2548 unsigned Node::connectedSubframeCount() const
2549 {
2550     return hasRareData() ? rareData()->connectedSubframeCount() : 0;
2551 }
2552
2553 void Node::incrementConnectedSubframeCount(unsigned amount)
2554 {
2555     ASSERT(isContainerNode());
2556     ensureRareData().incrementConnectedSubframeCount(amount);
2557 }
2558
2559 void Node::decrementConnectedSubframeCount(unsigned amount)
2560 {
2561     rareData()->decrementConnectedSubframeCount(amount);
2562 }
2563
2564 void Node::updateAncestorConnectedSubframeCountForRemoval() const
2565 {
2566     unsigned count = connectedSubframeCount();
2567
2568     if (!count)
2569         return;
2570
2571     for (Node* node = parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode())
2572         node->decrementConnectedSubframeCount(count);
2573 }
2574
2575 void Node::updateAncestorConnectedSubframeCountForInsertion() const
2576 {
2577     unsigned count = connectedSubframeCount();
2578
2579     if (!count)
2580         return;
2581
2582     for (Node* node = parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode())
2583         node->incrementConnectedSubframeCount(count);
2584 }
2585
2586 bool Node::inRenderedDocument() const
2587 {
2588     return isConnected() && document().hasLivingRenderTree();
2589 }
2590
2591 void* Node::opaqueRootSlow() const
2592 {
2593     const Node* node = this;
2594     for (;;) {
2595         const Node* nextNode = node->parentOrShadowHostNode();
2596         if (!nextNode)
2597             break;
2598         node = nextNode;
2599     }
2600     return const_cast<void*>(static_cast<const void*>(node));
2601 }
2602
2603 } // namespace WebCore
2604
2605 #if ENABLE(TREE_DEBUGGING)
2606
2607 void showTree(const WebCore::Node* node)
2608 {
2609     if (node)
2610         node->showTreeForThis();
2611 }
2612
2613 void showNodePath(const WebCore::Node* node)
2614 {
2615     if (node)
2616         node->showNodePathForThis();
2617 }
2618
2619 #endif // ENABLE(TREE_DEBUGGING)