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, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
6 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public License
19 * along with this library; see the file COPYING.LIB. If not, write to
20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
28 #include "EventTarget.h"
30 #include "LayoutRect.h"
31 #include "MutationObserver.h"
32 #include "RenderStyleConstants.h"
33 #include "ScriptWrappable.h"
34 #include "TreeScope.h"
35 #include <wtf/Forward.h>
36 #include <wtf/ListHashSet.h>
37 #include <wtf/MainThread.h>
38 #include <wtf/TypeCasts.h>
40 // This needs to be here because Document.h also depends on it.
41 #define DUMP_NODE_STATISTICS 0
46 class ClassCollection;
48 class DOMSettableTokenList;
55 class HTMLInputElement;
56 class HTMLQualifiedName;
57 class HTMLSlotElement;
60 class MathMLQualifiedName;
65 class NodeListsNodeData;
70 class RegisteredEventListener;
72 class RenderBoxModelObject;
75 class SVGQualifiedName;
83 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
87 typedef int ExceptionCode;
89 const int nodeStyleChangeShift = 14;
91 // SyntheticStyleChange means that we need to go through the entire style change logic even though
92 // no style property has actually changed. It is used to restructure the tree when, for instance,
93 // RenderLayers are created or destroyed due to animation changes.
94 enum StyleChangeType {
96 InlineStyleChange = 1 << nodeStyleChangeShift,
97 FullStyleChange = 2 << nodeStyleChangeShift,
98 SyntheticStyleChange = 3 << nodeStyleChangeShift,
99 ReconstructRenderTree = 4 << nodeStyleChangeShift,
102 class NodeRareDataBase {
104 RenderObject* renderer() const { return m_renderer; }
105 void setRenderer(RenderObject* renderer) { m_renderer = renderer; }
108 NodeRareDataBase(RenderObject* renderer)
109 : m_renderer(renderer)
113 RenderObject* m_renderer;
116 class Node : public EventTarget, public ScriptWrappable {
117 WTF_MAKE_FAST_ALLOCATED;
119 friend class Document;
120 friend class TreeScope;
121 friend class TreeScopeAdopter;
127 CDATA_SECTION_NODE = 4,
128 PROCESSING_INSTRUCTION_NODE = 7,
131 DOCUMENT_TYPE_NODE = 10,
132 DOCUMENT_FRAGMENT_NODE = 11,
134 enum DeprecatedNodeType {
135 ENTITY_REFERENCE_NODE = 5,
139 enum DocumentPosition {
140 DOCUMENT_POSITION_EQUIVALENT = 0x00,
141 DOCUMENT_POSITION_DISCONNECTED = 0x01,
142 DOCUMENT_POSITION_PRECEDING = 0x02,
143 DOCUMENT_POSITION_FOLLOWING = 0x04,
144 DOCUMENT_POSITION_CONTAINS = 0x08,
145 DOCUMENT_POSITION_CONTAINED_BY = 0x10,
146 DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20,
149 static bool isSupported(const String& feature, const String& version);
151 WEBCORE_EXPORT static void startIgnoringLeaks();
152 WEBCORE_EXPORT static void stopIgnoringLeaks();
154 static void dumpStatistics();
157 void willBeDeletedFrom(Document&);
159 // DOM methods & attributes for Node
161 bool hasTagName(const HTMLQualifiedName&) const;
162 bool hasTagName(const MathMLQualifiedName&) const;
163 bool hasTagName(const SVGQualifiedName&) const;
164 virtual String nodeName() const = 0;
165 virtual String nodeValue() const;
166 virtual void setNodeValue(const String&, ExceptionCode&);
167 virtual NodeType nodeType() const = 0;
168 ContainerNode* parentNode() const;
169 static ptrdiff_t parentNodeMemoryOffset() { return OBJECT_OFFSETOF(Node, m_parentNode); }
170 Element* parentElement() const;
171 Node* previousSibling() const { return m_previous; }
172 static ptrdiff_t previousSiblingMemoryOffset() { return OBJECT_OFFSETOF(Node, m_previous); }
173 Node* nextSibling() const { return m_next; }
174 static ptrdiff_t nextSiblingMemoryOffset() { return OBJECT_OFFSETOF(Node, m_next); }
175 RefPtr<NodeList> childNodes();
176 Node* firstChild() const;
177 Node* lastChild() const;
178 bool hasAttributes() const;
179 NamedNodeMap* attributes() const;
180 Node* pseudoAwareNextSibling() const;
181 Node* pseudoAwarePreviousSibling() const;
182 Node* pseudoAwareFirstChild() const;
183 Node* pseudoAwareLastChild() const;
187 void getSubresourceURLs(ListHashSet<URL>&) const;
189 // These should all actually return a node, but this is only important for language bindings,
190 // which will already know and hold a ref on the right node to return. Returning bool allows
191 // these methods to be more efficient since they don't need to return a ref
192 WEBCORE_EXPORT bool insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionCode&);
193 bool replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionCode&);
194 WEBCORE_EXPORT bool removeChild(Node* child, ExceptionCode&);
195 WEBCORE_EXPORT bool appendChild(PassRefPtr<Node> newChild, ExceptionCode&);
197 bool hasChildNodes() const { return firstChild(); }
199 enum class CloningOperation {
201 SelfWithTemplateContent,
204 virtual Ref<Node> cloneNodeInternal(Document&, CloningOperation) = 0;
205 Ref<Node> cloneNode(bool deep) { return cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf); }
207 virtual const AtomicString& localName() const;
208 virtual const AtomicString& namespaceURI() const;
209 virtual const AtomicString& prefix() const;
210 virtual void setPrefix(const AtomicString&, ExceptionCode&);
213 bool isSameNode(Node* other) const { return this == other; }
214 bool isEqualNode(Node*) const;
215 bool isDefaultNamespace(const AtomicString& namespaceURI) const;
216 String lookupPrefix(const AtomicString& namespaceURI) const;
217 String lookupNamespaceURI(const String& prefix) const;
218 String lookupNamespacePrefix(const AtomicString& namespaceURI, const Element* originalElement) const;
220 WEBCORE_EXPORT String textContent(bool convertBRsToNewlines = false) const;
221 WEBCORE_EXPORT void setTextContent(const String&, ExceptionCode&);
223 Node* lastDescendant() const;
224 Node* firstDescendant() const;
226 // From the NonDocumentTypeChildNode - https://dom.spec.whatwg.org/#nondocumenttypechildnode
227 Element* previousElementSibling() const;
228 Element* nextElementSibling() const;
230 // From the ChildNode - https://dom.spec.whatwg.org/#childnode
231 void before(Vector<NodeOrString>&&, ExceptionCode&);
232 void after(Vector<NodeOrString>&&, ExceptionCode&);
233 void replaceWith(Vector<NodeOrString>&&, ExceptionCode&);
234 WEBCORE_EXPORT void remove(ExceptionCode&);
236 // Other methods (not part of DOM)
238 bool isElementNode() const { return getFlag(IsElementFlag); }
239 bool isContainerNode() const { return getFlag(IsContainerFlag); }
240 bool isTextNode() const { return getFlag(IsTextFlag); }
241 bool isHTMLElement() const { return getFlag(IsHTMLFlag); }
242 bool isSVGElement() const { return getFlag(IsSVGFlag); }
243 bool isMathMLElement() const { return getFlag(IsMathMLFlag); }
245 bool isPseudoElement() const { return pseudoId() != NOPSEUDO; }
246 bool isBeforePseudoElement() const { return pseudoId() == BEFORE; }
247 bool isAfterPseudoElement() const { return pseudoId() == AFTER; }
248 PseudoId pseudoId() const { return (isElementNode() && hasCustomStyleResolveCallbacks()) ? customPseudoId() : NOPSEUDO; }
250 virtual bool isMediaControlElement() const { return false; }
251 virtual bool isMediaControls() const { return false; }
252 #if ENABLE(VIDEO_TRACK)
253 virtual bool isWebVTTElement() const { return false; }
255 bool isStyledElement() const { return getFlag(IsStyledElementFlag); }
256 virtual bool isAttributeNode() const { return false; }
257 virtual bool isCharacterDataNode() const { return false; }
258 virtual bool isFrameOwnerElement() const { return false; }
259 virtual bool isPluginElement() const { return false; }
260 #if ENABLE(SERVICE_CONTROLS)
261 virtual bool isImageControlsRootElement() const { return false; }
262 virtual bool isImageControlsButtonElement() const { return false; }
265 bool isDocumentNode() const;
266 bool isTreeScope() const;
267 bool isDocumentFragment() const { return getFlag(IsDocumentFragmentFlag); }
268 bool isShadowRoot() const { return isDocumentFragment() && isTreeScope(); }
270 bool isNamedFlowContentNode() const { return getFlag(IsNamedFlowContentNodeFlag); }
271 bool hasCustomStyleResolveCallbacks() const { return getFlag(HasCustomStyleResolveCallbacksFlag); }
273 bool hasSyntheticAttrChildNodes() const { return getFlag(HasSyntheticAttrChildNodesFlag); }
274 void setHasSyntheticAttrChildNodes(bool flag) { setFlag(flag, HasSyntheticAttrChildNodesFlag); }
276 // If this node is in a shadow tree, returns its shadow host. Otherwise, returns null.
277 WEBCORE_EXPORT Element* shadowHost() const;
278 // If this node is in a shadow tree, returns its shadow host. Otherwise, returns this.
279 // Deprecated. Should use shadowHost() and check the return value.
280 WEBCORE_EXPORT Node* deprecatedShadowAncestorNode() const;
281 ShadowRoot* containingShadowRoot() const;
282 ShadowRoot* shadowRoot() const;
284 #if ENABLE(SHADOW_DOM)
285 HTMLSlotElement* assignedSlot() const;
288 // Returns null, a child of ShadowRoot, or a legacy shadow root.
289 Node* nonBoundaryShadowTreeRootNode();
291 // Node's parent or shadow tree host.
292 ContainerNode* parentOrShadowHostNode() const;
293 Element* parentOrShadowHostElement() const;
294 void setParentNode(ContainerNode*);
295 Node* highestAncestor() const;
297 // Use when it's guaranteed to that shadowHost is null.
298 ContainerNode* parentNodeGuaranteedHostFree() const;
299 // Returns the parent node, but null if the parent node is a ShadowRoot.
300 ContainerNode* nonShadowBoundaryParentNode() const;
302 bool selfOrAncestorHasDirAutoAttribute() const { return getFlag(SelfOrAncestorHasDirAutoFlag); }
303 void setSelfOrAncestorHasDirAutoAttribute(bool flag) { setFlag(flag, SelfOrAncestorHasDirAutoFlag); }
305 // Returns the enclosing event parent Element (or self) that, when clicked, would trigger a navigation.
306 Element* enclosingLinkEventParentOrSelf();
308 // These low-level calls give the caller responsibility for maintaining the integrity of the tree.
309 void setPreviousSibling(Node* previous) { m_previous = previous; }
310 void setNextSibling(Node* next) { m_next = next; }
312 virtual bool canContainRangeEndPoint() const { return false; }
314 bool isRootEditableElement() const;
315 WEBCORE_EXPORT Element* rootEditableElement() const;
317 // Called by the parser when this element's close tag is reached,
318 // signaling that all child tags have been parsed and added.
319 // This is needed for <applet> and <object> elements, which can't lay themselves out
320 // until they know all of their nested <param>s. [Radar 3603191, 4040848].
321 // Also used for script elements and some SVG elements for similar purposes,
322 // but making parsing a special case in this respect should be avoided if possible.
323 virtual void finishParsingChildren() { }
324 virtual void beginParsingChildren() { }
326 // For <link> and <style> elements.
327 virtual bool sheetLoaded() { return true; }
328 virtual void notifyLoadedSheetAndAllCriticalSubresources(bool /* error loading subresource */) { }
329 virtual void startLoadingDynamicSheet() { ASSERT_NOT_REACHED(); }
331 bool isUserActionElement() const { return getFlag(IsUserActionElement); }
332 void setUserActionElement(bool flag) { setFlag(flag, IsUserActionElement); }
334 bool inRenderedDocument() const;
335 bool needsStyleRecalc() const { return styleChangeType() != NoStyleChange; }
336 StyleChangeType styleChangeType() const { return static_cast<StyleChangeType>(m_nodeFlags & StyleChangeMask); }
337 bool childNeedsStyleRecalc() const { return getFlag(ChildNeedsStyleRecalcFlag); }
338 bool styleIsAffectedByPreviousSibling() const { return getFlag(StyleIsAffectedByPreviousSibling); }
339 bool isEditingText() const { return getFlag(IsEditingTextFlag); }
341 void setChildNeedsStyleRecalc() { setFlag(ChildNeedsStyleRecalcFlag); }
342 void clearChildNeedsStyleRecalc() { m_nodeFlags &= ~(ChildNeedsStyleRecalcFlag | DirectChildNeedsStyleRecalcFlag); }
344 WEBCORE_EXPORT void setNeedsStyleRecalc(StyleChangeType = FullStyleChange);
345 void clearNeedsStyleRecalc() { m_nodeFlags &= ~StyleChangeMask; }
347 bool isLink() const { return getFlag(IsLinkFlag); }
348 void setIsLink(bool flag) { setFlag(flag, IsLinkFlag); }
350 void setIsNamedFlowContentNode() { setFlag(IsNamedFlowContentNodeFlag); }
351 void clearIsNamedFlowContentNode() { clearFlag(IsNamedFlowContentNodeFlag); }
353 bool hasEventTargetData() const { return getFlag(HasEventTargetDataFlag); }
354 void setHasEventTargetData(bool flag) { setFlag(flag, HasEventTargetDataFlag); }
356 enum UserSelectAllTreatment {
357 UserSelectAllDoesNotAffectEditability,
358 UserSelectAllIsAlwaysNonEditable
360 WEBCORE_EXPORT bool isContentEditable();
361 bool isContentRichlyEditable();
363 WEBCORE_EXPORT void inspect();
365 bool hasEditableStyle(UserSelectAllTreatment treatment = UserSelectAllIsAlwaysNonEditable) const
367 return computeEditability(treatment, ShouldUpdateStyle::DoNotUpdate) != Editability::ReadOnly;
369 // FIXME: Replace every use of this function by helpers in htmlediting.h
370 bool hasRichlyEditableStyle() const
372 return computeEditability(UserSelectAllIsAlwaysNonEditable, ShouldUpdateStyle::DoNotUpdate) == Editability::CanEditRichly;
375 enum class Editability { ReadOnly, CanEditPlainText, CanEditRichly };
376 enum class ShouldUpdateStyle { Update, DoNotUpdate };
377 WEBCORE_EXPORT Editability computeEditability(UserSelectAllTreatment, ShouldUpdateStyle) const;
379 WEBCORE_EXPORT LayoutRect renderRect(bool* isReplaced);
380 IntRect pixelSnappedRenderRect(bool* isReplaced) { return snappedIntRect(renderRect(isReplaced)); }
382 WEBCORE_EXPORT unsigned computeNodeIndex() const;
384 // Returns the DOM ownerDocument attribute. This method never returns null, except in the case
385 // of a Document node.
386 WEBCORE_EXPORT Document* ownerDocument() const;
388 // Returns the document associated with this node.
389 // A Document node returns itself.
390 Document& document() const
393 return treeScope().documentScope();
396 TreeScope& treeScope() const
401 static ptrdiff_t treeScopeMemoryOffset() { return OBJECT_OFFSETOF(Node, m_treeScope); }
403 // Returns true if this node is associated with a document and is in its associated document's
404 // node tree, false otherwise.
405 bool inDocument() const
407 return getFlag(InDocumentFlag);
409 bool isInUserAgentShadowTree() const;
410 bool isInShadowTree() const { return getFlag(IsInShadowTreeFlag); }
411 bool isInTreeScope() const { return getFlag(static_cast<NodeFlags>(InDocumentFlag | IsInShadowTreeFlag)); }
413 bool isDocumentTypeNode() const { return nodeType() == DOCUMENT_TYPE_NODE; }
414 virtual bool childTypeAllowed(NodeType) const { return false; }
415 unsigned countChildNodes() const;
416 Node* traverseToChildAt(unsigned) const;
418 void checkSetPrefix(const AtomicString& prefix, ExceptionCode&);
420 WEBCORE_EXPORT bool isDescendantOf(const Node*) const;
421 bool isDescendantOrShadowDescendantOf(const Node*) const;
422 bool contains(const Node*) const;
423 bool containsIncludingShadowDOM(const Node*) const;
424 bool containsIncludingHostElements(const Node*) const;
426 // Used to determine whether range offsets use characters or node indices.
427 virtual bool offsetInCharacters() const;
428 // Number of DOM 16-bit units contained in node. Note that rendered text length can be different - e.g. because of
429 // css-transform:capitalize breaking up precomposed characters and ligatures.
430 virtual int maxCharacterOffset() const;
432 // Whether or not a selection can be started in this object
433 virtual bool canStartSelection() const;
435 virtual bool shouldSelectOnMouseDown() { return false; }
437 // Getting points into and out of screen space
438 FloatPoint convertToPage(const FloatPoint&) const;
439 FloatPoint convertFromPage(const FloatPoint&) const;
441 // -----------------------------------------------------------------------------
442 // Integration with rendering tree
444 // As renderer() includes a branch you should avoid calling it repeatedly in hot code paths.
445 RenderObject* renderer() const { return hasRareData() ? m_data.m_rareData->renderer() : m_data.m_renderer; };
446 void setRenderer(RenderObject* renderer)
449 m_data.m_rareData->setRenderer(renderer);
451 m_data.m_renderer = renderer;
454 // Use these two methods with caution.
455 WEBCORE_EXPORT RenderBox* renderBox() const;
456 RenderBoxModelObject* renderBoxModelObject() const;
458 // Wrapper for nodes that don't have a renderer, but still cache the style (like HTMLOptionElement).
459 RenderStyle* renderStyle() const;
461 virtual RenderStyle* computedStyle(PseudoId pseudoElementSpecifier = NOPSEUDO);
463 // -----------------------------------------------------------------------------
464 // Notification of document structure changes (see ContainerNode.h for more notification methods)
466 // At first, WebKit notifies the node that it has been inserted into the document. This is called during document parsing, and also
467 // when a node is added through the DOM methods insertBefore(), appendChild() or replaceChild(). The call happens _after_ the node has been added to the tree.
468 // This is similar to the DOMNodeInsertedIntoDocument DOM event, but does not require the overhead of event
471 // WebKit notifies this callback regardless if the subtree of the node is a document tree or a floating subtree.
472 // Implementation can determine the type of subtree by seeing insertionPoint->inDocument().
473 // For a performance reason, notifications are delivered only to ContainerNode subclasses if the insertionPoint is out of document.
475 // There is another callback named finishedInsertingSubtree(), which is called after all descendants are notified.
476 // Only a few subclasses actually need this. To utilize this, the node should return InsertionShouldCallFinishedInsertingSubtree
477 // from insrtedInto().
479 enum InsertionNotificationRequest {
481 InsertionShouldCallFinishedInsertingSubtree
484 virtual InsertionNotificationRequest insertedInto(ContainerNode& insertionPoint);
485 virtual void finishedInsertingSubtree() { }
487 // Notifies the node that it is no longer part of the tree.
489 // This is a dual of insertedInto(), and is similar to the DOMNodeRemovedFromDocument DOM event, but does not require the overhead of event
490 // dispatching, and is called _after_ the node is removed from the tree.
492 virtual void removedFrom(ContainerNode& insertionPoint);
494 #if ENABLE(TREE_DEBUGGING)
495 virtual void formatForDebugger(char* buffer, unsigned length) const;
497 void showNode(const char* prefix = "") const;
498 void showTreeForThis() const;
499 void showNodePathForThis() const;
500 void showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2 = nullptr, const char* markedLabel2 = nullptr) const;
501 void showTreeForThisAcrossFrame() const;
502 #endif // ENABLE(TREE_DEBUGGING)
504 void invalidateNodeListAndCollectionCachesInAncestors(const QualifiedName* attrName = nullptr, Element* attributeOwnerElement = nullptr);
505 NodeListsNodeData* nodeLists();
506 void clearNodeLists();
508 virtual bool willRespondToMouseMoveEvents();
509 virtual bool willRespondToMouseClickEvents();
510 virtual bool willRespondToMouseWheelEvents();
512 WEBCORE_EXPORT unsigned short compareDocumentPosition(Node*);
514 virtual Node* toNode() override;
516 virtual EventTargetInterface eventTargetInterface() const override;
517 virtual ScriptExecutionContext* scriptExecutionContext() const override final; // Implemented in Document.h
519 virtual bool addEventListener(const AtomicString& eventType, RefPtr<EventListener>&&, bool useCapture) override;
520 virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture) override;
522 using EventTarget::dispatchEvent;
523 virtual bool dispatchEvent(PassRefPtr<Event>) override;
525 void dispatchScopedEvent(PassRefPtr<Event>);
527 virtual void handleLocalEvents(Event&);
529 void dispatchSubtreeModifiedEvent();
530 bool dispatchDOMActivateEvent(int detail, PassRefPtr<Event> underlyingEvent);
532 #if ENABLE(TOUCH_EVENTS)
533 virtual bool allowsDoubleTapGesture() const { return true; }
536 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
537 bool dispatchTouchEvent(PassRefPtr<TouchEvent>);
540 bool dispatchUIRequestEvent(PassRefPtr<UIRequestEvent>);
543 bool dispatchBeforeLoadEvent(const String& sourceURL);
545 virtual void dispatchInputEvent();
547 // Perform the default action for an event.
548 virtual void defaultEventHandler(Event*);
552 bool hasOneRef() const;
553 int refCount() const;
556 bool m_deletionHasBegun { false };
557 bool m_inRemovedLastRefFunction { false };
558 bool m_adoptionIsRequired { true };
561 virtual EventTargetData* eventTargetData() override final;
562 virtual EventTargetData& ensureEventTargetData() override final;
564 void getRegisteredMutationObserversOfType(HashMap<MutationObserver*, MutationRecordDeliveryOptions>&, MutationObserver::MutationType, const QualifiedName* attributeName);
565 void registerMutationObserver(MutationObserver*, MutationObserverOptions, const HashSet<AtomicString>& attributeFilter);
566 void unregisterMutationObserver(MutationObserverRegistration*);
567 void registerTransientMutationObserver(MutationObserverRegistration*);
568 void unregisterTransientMutationObserver(MutationObserverRegistration*);
569 void notifyMutationObserversNodeWillDetach();
571 WEBCORE_EXPORT void textRects(Vector<IntRect>&) const;
573 unsigned connectedSubframeCount() const;
574 void incrementConnectedSubframeCount(unsigned amount = 1);
575 void decrementConnectedSubframeCount(unsigned amount = 1);
576 void updateAncestorConnectedSubframeCountForRemoval() const;
577 void updateAncestorConnectedSubframeCountForInsertion() const;
579 #if ENABLE(CSS_SELECTOR_JIT)
580 static ptrdiff_t nodeFlagsMemoryOffset() { return OBJECT_OFFSETOF(Node, m_nodeFlags); }
581 static ptrdiff_t rareDataMemoryOffset() { return OBJECT_OFFSETOF(Node, m_data.m_rareData); }
582 static int32_t flagIsText() { return IsTextFlag; }
583 static int32_t flagIsElement() { return IsElementFlag; }
584 static int32_t flagIsHTML() { return IsHTMLFlag; }
585 static int32_t flagIsLink() { return IsLinkFlag; }
586 static int32_t flagHasRareData() { return HasRareDataFlag; }
587 static int32_t flagIsParsingChildrenFinished() { return IsParsingChildrenFinishedFlag; }
588 static int32_t flagChildrenAffectedByFirstChildRulesFlag() { return ChildrenAffectedByFirstChildRulesFlag; }
589 static int32_t flagChildrenAffectedByLastChildRulesFlag() { return ChildrenAffectedByLastChildRulesFlag; }
591 static int32_t flagAffectsNextSiblingElementStyle() { return AffectsNextSiblingElementStyle; }
592 static int32_t flagStyleIsAffectedByPreviousSibling() { return StyleIsAffectedByPreviousSibling; }
593 #endif // ENABLE(CSS_SELECTOR_JIT)
598 IsContainerFlag = 1 << 1,
599 IsElementFlag = 1 << 2,
600 IsStyledElementFlag = 1 << 3,
603 ChildNeedsStyleRecalcFlag = 1 << 7,
604 InDocumentFlag = 1 << 8,
606 IsUserActionElement = 1 << 10,
607 HasRareDataFlag = 1 << 11,
608 IsDocumentFragmentFlag = 1 << 12,
610 // These bits are used by derived classes, pulled up here so they can
611 // be stored in the same memory word as the Node bits above.
612 IsParsingChildrenFinishedFlag = 1 << 13, // Element
614 StyleChangeMask = 1 << nodeStyleChangeShift | 1 << (nodeStyleChangeShift + 1) | 1 << (nodeStyleChangeShift + 2),
615 IsEditingTextFlag = 1 << 17,
616 IsNamedFlowContentNodeFlag = 1 << 18,
617 HasSyntheticAttrChildNodesFlag = 1 << 19,
618 HasCustomStyleResolveCallbacksFlag = 1 << 20,
619 HasEventTargetDataFlag = 1 << 21,
620 // HeyItIsAFreeBit = 1 << 22,
621 IsInShadowTreeFlag = 1 << 23,
622 IsMathMLFlag = 1 << 24,
624 ChildrenAffectedByFirstChildRulesFlag = 1 << 25,
625 ChildrenAffectedByLastChildRulesFlag = 1 << 26,
626 ChildrenAffectedByHoverRulesFlag = 1 << 27,
628 DirectChildNeedsStyleRecalcFlag = 1 << 28,
629 AffectsNextSiblingElementStyle = 1 << 29,
630 StyleIsAffectedByPreviousSibling = 1 << 30,
632 SelfOrAncestorHasDirAutoFlag = 1 << 31,
634 DefaultNodeFlags = IsParsingChildrenFinishedFlag
637 bool getFlag(NodeFlags mask) const { return m_nodeFlags & mask; }
638 void setFlag(bool f, NodeFlags mask) const { m_nodeFlags = (m_nodeFlags & ~mask) | (-(int32_t)f & mask); }
639 void setFlag(NodeFlags mask) const { m_nodeFlags |= mask; }
640 void clearFlag(NodeFlags mask) const { m_nodeFlags &= ~mask; }
642 enum ConstructionType {
643 CreateOther = DefaultNodeFlags,
644 CreateText = DefaultNodeFlags | IsTextFlag,
645 CreateContainer = DefaultNodeFlags | IsContainerFlag,
646 CreateElement = CreateContainer | IsElementFlag,
647 CreatePseudoElement = CreateElement | InDocumentFlag,
648 CreateShadowRoot = CreateContainer | IsDocumentFragmentFlag | IsInShadowTreeFlag,
649 CreateDocumentFragment = CreateContainer | IsDocumentFragmentFlag,
650 CreateStyledElement = CreateElement | IsStyledElementFlag,
651 CreateHTMLElement = CreateStyledElement | IsHTMLFlag,
652 CreateSVGElement = CreateStyledElement | IsSVGFlag | HasCustomStyleResolveCallbacksFlag,
653 CreateDocument = CreateContainer | InDocumentFlag,
654 CreateEditingText = CreateText | IsEditingTextFlag,
655 CreateMathMLElement = CreateStyledElement | IsMathMLFlag
657 Node(Document&, ConstructionType);
659 virtual void didMoveToNewDocument(Document* oldDocument);
661 virtual void addSubresourceAttributeURLs(ListHashSet<URL>&) const { }
663 bool hasRareData() const { return getFlag(HasRareDataFlag); }
665 NodeRareData* rareData() const;
666 NodeRareData& ensureRareData();
667 void clearRareData();
669 void clearEventTargetData();
671 void setHasCustomStyleResolveCallbacks() { setFlag(true, HasCustomStyleResolveCallbacksFlag); }
673 void setTreeScope(TreeScope& scope) { m_treeScope = &scope; }
675 void setStyleChange(StyleChangeType changeType) { m_nodeFlags = (m_nodeFlags & ~StyleChangeMask) | changeType; }
676 void updateAncestorsForStyleRecalc();
679 virtual PseudoId customPseudoId() const
681 ASSERT(hasCustomStyleResolveCallbacks());
685 WEBCORE_EXPORT void removedLastRef();
687 virtual void refEventTarget() override;
688 virtual void derefEventTarget() override;
690 Element* ancestorElement() const;
692 void trackForDebugging();
693 void materializeRareData();
695 Vector<std::unique_ptr<MutationObserverRegistration>>* mutationObserverRegistry();
696 HashSet<MutationObserverRegistration*>* transientMutationObserverRegistry();
699 mutable uint32_t m_nodeFlags;
701 ContainerNode* m_parentNode { nullptr };
702 TreeScope* m_treeScope { nullptr };
703 Node* m_previous { nullptr };
704 Node* m_next { nullptr };
705 // When a node has rare data we move the renderer into the rare data.
707 RenderObject* m_renderer { nullptr };
708 NodeRareDataBase* m_rareData;
712 bool isParsingChildrenFinished() const { return getFlag(IsParsingChildrenFinishedFlag); }
713 void setIsParsingChildrenFinished() { setFlag(IsParsingChildrenFinishedFlag); }
714 void clearIsParsingChildrenFinished() { clearFlag(IsParsingChildrenFinishedFlag); }
718 inline void adopted(Node* node)
722 ASSERT(!node->m_deletionHasBegun);
723 ASSERT(!node->m_inRemovedLastRefFunction);
724 node->m_adoptionIsRequired = false;
728 ALWAYS_INLINE void Node::ref()
730 ASSERT(isMainThread());
731 ASSERT(!m_deletionHasBegun);
732 ASSERT(!m_inRemovedLastRefFunction);
733 ASSERT(!m_adoptionIsRequired);
737 ALWAYS_INLINE void Node::deref()
739 ASSERT(isMainThread());
740 ASSERT(m_refCount >= 0);
741 ASSERT(!m_deletionHasBegun);
742 ASSERT(!m_inRemovedLastRefFunction);
743 ASSERT(!m_adoptionIsRequired);
744 if (--m_refCount <= 0 && !parentNode()) {
746 m_inRemovedLastRefFunction = true;
752 ALWAYS_INLINE bool Node::hasOneRef() const
754 ASSERT(!m_deletionHasBegun);
755 ASSERT(!m_inRemovedLastRefFunction);
756 return m_refCount == 1;
759 ALWAYS_INLINE int Node::refCount() const
764 // Used in Node::addSubresourceAttributeURLs() and in addSubresourceStyleURLs()
765 inline void addSubresourceURL(ListHashSet<URL>& urls, const URL& url)
771 inline void Node::setParentNode(ContainerNode* parent)
773 ASSERT(isMainThread());
774 m_parentNode = parent;
777 inline ContainerNode* Node::parentNode() const
779 ASSERT(isMainThreadOrGCThread());
783 inline ContainerNode* Node::parentNodeGuaranteedHostFree() const
785 ASSERT(!isShadowRoot());
789 } // namespace WebCore
791 #if ENABLE(TREE_DEBUGGING)
792 // Outside the WebCore namespace for ease of invocation from gdb.
793 void showTree(const WebCore::Node*);
794 void showNodePath(const WebCore::Node*);