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.
27 #include "EventTarget.h"
28 #include "ExceptionOr.h"
29 #include "LayoutRect.h"
30 #include "MutationObserver.h"
31 #include "RenderStyleConstants.h"
32 #include "StyleValidity.h"
33 #include "TreeScope.h"
35 #include <wtf/Forward.h>
36 #include <wtf/ListHashSet.h>
37 #include <wtf/MainThread.h>
39 // This needs to be here because Document.h also depends on it.
40 #define DUMP_NODE_STATISTICS 0
48 class HTMLQualifiedName;
49 class HTMLSlotElement;
50 class MathMLQualifiedName;
53 class NodeListsNodeData;
57 class RenderBoxModelObject;
60 class SVGQualifiedName;
64 using NodeOrString = Variant<RefPtr<Node>, String>;
66 class NodeRareDataBase {
68 RenderObject* renderer() const { return m_renderer; }
69 void setRenderer(RenderObject* renderer) { m_renderer = renderer; }
72 NodeRareDataBase(RenderObject* renderer)
73 : m_renderer(renderer)
77 RenderObject* m_renderer;
80 class Node : public EventTarget {
81 WTF_MAKE_FAST_ALLOCATED;
83 friend class Document;
84 friend class TreeScope;
90 CDATA_SECTION_NODE = 4,
91 PROCESSING_INSTRUCTION_NODE = 7,
94 DOCUMENT_TYPE_NODE = 10,
95 DOCUMENT_FRAGMENT_NODE = 11,
97 enum DeprecatedNodeType {
98 ENTITY_REFERENCE_NODE = 5,
102 enum DocumentPosition {
103 DOCUMENT_POSITION_EQUIVALENT = 0x00,
104 DOCUMENT_POSITION_DISCONNECTED = 0x01,
105 DOCUMENT_POSITION_PRECEDING = 0x02,
106 DOCUMENT_POSITION_FOLLOWING = 0x04,
107 DOCUMENT_POSITION_CONTAINS = 0x08,
108 DOCUMENT_POSITION_CONTAINED_BY = 0x10,
109 DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20,
112 WEBCORE_EXPORT static void startIgnoringLeaks();
113 WEBCORE_EXPORT static void stopIgnoringLeaks();
115 static void dumpStatistics();
118 void willBeDeletedFrom(Document&);
120 // DOM methods & attributes for Node
122 bool hasTagName(const HTMLQualifiedName&) const;
123 bool hasTagName(const MathMLQualifiedName&) const;
124 bool hasTagName(const SVGQualifiedName&) const;
125 virtual String nodeName() const = 0;
126 virtual String nodeValue() const;
127 virtual ExceptionOr<void> setNodeValue(const String&);
128 virtual NodeType nodeType() const = 0;
129 virtual size_t approximateMemoryCost() const { return sizeof(*this); }
130 ContainerNode* parentNode() const;
131 static ptrdiff_t parentNodeMemoryOffset() { return OBJECT_OFFSETOF(Node, m_parentNode); }
132 Element* parentElement() const;
133 Node* previousSibling() const { return m_previous; }
134 static ptrdiff_t previousSiblingMemoryOffset() { return OBJECT_OFFSETOF(Node, m_previous); }
135 Node* nextSibling() const { return m_next; }
136 static ptrdiff_t nextSiblingMemoryOffset() { return OBJECT_OFFSETOF(Node, m_next); }
137 WEBCORE_EXPORT RefPtr<NodeList> childNodes();
138 Node* firstChild() const;
139 Node* lastChild() const;
140 bool hasAttributes() const;
141 NamedNodeMap* attributes() const;
142 Node* pseudoAwareNextSibling() const;
143 Node* pseudoAwarePreviousSibling() const;
144 Node* pseudoAwareFirstChild() const;
145 Node* pseudoAwareLastChild() const;
147 WEBCORE_EXPORT const URL& baseURI() const;
149 void getSubresourceURLs(ListHashSet<URL>&) const;
151 WEBCORE_EXPORT ExceptionOr<void> insertBefore(Node& newChild, Node* refChild);
152 WEBCORE_EXPORT ExceptionOr<void> replaceChild(Node& newChild, Node& oldChild);
153 WEBCORE_EXPORT ExceptionOr<void> removeChild(Node& child);
154 WEBCORE_EXPORT ExceptionOr<void> appendChild(Node& newChild);
156 bool hasChildNodes() const { return firstChild(); }
158 enum class CloningOperation {
160 SelfWithTemplateContent,
163 virtual Ref<Node> cloneNodeInternal(Document&, CloningOperation) = 0;
164 Ref<Node> cloneNode(bool deep) { return cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf); }
165 WEBCORE_EXPORT ExceptionOr<Ref<Node>> cloneNodeForBindings(bool deep);
167 virtual const AtomicString& localName() const;
168 virtual const AtomicString& namespaceURI() const;
169 virtual const AtomicString& prefix() const;
170 virtual ExceptionOr<void> setPrefix(const AtomicString&);
171 WEBCORE_EXPORT void normalize();
173 bool isSameNode(Node* other) const { return this == other; }
174 WEBCORE_EXPORT bool isEqualNode(Node*) const;
175 WEBCORE_EXPORT bool isDefaultNamespace(const AtomicString& namespaceURI) const;
176 WEBCORE_EXPORT const AtomicString& lookupPrefix(const AtomicString& namespaceURI) const;
177 WEBCORE_EXPORT const AtomicString& lookupNamespaceURI(const AtomicString& prefix) const;
179 WEBCORE_EXPORT String textContent(bool convertBRsToNewlines = false) const;
180 WEBCORE_EXPORT ExceptionOr<void> setTextContent(const String&);
182 Node* lastDescendant() const;
183 Node* firstDescendant() const;
185 // From the NonDocumentTypeChildNode - https://dom.spec.whatwg.org/#nondocumenttypechildnode
186 WEBCORE_EXPORT Element* previousElementSibling() const;
187 WEBCORE_EXPORT Element* nextElementSibling() const;
189 // From the ChildNode - https://dom.spec.whatwg.org/#childnode
190 ExceptionOr<void> before(Vector<NodeOrString>&&);
191 ExceptionOr<void> after(Vector<NodeOrString>&&);
192 ExceptionOr<void> replaceWith(Vector<NodeOrString>&&);
193 WEBCORE_EXPORT ExceptionOr<void> remove();
195 // Other methods (not part of DOM)
197 bool isElementNode() const { return getFlag(IsElementFlag); }
198 bool isContainerNode() const { return getFlag(IsContainerFlag); }
199 bool isTextNode() const { return getFlag(IsTextFlag); }
200 bool isHTMLElement() const { return getFlag(IsHTMLFlag); }
201 bool isSVGElement() const { return getFlag(IsSVGFlag); }
202 bool isMathMLElement() const { return getFlag(IsMathMLFlag); }
204 bool isPseudoElement() const { return pseudoId() != NOPSEUDO; }
205 bool isBeforePseudoElement() const { return pseudoId() == BEFORE; }
206 bool isAfterPseudoElement() const { return pseudoId() == AFTER; }
207 PseudoId pseudoId() const { return (isElementNode() && hasCustomStyleResolveCallbacks()) ? customPseudoId() : NOPSEUDO; }
209 virtual bool isMediaControlElement() const { return false; }
210 virtual bool isMediaControls() const { return false; }
211 #if ENABLE(VIDEO_TRACK)
212 virtual bool isWebVTTElement() const { return false; }
214 bool isStyledElement() const { return getFlag(IsStyledElementFlag); }
215 virtual bool isAttributeNode() const { return false; }
216 virtual bool isCharacterDataNode() const { return false; }
217 virtual bool isFrameOwnerElement() const { return false; }
218 virtual bool isPluginElement() const { return false; }
219 #if ENABLE(SERVICE_CONTROLS)
220 virtual bool isImageControlsRootElement() const { return false; }
221 virtual bool isImageControlsButtonElement() const { return false; }
224 bool isDocumentNode() const { return getFlag(IsContainerFlag) && !getFlag(IsElementFlag) && !getFlag(IsDocumentFragmentFlag); }
225 bool isTreeScope() const;
226 bool isDocumentFragment() const { return getFlag(IsDocumentFragmentFlag); }
227 bool isShadowRoot() const { return isDocumentFragment() && isTreeScope(); }
229 bool hasCustomStyleResolveCallbacks() const { return getFlag(HasCustomStyleResolveCallbacksFlag); }
231 bool hasSyntheticAttrChildNodes() const { return getFlag(HasSyntheticAttrChildNodesFlag); }
232 void setHasSyntheticAttrChildNodes(bool flag) { setFlag(flag, HasSyntheticAttrChildNodesFlag); }
234 // If this node is in a shadow tree, returns its shadow host. Otherwise, returns null.
235 WEBCORE_EXPORT Element* shadowHost() const;
236 // If this node is in a shadow tree, returns its shadow host. Otherwise, returns this.
237 // Deprecated. Should use shadowHost() and check the return value.
238 WEBCORE_EXPORT Node* deprecatedShadowAncestorNode() const;
239 ShadowRoot* containingShadowRoot() const;
240 ShadowRoot* shadowRoot() const;
241 bool isClosedShadowHidden(const Node&) const;
243 HTMLSlotElement* assignedSlot() const;
244 HTMLSlotElement* assignedSlotForBindings() const;
246 bool isUndefinedCustomElement() const { return isElementNode() && getFlag(IsEditingTextOrUndefinedCustomElementFlag); }
247 bool isCustomElementUpgradeCandidate() const { return getFlag(IsCustomElement) && getFlag(IsEditingTextOrUndefinedCustomElementFlag); }
248 bool isDefinedCustomElement() const { return getFlag(IsCustomElement) && !getFlag(IsEditingTextOrUndefinedCustomElementFlag); }
249 bool isFailedCustomElement() const { return isElementNode() && !getFlag(IsCustomElement) && getFlag(IsEditingTextOrUndefinedCustomElementFlag); }
251 // Returns null, a child of ShadowRoot, or a legacy shadow root.
252 Node* nonBoundaryShadowTreeRootNode();
254 // Node's parent or shadow tree host.
255 ContainerNode* parentOrShadowHostNode() const;
256 ContainerNode* parentInComposedTree() const;
257 Element* parentElementInComposedTree() const;
258 Element* parentOrShadowHostElement() const;
259 void setParentNode(ContainerNode*);
260 Node& rootNode() const;
261 Node& traverseToRootNode() const;
262 Node& shadowIncludingRoot() const;
264 struct GetRootNodeOptions {
267 Node& getRootNode(const GetRootNodeOptions&) const;
269 void* opaqueRoot() const;
271 // Use when it's guaranteed to that shadowHost is null.
272 ContainerNode* parentNodeGuaranteedHostFree() const;
273 // Returns the parent node, but null if the parent node is a ShadowRoot.
274 ContainerNode* nonShadowBoundaryParentNode() const;
276 bool selfOrAncestorHasDirAutoAttribute() const { return getFlag(SelfOrAncestorHasDirAutoFlag); }
277 void setSelfOrAncestorHasDirAutoAttribute(bool flag) { setFlag(flag, SelfOrAncestorHasDirAutoFlag); }
279 // Returns the enclosing event parent Element (or self) that, when clicked, would trigger a navigation.
280 Element* enclosingLinkEventParentOrSelf();
282 // These low-level calls give the caller responsibility for maintaining the integrity of the tree.
283 void setPreviousSibling(Node* previous) { m_previous = previous; }
284 void setNextSibling(Node* next) { m_next = next; }
286 virtual bool canContainRangeEndPoint() const { return false; }
288 bool isRootEditableElement() const;
289 WEBCORE_EXPORT Element* rootEditableElement() const;
291 // Called by the parser when this element's close tag is reached,
292 // signaling that all child tags have been parsed and added.
293 // This is needed for <applet> and <object> elements, which can't lay themselves out
294 // until they know all of their nested <param>s. [Radar 3603191, 4040848].
295 // Also used for script elements and some SVG elements for similar purposes,
296 // but making parsing a special case in this respect should be avoided if possible.
297 virtual void finishParsingChildren() { }
298 virtual void beginParsingChildren() { }
300 // For <link> and <style> elements.
301 virtual bool sheetLoaded() { return true; }
302 virtual void notifyLoadedSheetAndAllCriticalSubresources(bool /* error loading subresource */) { }
303 virtual void startLoadingDynamicSheet() { ASSERT_NOT_REACHED(); }
305 bool isUserActionElement() const { return getFlag(IsUserActionElement); }
306 void setUserActionElement(bool flag) { setFlag(flag, IsUserActionElement); }
308 bool inRenderedDocument() const;
309 bool needsStyleRecalc() const { return styleValidity() != Style::Validity::Valid; }
310 Style::Validity styleValidity() const;
311 bool styleResolutionShouldRecompositeLayer() const;
312 bool childNeedsStyleRecalc() const { return getFlag(ChildNeedsStyleRecalcFlag); }
313 bool styleIsAffectedByPreviousSibling() const { return getFlag(StyleIsAffectedByPreviousSibling); }
314 bool isEditingText() const { return getFlag(IsTextFlag) && getFlag(IsEditingTextOrUndefinedCustomElementFlag); }
316 void setChildNeedsStyleRecalc() { setFlag(ChildNeedsStyleRecalcFlag); }
317 void clearChildNeedsStyleRecalc() { m_nodeFlags &= ~(ChildNeedsStyleRecalcFlag | DirectChildNeedsStyleRecalcFlag); }
319 void setHasValidStyle();
321 bool isLink() const { return getFlag(IsLinkFlag); }
322 void setIsLink(bool flag) { setFlag(flag, IsLinkFlag); }
324 bool hasEventTargetData() const { return getFlag(HasEventTargetDataFlag); }
325 void setHasEventTargetData(bool flag) { setFlag(flag, HasEventTargetDataFlag); }
327 enum UserSelectAllTreatment {
328 UserSelectAllDoesNotAffectEditability,
329 UserSelectAllIsAlwaysNonEditable
331 WEBCORE_EXPORT bool isContentEditable();
332 bool isContentRichlyEditable();
334 WEBCORE_EXPORT void inspect();
336 bool hasEditableStyle(UserSelectAllTreatment treatment = UserSelectAllIsAlwaysNonEditable) const
338 return computeEditability(treatment, ShouldUpdateStyle::DoNotUpdate) != Editability::ReadOnly;
340 // FIXME: Replace every use of this function by helpers in Editing.h
341 bool hasRichlyEditableStyle() const
343 return computeEditability(UserSelectAllIsAlwaysNonEditable, ShouldUpdateStyle::DoNotUpdate) == Editability::CanEditRichly;
346 enum class Editability { ReadOnly, CanEditPlainText, CanEditRichly };
347 enum class ShouldUpdateStyle { Update, DoNotUpdate };
348 WEBCORE_EXPORT Editability computeEditability(UserSelectAllTreatment, ShouldUpdateStyle) const;
350 WEBCORE_EXPORT LayoutRect renderRect(bool* isReplaced);
351 IntRect pixelSnappedRenderRect(bool* isReplaced) { return snappedIntRect(renderRect(isReplaced)); }
353 WEBCORE_EXPORT unsigned computeNodeIndex() const;
355 // Returns the DOM ownerDocument attribute. This method never returns null, except in the case
356 // of a Document node.
357 WEBCORE_EXPORT Document* ownerDocument() const;
359 // Returns the document associated with this node.
360 // A Document node returns itself.
361 Document& document() const
363 return treeScope().documentScope();
366 TreeScope& treeScope() const
371 void setTreeScopeRecursively(TreeScope&);
372 static ptrdiff_t treeScopeMemoryOffset() { return OBJECT_OFFSETOF(Node, m_treeScope); }
374 // Returns true if this node is associated with a document and is in its associated document's
375 // node tree, false otherwise (https://dom.spec.whatwg.org/#connected).
376 bool isConnected() const
378 return getFlag(IsConnectedFlag);
380 bool isInUserAgentShadowTree() const;
381 bool isInShadowTree() const { return getFlag(IsInShadowTreeFlag); }
382 bool isInTreeScope() const { return getFlag(static_cast<NodeFlags>(IsConnectedFlag | IsInShadowTreeFlag)); }
384 bool isDocumentTypeNode() const { return nodeType() == DOCUMENT_TYPE_NODE; }
385 virtual bool childTypeAllowed(NodeType) const { return false; }
386 unsigned countChildNodes() const;
387 Node* traverseToChildAt(unsigned) const;
389 ExceptionOr<void> checkSetPrefix(const AtomicString& prefix);
391 WEBCORE_EXPORT bool isDescendantOf(const Node&) const;
392 bool isDescendantOf(const Node* other) const { return other && isDescendantOf(*other); }
394 bool isDescendantOrShadowDescendantOf(const Node*) const;
395 WEBCORE_EXPORT bool contains(const Node*) const;
396 bool containsIncludingShadowDOM(const Node*) const;
397 bool containsIncludingHostElements(const Node*) const;
399 // Used to determine whether range offsets use characters or node indices.
400 virtual bool offsetInCharacters() const;
401 // Number of DOM 16-bit units contained in node. Note that rendered text length can be different - e.g. because of
402 // css-transform:capitalize breaking up precomposed characters and ligatures.
403 virtual int maxCharacterOffset() const;
405 // Whether or not a selection can be started in this object
406 virtual bool canStartSelection() const;
408 virtual bool shouldSelectOnMouseDown() { return false; }
410 // Getting points into and out of screen space
411 FloatPoint convertToPage(const FloatPoint&) const;
412 FloatPoint convertFromPage(const FloatPoint&) const;
414 // -----------------------------------------------------------------------------
415 // Integration with rendering tree
417 // As renderer() includes a branch you should avoid calling it repeatedly in hot code paths.
418 RenderObject* renderer() const { return hasRareData() ? m_data.m_rareData->renderer() : m_data.m_renderer; };
419 void setRenderer(RenderObject* renderer)
422 m_data.m_rareData->setRenderer(renderer);
424 m_data.m_renderer = renderer;
427 // Use these two methods with caution.
428 WEBCORE_EXPORT RenderBox* renderBox() const;
429 RenderBoxModelObject* renderBoxModelObject() const;
431 // Wrapper for nodes that don't have a renderer, but still cache the style (like HTMLOptionElement).
432 const RenderStyle* renderStyle() const;
434 virtual const RenderStyle* computedStyle(PseudoId pseudoElementSpecifier = NOPSEUDO);
436 enum class InsertedIntoAncestorResult {
438 NeedsPostInsertionCallback,
441 struct InsertionType {
442 #if !COMPILER_SUPPORTS(NSDMI_FOR_AGGREGATES)
443 InsertionType(bool connectedToDocument, bool treeScopeChanged)
444 : connectedToDocument(connectedToDocument)
445 , treeScopeChanged(treeScopeChanged)
448 bool connectedToDocument { false };
449 bool treeScopeChanged { false };
451 // Called *after* this node or its ancestor is inserted into a new parent (may or may not be a part of document) by scripts or parser.
452 // insertedInto **MUST NOT** invoke scripts. Return NeedsPostInsertionCallback and implement didFinishInsertingNode instead to run scripts.
453 virtual InsertedIntoAncestorResult insertedIntoAncestor(InsertionType, ContainerNode& parentOfInsertedTree);
454 virtual void didFinishInsertingNode() { }
457 #if !COMPILER_SUPPORTS(NSDMI_FOR_AGGREGATES)
458 RemovalType(bool disconnectedFromDocument, bool treeScopeChanged)
459 : disconnectedFromDocument(disconnectedFromDocument)
460 , treeScopeChanged(treeScopeChanged)
463 bool disconnectedFromDocument { false };
464 bool treeScopeChanged { false };
466 virtual void removedFromAncestor(RemovalType, ContainerNode& oldParentOfRemovedTree);
468 #if ENABLE(TREE_DEBUGGING)
469 virtual void formatForDebugger(char* buffer, unsigned length) const;
471 void showNode(const char* prefix = "") const;
472 void showTreeForThis() const;
473 void showNodePathForThis() const;
474 void showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2 = nullptr, const char* markedLabel2 = nullptr) const;
475 void showTreeForThisAcrossFrame() const;
476 #endif // ENABLE(TREE_DEBUGGING)
478 void invalidateNodeListAndCollectionCachesInAncestors();
479 void invalidateNodeListAndCollectionCachesInAncestorsForAttribute(const QualifiedName& attrName);
480 NodeListsNodeData* nodeLists();
481 void clearNodeLists();
483 virtual bool willRespondToMouseMoveEvents();
484 virtual bool willRespondToMouseClickEvents();
485 virtual bool willRespondToMouseWheelEvents();
487 WEBCORE_EXPORT unsigned short compareDocumentPosition(Node&);
489 RefPtr<Node> toNode() override;
491 EventTargetInterface eventTargetInterface() const override;
492 ScriptExecutionContext* scriptExecutionContext() const final; // Implemented in Document.h
494 bool addEventListener(const AtomicString& eventType, Ref<EventListener>&&, const AddEventListenerOptions&) override;
495 bool removeEventListener(const AtomicString& eventType, EventListener&, const ListenerOptions&) override;
497 using EventTarget::dispatchEvent;
498 bool dispatchEvent(Event&) override;
500 void dispatchScopedEvent(Event&);
502 virtual void handleLocalEvents(Event&);
504 void dispatchSubtreeModifiedEvent();
505 bool dispatchDOMActivateEvent(int detail, Event& underlyingEvent);
507 #if ENABLE(TOUCH_EVENTS)
508 virtual bool allowsDoubleTapGesture() const { return true; }
511 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
512 bool dispatchTouchEvent(TouchEvent&);
514 bool dispatchBeforeLoadEvent(const String& sourceURL);
516 void dispatchInputEvent();
518 // Perform the default action for an event.
519 virtual void defaultEventHandler(Event&);
523 bool hasOneRef() const;
524 int refCount() const;
527 bool m_deletionHasBegun { false };
528 bool m_inRemovedLastRefFunction { false };
529 bool m_adoptionIsRequired { true };
532 EventTargetData* eventTargetData() final;
533 EventTargetData* eventTargetDataConcurrently() final;
534 EventTargetData& ensureEventTargetData() final;
536 HashMap<MutationObserver*, MutationRecordDeliveryOptions> registeredMutationObservers(MutationObserver::MutationType, const QualifiedName* attributeName);
537 void registerMutationObserver(MutationObserver&, MutationObserverOptions, const HashSet<AtomicString>& attributeFilter);
538 void unregisterMutationObserver(MutationObserverRegistration&);
539 void registerTransientMutationObserver(MutationObserverRegistration&);
540 void unregisterTransientMutationObserver(MutationObserverRegistration&);
541 void notifyMutationObserversNodeWillDetach();
543 WEBCORE_EXPORT void textRects(Vector<IntRect>&) const;
545 unsigned connectedSubframeCount() const;
546 void incrementConnectedSubframeCount(unsigned amount = 1);
547 void decrementConnectedSubframeCount(unsigned amount = 1);
548 void updateAncestorConnectedSubframeCountForRemoval() const;
549 void updateAncestorConnectedSubframeCountForInsertion() const;
552 static ptrdiff_t nodeFlagsMemoryOffset() { return OBJECT_OFFSETOF(Node, m_nodeFlags); }
553 static ptrdiff_t rareDataMemoryOffset() { return OBJECT_OFFSETOF(Node, m_data.m_rareData); }
554 static int32_t flagIsText() { return IsTextFlag; }
555 static int32_t flagIsContainer() { return IsContainerFlag; }
556 static int32_t flagIsElement() { return IsElementFlag; }
557 static int32_t flagIsHTML() { return IsHTMLFlag; }
558 static int32_t flagIsLink() { return IsLinkFlag; }
559 static int32_t flagHasFocusWithin() { return HasFocusWithin; }
560 static int32_t flagHasRareData() { return HasRareDataFlag; }
561 static int32_t flagIsParsingChildrenFinished() { return IsParsingChildrenFinishedFlag; }
562 static int32_t flagChildrenAffectedByFirstChildRulesFlag() { return ChildrenAffectedByFirstChildRulesFlag; }
563 static int32_t flagChildrenAffectedByLastChildRulesFlag() { return ChildrenAffectedByLastChildRulesFlag; }
565 static int32_t flagAffectsNextSiblingElementStyle() { return AffectsNextSiblingElementStyle; }
566 static int32_t flagStyleIsAffectedByPreviousSibling() { return StyleIsAffectedByPreviousSibling; }
567 #endif // ENABLE(JIT)
572 IsContainerFlag = 1 << 1,
573 IsElementFlag = 1 << 2,
574 IsStyledElementFlag = 1 << 3,
577 // One free bit left.
578 ChildNeedsStyleRecalcFlag = 1 << 7,
579 IsConnectedFlag = 1 << 8,
581 IsUserActionElement = 1 << 10,
582 HasRareDataFlag = 1 << 11,
583 IsDocumentFragmentFlag = 1 << 12,
585 // These bits are used by derived classes, pulled up here so they can
586 // be stored in the same memory word as the Node bits above.
587 IsParsingChildrenFinishedFlag = 1 << 13, // Element
588 StyleValidityShift = 14,
589 StyleValidityMask = 3 << StyleValidityShift,
590 StyleResolutionShouldRecompositeLayerFlag = 1 << 16,
591 IsEditingTextOrUndefinedCustomElementFlag = 1 << 17,
592 HasFocusWithin = 1 << 18,
593 HasSyntheticAttrChildNodesFlag = 1 << 19,
594 HasCustomStyleResolveCallbacksFlag = 1 << 20,
595 HasEventTargetDataFlag = 1 << 21,
596 IsCustomElement = 1 << 22,
597 IsInShadowTreeFlag = 1 << 23,
598 IsMathMLFlag = 1 << 24,
600 ChildrenAffectedByFirstChildRulesFlag = 1 << 25,
601 ChildrenAffectedByLastChildRulesFlag = 1 << 26,
602 ChildrenAffectedByHoverRulesFlag = 1 << 27,
604 DirectChildNeedsStyleRecalcFlag = 1 << 28,
605 AffectsNextSiblingElementStyle = 1 << 29,
606 StyleIsAffectedByPreviousSibling = 1 << 30,
608 SelfOrAncestorHasDirAutoFlag = 1 << 31,
610 DefaultNodeFlags = IsParsingChildrenFinishedFlag
613 bool getFlag(NodeFlags mask) const { return m_nodeFlags & mask; }
614 void setFlag(bool f, NodeFlags mask) const { m_nodeFlags = (m_nodeFlags & ~mask) | (-(int32_t)f & mask); }
615 void setFlag(NodeFlags mask) const { m_nodeFlags |= mask; }
616 void clearFlag(NodeFlags mask) const { m_nodeFlags &= ~mask; }
618 bool isParsingChildrenFinished() const { return getFlag(IsParsingChildrenFinishedFlag); }
619 void setIsParsingChildrenFinished() { setFlag(IsParsingChildrenFinishedFlag); }
620 void clearIsParsingChildrenFinished() { clearFlag(IsParsingChildrenFinishedFlag); }
622 enum ConstructionType {
623 CreateOther = DefaultNodeFlags,
624 CreateText = DefaultNodeFlags | IsTextFlag,
625 CreateContainer = DefaultNodeFlags | IsContainerFlag,
626 CreateElement = CreateContainer | IsElementFlag,
627 CreatePseudoElement = CreateElement | IsConnectedFlag,
628 CreateShadowRoot = CreateContainer | IsDocumentFragmentFlag | IsInShadowTreeFlag,
629 CreateDocumentFragment = CreateContainer | IsDocumentFragmentFlag,
630 CreateStyledElement = CreateElement | IsStyledElementFlag,
631 CreateHTMLElement = CreateStyledElement | IsHTMLFlag,
632 CreateSVGElement = CreateStyledElement | IsSVGFlag | HasCustomStyleResolveCallbacksFlag,
633 CreateDocument = CreateContainer | IsConnectedFlag,
634 CreateEditingText = CreateText | IsEditingTextOrUndefinedCustomElementFlag,
635 CreateMathMLElement = CreateStyledElement | IsMathMLFlag
637 Node(Document&, ConstructionType);
639 virtual void addSubresourceAttributeURLs(ListHashSet<URL>&) const { }
641 bool hasRareData() const { return getFlag(HasRareDataFlag); }
643 NodeRareData* rareData() const;
644 NodeRareData& ensureRareData();
645 void clearRareData();
647 void clearEventTargetData();
649 void setHasCustomStyleResolveCallbacks() { setFlag(true, HasCustomStyleResolveCallbacksFlag); }
651 void setTreeScope(TreeScope& scope) { m_treeScope = &scope; }
653 void invalidateStyle(Style::Validity, Style::InvalidationMode = Style::InvalidationMode::Normal);
654 void updateAncestorsForStyleRecalc();
656 ExceptionOr<RefPtr<Node>> convertNodesOrStringsIntoNode(Vector<NodeOrString>&&);
659 virtual PseudoId customPseudoId() const
661 ASSERT(hasCustomStyleResolveCallbacks());
665 WEBCORE_EXPORT void removedLastRef();
667 void refEventTarget() override;
668 void derefEventTarget() override;
670 void trackForDebugging();
671 void materializeRareData();
673 Vector<std::unique_ptr<MutationObserverRegistration>>* mutationObserverRegistry();
674 HashSet<MutationObserverRegistration*>* transientMutationObserverRegistry();
676 void adjustStyleValidity(Style::Validity, Style::InvalidationMode);
678 void* opaqueRootSlow() const;
680 static void moveShadowTreeToNewDocument(ShadowRoot&, Document& oldDocument, Document& newDocument);
681 static void moveTreeToNewScope(Node&, TreeScope& oldScope, TreeScope& newScope);
682 void moveNodeToNewDocument(Document& oldDocument, Document& newDocument);
685 mutable uint32_t m_nodeFlags;
687 ContainerNode* m_parentNode { nullptr };
688 TreeScope* m_treeScope { nullptr };
689 Node* m_previous { nullptr };
690 Node* m_next { nullptr };
691 // When a node has rare data we move the renderer into the rare data.
693 RenderObject* m_renderer;
694 NodeRareDataBase* m_rareData;
695 } m_data { nullptr };
699 inline void adopted(Node* node)
703 ASSERT(!node->m_deletionHasBegun);
704 ASSERT(!node->m_inRemovedLastRefFunction);
705 node->m_adoptionIsRequired = false;
709 ALWAYS_INLINE void Node::ref()
711 ASSERT(isMainThread());
712 ASSERT(!m_deletionHasBegun);
713 ASSERT(!m_inRemovedLastRefFunction);
714 ASSERT(!m_adoptionIsRequired);
718 ALWAYS_INLINE void Node::deref()
720 ASSERT(isMainThread());
721 ASSERT(m_refCount >= 0);
722 ASSERT(!m_deletionHasBegun);
723 ASSERT(!m_inRemovedLastRefFunction);
724 ASSERT(!m_adoptionIsRequired);
725 if (--m_refCount <= 0 && !parentNode()) {
727 m_inRemovedLastRefFunction = true;
733 ALWAYS_INLINE bool Node::hasOneRef() const
735 ASSERT(!m_deletionHasBegun);
736 ASSERT(!m_inRemovedLastRefFunction);
737 return m_refCount == 1;
740 ALWAYS_INLINE int Node::refCount() const
745 // Used in Node::addSubresourceAttributeURLs() and in addSubresourceStyleURLs()
746 inline void addSubresourceURL(ListHashSet<URL>& urls, const URL& url)
752 inline void Node::setParentNode(ContainerNode* parent)
754 ASSERT(isMainThread());
755 m_parentNode = parent;
758 inline ContainerNode* Node::parentNode() const
760 ASSERT(isMainThreadOrGCThread());
764 inline void* Node::opaqueRoot() const
766 // FIXME: Possible race?
767 // https://bugs.webkit.org/show_bug.cgi?id=165713
770 return opaqueRootSlow();
773 inline ContainerNode* Node::parentNodeGuaranteedHostFree() const
775 ASSERT(!isShadowRoot());
779 inline Style::Validity Node::styleValidity() const
781 return static_cast<Style::Validity>((m_nodeFlags & StyleValidityMask) >> StyleValidityShift);
784 inline bool Node::styleResolutionShouldRecompositeLayer() const
786 return getFlag(StyleResolutionShouldRecompositeLayerFlag);
789 inline void Node::setHasValidStyle()
791 m_nodeFlags &= ~StyleValidityMask;
792 clearFlag(StyleResolutionShouldRecompositeLayerFlag);
795 inline void Node::setTreeScopeRecursively(TreeScope& newTreeScope)
797 ASSERT(!isDocumentNode());
798 ASSERT(!m_deletionHasBegun);
799 if (m_treeScope != &newTreeScope)
800 moveTreeToNewScope(*this, *m_treeScope, newTreeScope);
803 } // namespace WebCore
805 #if ENABLE(TREE_DEBUGGING)
806 // Outside the WebCore namespace for ease of invocation from the debugger.
807 void showTree(const WebCore::Node*);
808 void showNodePath(const WebCore::Node*);