Factor style sharing code out of StyleResolver
authorantti@apple.com <antti@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Tue, 2 Feb 2016 22:34:45 +0000 (22:34 +0000)
committerantti@apple.com <antti@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Tue, 2 Feb 2016 22:34:45 +0000 (22:34 +0000)
https://bugs.webkit.org/show_bug.cgi?id=153768

Reviewed by Darin Adler.

Move the code to a new class, Style::SharingResolver.

When resolving document style we query the sharing resolver first before using the regular style resolver.
Other paths that call style resolver were mostly already disabling it with DisallowStyleSharing flag.

* WebCore.xcodeproj/project.pbxproj:
* css/ElementRuleCollector.cpp:
(WebCore::MatchRequest::MatchRequest):
(WebCore::ElementRuleCollector::matchAllRules):
(WebCore::ElementRuleCollector::hasAnyMatchingRules):

    More const.

* css/ElementRuleCollector.h:
(WebCore::ElementRuleCollector::setRegionForStyling):
(WebCore::ElementRuleCollector::setMedium):
* css/MediaQueryMatcher.cpp:
(WebCore::MediaQueryMatcher::prepareEvaluator):
* css/StyleMedia.cpp:
(WebCore::StyleMedia::matchMedium):
* css/StyleResolver.cpp:
(WebCore::StyleResolver::State::cacheBorderAndBackground):
(WebCore::StyleResolver::StyleResolver):
(WebCore::StyleResolver::sweepMatchedPropertiesCache):
(WebCore::StyleResolver::State::State):
(WebCore::StyleResolver::State::setStyle):
(WebCore::isAtShadowBoundary):
(WebCore::StyleResolver::styleForElement):
(WebCore::StyleResolver::classNamesAffectedByRules): Deleted.
(WebCore::parentElementPreventsSharing): Deleted.
(WebCore::StyleResolver::locateCousinList): Deleted.
(WebCore::StyleResolver::styleSharingCandidateMatchesRuleSet): Deleted.
(WebCore::StyleResolver::canShareStyleWithControl): Deleted.
(WebCore::elementHasDirectionAuto): Deleted.
(WebCore::StyleResolver::sharingCandidateHasIdenticalStyleAffectingAttributes): Deleted.
(WebCore::StyleResolver::canShareStyleWithElement): Deleted.
(WebCore::StyleResolver::findSiblingForStyleSharing): Deleted.
(WebCore::StyleResolver::locateSharedStyle): Deleted.

    Style sharing code moves to SharingResolver.

* css/StyleResolver.h:
(WebCore::StyleResolver::mediaQueryEvaluator):
(WebCore::StyleResolver::State::regionForStyling):
(WebCore::StyleResolver::State::elementLinkState):
(WebCore::StyleResolver::State::setApplyPropertyToRegularStyle):
(WebCore::StyleResolver::State::setApplyPropertyToVisitedLinkStyle):
(WebCore::StyleResolver::state):
(WebCore::StyleResolver::setTextOrientation):
(WebCore::StyleResolver::State::setElementAffectedByClassRules): Deleted.
(WebCore::StyleResolver::State::elementAffectedByClassRules): Deleted.
(WebCore::StyleResolver::styleNotYetAvailable): Deleted.

    Placeholder code moves to TreeResolver.

* dom/VisitedLinkState.cpp:
(WebCore::linkAttribute):
(WebCore::VisitedLinkState::invalidateStyleForAllLinks):
(WebCore::linkHashForElement):
(WebCore::VisitedLinkState::invalidateStyleForLink):
(WebCore::VisitedLinkState::determineLinkStateSlowCase):
* dom/VisitedLinkState.h:
(WebCore::VisitedLinkState::determineLinkState):
* html/HTMLFormControlElement.h:
* rendering/RenderElement.cpp:
(WebCore::RenderElement::getUncachedPseudoStyle):
* rendering/RenderNamedFlowFragment.cpp:
(WebCore::RenderNamedFlowFragment::computeStyleInRegion):
* rendering/style/RenderStyle.cpp:
(WebCore::RenderStyle::isStyleAvailable):
(WebCore::RenderStyle::hasUniquePseudoStyle):
* style/StyleSharingResolver.cpp: Added.
(WebCore::Style::SharingResolver::SharingResolver):
(WebCore::Style::parentElementPreventsSharing):
(WebCore::Style::elementHasDirectionAuto):
(WebCore::Style::SharingResolver::searchSimilar):
(WebCore::Style::SharingResolver::findSibling):
(WebCore::Style::SharingResolver::locateCousinList):
(WebCore::Style::canShareStyleWithControl):
(WebCore::Style::SharingResolver::canShareStyleWithElement):
(WebCore::Style::SharingResolver::styleSharingCandidateMatchesRuleSet):
(WebCore::Style::SharingResolver::sharingCandidateHasIdenticalStyleAffectingAttributes):
(WebCore::Style::SharingResolver::classNamesAffectedByRules):
* style/StyleSharingResolver.h: Added.
* style/StyleTreeResolver.cpp:
(WebCore::Style::ensurePlaceholderStyle):
(WebCore::Style::TreeResolver::TreeResolver):
(WebCore::Style::TreeResolver::styleForElement):

    Try to use SharingResolver first.
    Also move placeholder style handling here, it is only relevant when resolving document style.

(WebCore::Style::postResolutionCallbacksAreSuspended):
(WebCore::Style::isPlaceholderStyle):
* style/StyleTreeResolver.h:
* svg/SVGElement.cpp:
(WebCore::SVGElement::customStyleForRenderer):
* svg/SVGElementRareData.h:
(WebCore::SVGElementRareData::overrideComputedStyle):

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@196031 268f45cc-cd09-0410-ab3c-d52691b4dbfc

22 files changed:
Source/WebCore/CMakeLists.txt
Source/WebCore/ChangeLog
Source/WebCore/WebCore.vcxproj/WebCore.vcxproj
Source/WebCore/WebCore.xcodeproj/project.pbxproj
Source/WebCore/css/ElementRuleCollector.cpp
Source/WebCore/css/ElementRuleCollector.h
Source/WebCore/css/MediaQueryMatcher.cpp
Source/WebCore/css/StyleMedia.cpp
Source/WebCore/css/StyleResolver.cpp
Source/WebCore/css/StyleResolver.h
Source/WebCore/dom/VisitedLinkState.cpp
Source/WebCore/dom/VisitedLinkState.h
Source/WebCore/html/HTMLFormControlElement.h
Source/WebCore/rendering/RenderElement.cpp
Source/WebCore/rendering/RenderNamedFlowFragment.cpp
Source/WebCore/rendering/style/RenderStyle.cpp
Source/WebCore/style/StyleSharingResolver.cpp [new file with mode: 0644]
Source/WebCore/style/StyleSharingResolver.h [new file with mode: 0644]
Source/WebCore/style/StyleTreeResolver.cpp
Source/WebCore/style/StyleTreeResolver.h
Source/WebCore/svg/SVGElement.cpp
Source/WebCore/svg/SVGElementRareData.h

index 86fa0ad..28ff5bc 100644 (file)
@@ -2639,6 +2639,7 @@ set(WebCore_SOURCES
     style/StyleChange.cpp
     style/StyleFontSizeFunctions.cpp
     style/StyleResolveForDocument.cpp
+    style/StyleSharingResolver.cpp
     style/StyleTreeResolver.cpp
 
     svg/SVGAElement.cpp
index cde09c0..e9fbf23 100644 (file)
@@ -1,3 +1,110 @@
+2016-02-02  Antti Koivisto  <antti@apple.com>
+
+        Factor style sharing code out of StyleResolver
+        https://bugs.webkit.org/show_bug.cgi?id=153768
+
+        Reviewed by Darin Adler.
+
+        Move the code to a new class, Style::SharingResolver.
+
+        When resolving document style we query the sharing resolver first before using the regular style resolver.
+        Other paths that call style resolver were mostly already disabling it with DisallowStyleSharing flag.
+
+        * WebCore.xcodeproj/project.pbxproj:
+        * css/ElementRuleCollector.cpp:
+        (WebCore::MatchRequest::MatchRequest):
+        (WebCore::ElementRuleCollector::matchAllRules):
+        (WebCore::ElementRuleCollector::hasAnyMatchingRules):
+
+            More const.
+
+        * css/ElementRuleCollector.h:
+        (WebCore::ElementRuleCollector::setRegionForStyling):
+        (WebCore::ElementRuleCollector::setMedium):
+        * css/MediaQueryMatcher.cpp:
+        (WebCore::MediaQueryMatcher::prepareEvaluator):
+        * css/StyleMedia.cpp:
+        (WebCore::StyleMedia::matchMedium):
+        * css/StyleResolver.cpp:
+        (WebCore::StyleResolver::State::cacheBorderAndBackground):
+        (WebCore::StyleResolver::StyleResolver):
+        (WebCore::StyleResolver::sweepMatchedPropertiesCache):
+        (WebCore::StyleResolver::State::State):
+        (WebCore::StyleResolver::State::setStyle):
+        (WebCore::isAtShadowBoundary):
+        (WebCore::StyleResolver::styleForElement):
+        (WebCore::StyleResolver::classNamesAffectedByRules): Deleted.
+        (WebCore::parentElementPreventsSharing): Deleted.
+        (WebCore::StyleResolver::locateCousinList): Deleted.
+        (WebCore::StyleResolver::styleSharingCandidateMatchesRuleSet): Deleted.
+        (WebCore::StyleResolver::canShareStyleWithControl): Deleted.
+        (WebCore::elementHasDirectionAuto): Deleted.
+        (WebCore::StyleResolver::sharingCandidateHasIdenticalStyleAffectingAttributes): Deleted.
+        (WebCore::StyleResolver::canShareStyleWithElement): Deleted.
+        (WebCore::StyleResolver::findSiblingForStyleSharing): Deleted.
+        (WebCore::StyleResolver::locateSharedStyle): Deleted.
+
+            Style sharing code moves to SharingResolver.
+
+        * css/StyleResolver.h:
+        (WebCore::StyleResolver::mediaQueryEvaluator):
+        (WebCore::StyleResolver::State::regionForStyling):
+        (WebCore::StyleResolver::State::elementLinkState):
+        (WebCore::StyleResolver::State::setApplyPropertyToRegularStyle):
+        (WebCore::StyleResolver::State::setApplyPropertyToVisitedLinkStyle):
+        (WebCore::StyleResolver::state):
+        (WebCore::StyleResolver::setTextOrientation):
+        (WebCore::StyleResolver::State::setElementAffectedByClassRules): Deleted.
+        (WebCore::StyleResolver::State::elementAffectedByClassRules): Deleted.
+        (WebCore::StyleResolver::styleNotYetAvailable): Deleted.
+
+            Placeholder code moves to TreeResolver.
+
+        * dom/VisitedLinkState.cpp:
+        (WebCore::linkAttribute):
+        (WebCore::VisitedLinkState::invalidateStyleForAllLinks):
+        (WebCore::linkHashForElement):
+        (WebCore::VisitedLinkState::invalidateStyleForLink):
+        (WebCore::VisitedLinkState::determineLinkStateSlowCase):
+        * dom/VisitedLinkState.h:
+        (WebCore::VisitedLinkState::determineLinkState):
+        * html/HTMLFormControlElement.h:
+        * rendering/RenderElement.cpp:
+        (WebCore::RenderElement::getUncachedPseudoStyle):
+        * rendering/RenderNamedFlowFragment.cpp:
+        (WebCore::RenderNamedFlowFragment::computeStyleInRegion):
+        * rendering/style/RenderStyle.cpp:
+        (WebCore::RenderStyle::isStyleAvailable):
+        (WebCore::RenderStyle::hasUniquePseudoStyle):
+        * style/StyleSharingResolver.cpp: Added.
+        (WebCore::Style::SharingResolver::SharingResolver):
+        (WebCore::Style::parentElementPreventsSharing):
+        (WebCore::Style::elementHasDirectionAuto):
+        (WebCore::Style::SharingResolver::searchSimilar):
+        (WebCore::Style::SharingResolver::findSibling):
+        (WebCore::Style::SharingResolver::locateCousinList):
+        (WebCore::Style::canShareStyleWithControl):
+        (WebCore::Style::SharingResolver::canShareStyleWithElement):
+        (WebCore::Style::SharingResolver::styleSharingCandidateMatchesRuleSet):
+        (WebCore::Style::SharingResolver::sharingCandidateHasIdenticalStyleAffectingAttributes):
+        (WebCore::Style::SharingResolver::classNamesAffectedByRules):
+        * style/StyleSharingResolver.h: Added.
+        * style/StyleTreeResolver.cpp:
+        (WebCore::Style::ensurePlaceholderStyle):
+        (WebCore::Style::TreeResolver::TreeResolver):
+        (WebCore::Style::TreeResolver::styleForElement):
+
+            Try to use SharingResolver first.
+            Also move placeholder style handling here, it is only relevant when resolving document style.
+
+        (WebCore::Style::postResolutionCallbacksAreSuspended):
+        (WebCore::Style::isPlaceholderStyle):
+        * style/StyleTreeResolver.h:
+        * svg/SVGElement.cpp:
+        (WebCore::SVGElement::customStyleForRenderer):
+        * svg/SVGElementRareData.h:
+        (WebCore::SVGElementRareData::overrideComputedStyle):
+
 2016-02-02  Tim Horton  <timothy_horton@apple.com>
 
         <attachment> icon should be a folder for the custom MIME type multipart/x-folder
index 37c8cd6..589dd93 100644 (file)
     <ClCompile Include="..\style\StyleChange.cpp" />
     <ClCompile Include="..\style\StyleFontSizeFunctions.cpp" />
     <ClCompile Include="..\style\StyleResolveForDocument.cpp" />
+    <ClCompile Include="..\style\StyleSharingResolver.cpp" />
     <ClCompile Include="..\style\StyleTreeResolver.cpp" />
     <ClCompile Include="..\bridge\jsc\BridgeJSC.cpp" />
     <ClCompile Include="..\bridge\c\c_class.cpp" />
     <ClInclude Include="..\style\StyleChange.h" />
     <ClInclude Include="..\style\StyleFontSizeFunctions.h" />
     <ClInclude Include="..\style\StyleResolveForDocument.h" />
+    <ClInclude Include="..\style\StyleSharingResolver.h" />
     <ClInclude Include="..\style\StyleTreeResolver.h" />
     <ClInclude Include="..\bridge\Bridge.h" />
     <ClInclude Include="..\bridge\jsc\BridgeJSC.h" />
index 657c565..a5d14c1 100644 (file)
                E47127CB163438AE00ED6F5A /* StyleInvalidationAnalysis.h in Headers */ = {isa = PBXBuildFile; fileRef = E47A97CF163059FC005DCD99 /* StyleInvalidationAnalysis.h */; };
                E4778B7F115A581A00B5D372 /* JSCustomEvent.cpp in Sources */ = {isa = PBXBuildFile; fileRef = E4778B7D115A581A00B5D372 /* JSCustomEvent.cpp */; };
                E4778B80115A581A00B5D372 /* JSCustomEvent.h in Headers */ = {isa = PBXBuildFile; fileRef = E4778B7E115A581A00B5D372 /* JSCustomEvent.h */; };
+               E47A3AC31C5EABBE00CCBFA7 /* StyleSharingResolver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = E47A3AC21C5EABBE00CCBFA7 /* StyleSharingResolver.cpp */; };
+               E47A3AC61C5EAC9D00CCBFA7 /* StyleSharingResolver.h in Headers */ = {isa = PBXBuildFile; fileRef = E47A3AC41C5EAC7900CCBFA7 /* StyleSharingResolver.h */; };
                E47B4BE80E71241600038854 /* CachedResourceHandle.h in Headers */ = {isa = PBXBuildFile; fileRef = E47B4BE60E71241600038854 /* CachedResourceHandle.h */; settings = {ATTRIBUTES = (Private, ); }; };
                E47B4BE90E71241600038854 /* CachedResourceHandle.cpp in Sources */ = {isa = PBXBuildFile; fileRef = E47B4BE70E71241600038854 /* CachedResourceHandle.cpp */; };
                E47E276516036ED200EE2AFB /* ExtensionStyleSheets.h in Headers */ = {isa = PBXBuildFile; fileRef = E47E276416036ED200EE2AFB /* ExtensionStyleSheets.h */; settings = {ATTRIBUTES = (Private, ); }; };
                E46A2B1D17CA76B1000DBCD8 /* ElementChildIterator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ElementChildIterator.h; sourceTree = "<group>"; };
                E4778B7D115A581A00B5D372 /* JSCustomEvent.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSCustomEvent.cpp; sourceTree = "<group>"; };
                E4778B7E115A581A00B5D372 /* JSCustomEvent.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSCustomEvent.h; sourceTree = "<group>"; };
+               E47A3AC21C5EABBE00CCBFA7 /* StyleSharingResolver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = StyleSharingResolver.cpp; sourceTree = "<group>"; };
+               E47A3AC41C5EAC7900CCBFA7 /* StyleSharingResolver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StyleSharingResolver.h; sourceTree = "<group>"; };
                E47A97CE163059FC005DCD99 /* StyleInvalidationAnalysis.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = StyleInvalidationAnalysis.cpp; sourceTree = "<group>"; };
                E47A97CF163059FC005DCD99 /* StyleInvalidationAnalysis.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StyleInvalidationAnalysis.h; sourceTree = "<group>"; };
                E47B4BE60E71241600038854 /* CachedResourceHandle.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CachedResourceHandle.h; sourceTree = "<group>"; };
                                E4D58EB317B4DBDC00CBDCA8 /* StyleResolveForDocument.h */,
                                E4DEAA1517A93DC3000E0430 /* StyleTreeResolver.cpp */,
                                E4DEAA1617A93DC3000E0430 /* StyleTreeResolver.h */,
+                               E47A3AC21C5EABBE00CCBFA7 /* StyleSharingResolver.cpp */,
+                               E47A3AC41C5EAC7900CCBFA7 /* StyleSharingResolver.h */,
                        );
                        path = style;
                        sourceTree = "<group>";
                                44A28AAF12DFB8BF00AE923B /* MathMLNames.h in Headers */,
                                439046E012DA25E17BAF80A2 /* MathMLOperatorDictionary.h in Headers */,
                                FA654A6C1108ABED002615E0 /* MathMLTextElement.h in Headers */,
+                               E47A3AC61C5EAC9D00CCBFA7 /* StyleSharingResolver.h in Headers */,
                                49D5DC2C0F423A73008F20FD /* Matrix3DTransformOperation.h in Headers */,
                                49E911C70EF86D47009D0CAF /* MatrixTransformOperation.h in Headers */,
                                5CBC8DAD1AAA302200E1C803 /* MediaAccessibilitySoftLink.h in Headers */,
                                A80E7E9A0A1A83E3007FB8C5 /* JSHTMLOptionElement.cpp in Sources */,
                                448A29C00A46D9CB0030759F /* JSHTMLOptionsCollection.cpp in Sources */,
                                448AD27C0A48137A0023D179 /* JSHTMLOptionsCollectionCustom.cpp in Sources */,
+                               E47A3AC31C5EABBE00CCBFA7 /* StyleSharingResolver.cpp in Sources */,
                                4AD0173C127E82860015035F /* JSHTMLOutputElement.cpp in Sources */,
                                1AE2ABA60A1CE90500B42B25 /* JSHTMLParagraphElement.cpp in Sources */,
                                1AE2ABA80A1CE90500B42B25 /* JSHTMLParamElement.cpp in Sources */,
index 0fdc354..b3f7afb 100644 (file)
@@ -68,7 +68,7 @@ static const StyleProperties& rightToLeftDeclaration()
 
 class MatchRequest {
 public:
-    MatchRequest(RuleSet* ruleSet, bool includeEmptyRules = false)
+    MatchRequest(const RuleSet* ruleSet, bool includeEmptyRules = false)
         : ruleSet(ruleSet)
         , includeEmptyRules(includeEmptyRules)
     {
@@ -529,7 +529,7 @@ void ElementRuleCollector::matchAllRules(bool matchAuthorAndUserStyles, bool inc
     }
 }
 
-bool ElementRuleCollector::hasAnyMatchingRules(RuleSet* ruleSet)
+bool ElementRuleCollector::hasAnyMatchingRules(const RuleSet* ruleSet)
 {
     clearMatchedRules();
 
index b1c3fd4..514d32e 100644 (file)
@@ -58,7 +58,7 @@ public:
     void setRegionForStyling(const RenderRegion* regionForStyling) { m_regionForStyling = regionForStyling; }
     void setMedium(const MediaQueryEvaluator* medium) { m_isPrintStyle = medium->mediaTypeMatchSpecific("print"); }
 
-    bool hasAnyMatchingRules(RuleSet*);
+    bool hasAnyMatchingRules(const RuleSet*);
 
     StyleResolver::MatchResult& matchedResult();
     const Vector<RefPtr<StyleRule>>& matchedRuleList() const;
index f330460..d9c7281 100644 (file)
@@ -85,7 +85,7 @@ std::unique_ptr<MediaQueryEvaluator> MediaQueryMatcher::prepareEvaluator() const
     if (!documentElement)
         return nullptr;
 
-    RefPtr<RenderStyle> rootStyle = m_document->ensureStyleResolver().styleForElement(*documentElement, m_document->renderStyle(), DisallowStyleSharing, MatchOnlyUserAgentRules);
+    RefPtr<RenderStyle> rootStyle = m_document->ensureStyleResolver().styleForElement(*documentElement, m_document->renderStyle(), MatchOnlyUserAgentRules);
 
     return std::make_unique<MediaQueryEvaluator>(mediaType(), m_document->frame(), rootStyle.get());
 }
index 2f66fe7..4f80695 100644 (file)
@@ -61,7 +61,7 @@ bool StyleMedia::matchMedium(const String& query) const
     if (!documentElement)
         return false;
 
-    RefPtr<RenderStyle> rootStyle = document->ensureStyleResolver().styleForElement(*documentElement, document->renderStyle(), DisallowStyleSharing, MatchOnlyUserAgentRules);
+    RefPtr<RenderStyle> rootStyle = document->ensureStyleResolver().styleForElement(*documentElement, document->renderStyle(), MatchOnlyUserAgentRules);
 
     RefPtr<MediaQuerySet> media = MediaQuerySet::create();
     if (!media->parse(query))
index 1ee1de5..bdd7a4b 100644 (file)
@@ -176,8 +176,6 @@ static const CSSPropertyID firstLowPriorityProperty = static_cast<CSSPropertyID>
 
 static void extractDirectionAndWritingMode(const RenderStyle&, const StyleResolver::MatchResult&, TextDirection&, WritingMode&);
 
-RenderStyle* StyleResolver::s_styleNotYetAvailable;
-
 inline void StyleResolver::State::cacheBorderAndBackground()
 {
     m_hasUAAppearance = m_style->hasAppearance();
@@ -264,7 +262,7 @@ StyleResolver::StyleResolver(Document& document)
         m_medium = std::make_unique<MediaQueryEvaluator>("all");
 
     if (root)
-        m_rootDefaultStyle = styleForElement(*root, m_document.renderStyle(), DisallowStyleSharing, MatchOnlyUserAgentRules);
+        m_rootDefaultStyle = styleForElement(*root, m_document.renderStyle(), MatchOnlyUserAgentRules);
 
     if (m_rootDefaultStyle && view)
         m_medium = std::make_unique<MediaQueryEvaluator>(view->mediaType(), &view->frame(), m_rootDefaultStyle.get());
@@ -332,15 +330,6 @@ void StyleResolver::sweepMatchedPropertiesCache()
     m_matchedPropertiesCacheAdditionsSinceLastSweep = 0;
 }
 
-bool StyleResolver::classNamesAffectedByRules(const SpaceSplitString& classNames) const
-{
-    for (unsigned i = 0; i < classNames.size(); ++i) {
-        if (m_ruleSets.features().classesInRules.contains(classNames[i].impl()))
-            return true;
-    }
-    return false;
-}
-
 StyleResolver::State::State(Element& element, RenderStyle* parentStyle, const RenderRegion* regionForStyling, const SelectorFilter* selectorFilter)
     : m_element(&element)
     , m_parentStyle(parentStyle)
@@ -369,305 +358,6 @@ inline void StyleResolver::State::setStyle(Ref<RenderStyle>&& style)
     m_style = WTFMove(style);
     updateConversionData();
 }
-
-static const unsigned cStyleSearchThreshold = 10;
-static const unsigned cStyleSearchLevelThreshold = 10;
-
-static inline bool parentElementPreventsSharing(const Element* parentElement)
-{
-    if (!parentElement)
-        return false;
-    return parentElement->hasFlagsSetDuringStylingOfChildren();
-}
-
-Node* StyleResolver::locateCousinList(Element* parent, unsigned& visitedNodeCount) const
-{
-    if (visitedNodeCount >= cStyleSearchThreshold * cStyleSearchLevelThreshold)
-        return nullptr;
-    if (!is<StyledElement>(parent))
-        return nullptr;
-    StyledElement* styledParent = downcast<StyledElement>(parent);
-    if (styledParent->inlineStyle())
-        return nullptr;
-    if (is<SVGElement>(*styledParent) && downcast<SVGElement>(*styledParent).animatedSMILStyleProperties())
-        return nullptr;
-    if (styledParent->hasID() && m_ruleSets.features().idsInRules.contains(styledParent->idForStyleResolution().impl()))
-        return nullptr;
-
-    RenderStyle* parentStyle = styledParent->renderStyle();
-    unsigned subcount = 0;
-    Node* thisCousin = styledParent;
-    Node* currentNode = styledParent->previousSibling();
-
-    // Reserve the tries for this level. This effectively makes sure that the algorithm
-    // will never go deeper than cStyleSearchLevelThreshold levels into recursion.
-    visitedNodeCount += cStyleSearchThreshold;
-    while (thisCousin) {
-        while (currentNode) {
-            ++subcount;
-            if (currentNode->renderStyle() == parentStyle && currentNode->lastChild()
-                && is<Element>(*currentNode) && !parentElementPreventsSharing(downcast<Element>(currentNode))
-                ) {
-                // Adjust for unused reserved tries.
-                visitedNodeCount -= cStyleSearchThreshold - subcount;
-                return currentNode->lastChild();
-            }
-            if (subcount >= cStyleSearchThreshold)
-                return nullptr;
-            currentNode = currentNode->previousSibling();
-        }
-        currentNode = locateCousinList(thisCousin->parentElement(), visitedNodeCount);
-        thisCousin = currentNode;
-    }
-
-    return nullptr;
-}
-
-bool StyleResolver::styleSharingCandidateMatchesRuleSet(RuleSet* ruleSet)
-{
-    if (!ruleSet)
-        return false;
-
-    ElementRuleCollector collector(*m_state.element(), m_state.style(), m_ruleSets, m_state.selectorFilter());
-    return collector.hasAnyMatchingRules(ruleSet);
-}
-
-bool StyleResolver::canShareStyleWithControl(StyledElement& element) const
-{
-    const State& state = m_state;
-    if (!is<HTMLInputElement>(element) || !is<HTMLInputElement>(*state.element()))
-        return false;
-
-    auto& thisInputElement = downcast<HTMLInputElement>(element);
-    auto& otherInputElement = downcast<HTMLInputElement>(*state.element());
-
-    if (thisInputElement.isAutoFilled() != otherInputElement.isAutoFilled())
-        return false;
-    if (thisInputElement.shouldAppearChecked() != otherInputElement.shouldAppearChecked())
-        return false;
-    if (thisInputElement.shouldAppearIndeterminate() != otherInputElement.shouldAppearIndeterminate())
-        return false;
-    if (thisInputElement.isRequired() != otherInputElement.isRequired())
-        return false;
-
-    if (element.isDisabledFormControl() != state.element()->isDisabledFormControl())
-        return false;
-
-    if (element.isDefaultButtonForForm() != state.element()->isDefaultButtonForForm())
-        return false;
-
-    if (element.isInRange() != state.element()->isInRange())
-        return false;
-
-    if (element.isOutOfRange() != state.element()->isOutOfRange())
-        return false;
-
-    return true;
-}
-
-static inline bool elementHasDirectionAuto(Element& element)
-{
-    // FIXME: This line is surprisingly hot, we may wish to inline hasDirectionAuto into StyleResolver.
-    return is<HTMLElement>(element) && downcast<HTMLElement>(element).hasDirectionAuto();
-}
-
-bool StyleResolver::sharingCandidateHasIdenticalStyleAffectingAttributes(StyledElement& sharingCandidate) const
-{
-    const State& state = m_state;
-    if (state.element()->elementData() == sharingCandidate.elementData())
-        return true;
-    if (state.element()->fastGetAttribute(XMLNames::langAttr) != sharingCandidate.fastGetAttribute(XMLNames::langAttr))
-        return false;
-    if (state.element()->fastGetAttribute(langAttr) != sharingCandidate.fastGetAttribute(langAttr))
-        return false;
-
-    if (!state.elementAffectedByClassRules()) {
-        if (sharingCandidate.hasClass() && classNamesAffectedByRules(sharingCandidate.classNames()))
-            return false;
-    } else if (sharingCandidate.hasClass()) {
-        // SVG elements require a (slow!) getAttribute comparision because "class" is an animatable attribute for SVG.
-        if (state.element()->isSVGElement()) {
-            if (state.element()->getAttribute(classAttr) != sharingCandidate.getAttribute(classAttr))
-                return false;
-        } else {
-            if (state.element()->classNames() != sharingCandidate.classNames())
-                return false;
-        }
-    } else
-        return false;
-
-    if (downcast<StyledElement>(*state.element()).presentationAttributeStyle() != sharingCandidate.presentationAttributeStyle())
-        return false;
-
-    if (state.element()->hasTagName(progressTag)) {
-        if (state.element()->shouldAppearIndeterminate() != sharingCandidate.shouldAppearIndeterminate())
-            return false;
-    }
-
-    return true;
-}
-
-bool StyleResolver::canShareStyleWithElement(StyledElement& element) const
-{
-    auto* style = element.renderStyle();
-    const State& state = m_state;
-
-    if (!style)
-        return false;
-    if (style->unique())
-        return false;
-    if (style->hasUniquePseudoStyle())
-        return false;
-    if (element.tagQName() != state.element()->tagQName())
-        return false;
-    if (element.inlineStyle())
-        return false;
-    if (element.needsStyleRecalc())
-        return false;
-    if (element.isSVGElement() && downcast<SVGElement>(element).animatedSMILStyleProperties())
-        return false;
-    if (element.isLink() != state.element()->isLink())
-        return false;
-    if (element.hovered() != state.element()->hovered())
-        return false;
-    if (element.active() != state.element()->active())
-        return false;
-    if (element.focused() != state.element()->focused())
-        return false;
-    if (element.shadowPseudoId() != state.element()->shadowPseudoId())
-        return false;
-    if (&element == element.document().cssTarget())
-        return false;
-    if (!sharingCandidateHasIdenticalStyleAffectingAttributes(element))
-        return false;
-    if (element.additionalPresentationAttributeStyle() != downcast<StyledElement>(*state.element()).additionalPresentationAttributeStyle())
-        return false;
-    if (element.affectsNextSiblingElementStyle() || element.styleIsAffectedByPreviousSibling())
-        return false;
-
-    if (element.hasID() && m_ruleSets.features().idsInRules.contains(element.idForStyleResolution().impl()))
-        return false;
-
-    bool isControl = is<HTMLFormControlElement>(element);
-
-    if (isControl != is<HTMLFormControlElement>(*state.element()))
-        return false;
-
-    if (isControl && !canShareStyleWithControl(element))
-        return false;
-
-    if (style->transitions() || style->animations())
-        return false;
-
-    // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
-    // See comments in RenderObject::setStyle().
-    if (element.hasTagName(iframeTag) || element.hasTagName(frameTag) || element.hasTagName(embedTag) || element.hasTagName(objectTag) || element.hasTagName(appletTag) || element.hasTagName(canvasTag))
-        return false;
-
-    if (elementHasDirectionAuto(element))
-        return false;
-
-    if (element.isLink() && state.elementLinkState() != style->insideLink())
-        return false;
-
-    if (element.elementData() != state.element()->elementData()) {
-        if (element.fastGetAttribute(readonlyAttr) != state.element()->fastGetAttribute(readonlyAttr))
-            return false;
-        if (element.isSVGElement()) {
-            if (element.getAttribute(typeAttr) != state.element()->getAttribute(typeAttr))
-                return false;
-        } else {
-            if (element.fastGetAttribute(typeAttr) != state.element()->fastGetAttribute(typeAttr))
-                return false;
-        }
-    }
-
-    if (element.matchesValidPseudoClass() != state.element()->matchesValidPseudoClass())
-        return false;
-
-    if (element.matchesInvalidPseudoClass() != state.element()->matchesValidPseudoClass())
-        return false;
-
-#if ENABLE(VIDEO_TRACK)
-    // Deny sharing styles between WebVTT and non-WebVTT nodes.
-    if (is<WebVTTElement>(*state.element()))
-        return false;
-#endif
-
-#if ENABLE(FULLSCREEN_API)
-    if (&element == element.document().webkitCurrentFullScreenElement() || state.element() == state.document().webkitCurrentFullScreenElement())
-        return false;
-#endif
-    return true;
-}
-
-inline StyledElement* StyleResolver::findSiblingForStyleSharing(Node* node, unsigned& count) const
-{
-    for (; node; node = node->previousSibling()) {
-        if (!is<StyledElement>(*node))
-            continue;
-        if (canShareStyleWithElement(downcast<StyledElement>(*node)))
-            break;
-        if (count++ == cStyleSearchThreshold)
-            return nullptr;
-    }
-    return downcast<StyledElement>(node);
-}
-
-RenderStyle* StyleResolver::locateSharedStyle()
-{
-    State& state = m_state;
-    if (!is<StyledElement>(state.element()) || !state.parentStyle())
-        return nullptr;
-    auto& styledElement = downcast<StyledElement>(*state.element());
-
-    // If the element has inline style it is probably unique.
-    if (styledElement.inlineStyle())
-        return nullptr;
-    if (styledElement.isSVGElement() && downcast<SVGElement>(styledElement).animatedSMILStyleProperties())
-        return nullptr;
-    // Ids stop style sharing if they show up in the stylesheets.
-    if (styledElement.hasID() && m_ruleSets.features().idsInRules.contains(styledElement.idForStyleResolution().impl()))
-        return nullptr;
-    if (parentElementPreventsSharing(styledElement.parentElement()))
-        return nullptr;
-    if (state.element() == state.document().cssTarget())
-        return nullptr;
-    if (elementHasDirectionAuto(*state.element()))
-        return nullptr;
-
-    // Cache whether state.element is affected by any known class selectors.
-    // FIXME: This shouldn't be a member variable. The style sharing code could be factored out of StyleResolver.
-    state.setElementAffectedByClassRules(state.element() && state.element()->hasClass() && classNamesAffectedByRules(state.element()->classNames()));
-
-    // Check previous siblings and their cousins.
-    unsigned count = 0;
-    unsigned visitedNodeCount = 0;
-    StyledElement* shareElement = nullptr;
-    Node* cousinList = styledElement.previousSibling();
-    while (cousinList) {
-        shareElement = findSiblingForStyleSharing(cousinList, count);
-        if (shareElement)
-            break;
-        cousinList = locateCousinList(cousinList->parentElement(), visitedNodeCount);
-    }
-
-    // If we have exhausted all our budget or our cousins.
-    if (!shareElement)
-        return nullptr;
-
-    // Can't share if sibling rules apply. This is checked at the end as it should rarely fail.
-    if (styleSharingCandidateMatchesRuleSet(m_ruleSets.sibling()))
-        return nullptr;
-    // Can't share if attribute rules apply.
-    if (styleSharingCandidateMatchesRuleSet(m_ruleSets.uncommonAttribute()))
-        return nullptr;
-    // Tracking child index requires unique style for each node. This may get set by the sibling rule match above.
-    if (parentElementPreventsSharing(styledElement.parentElement()))
-        return nullptr;
-    return shareElement->renderStyle();
-}
-
 static inline bool isAtShadowBoundary(const Element* element)
 {
     if (!element)
@@ -676,33 +366,13 @@ static inline bool isAtShadowBoundary(const Element* element)
     return parentNode && parentNode->isShadowRoot();
 }
 
-Ref<RenderStyle> StyleResolver::styleForElement(Element& element, RenderStyle* parentStyle,
-    StyleSharingBehavior sharingBehavior, RuleMatchingBehavior matchingBehavior, const RenderRegion* regionForStyling, const SelectorFilter* selectorFilter)
+Ref<RenderStyle> StyleResolver::styleForElement(Element& element, RenderStyle* parentStyle, RuleMatchingBehavior matchingBehavior, const RenderRegion* regionForStyling, const SelectorFilter* selectorFilter)
 {
     RELEASE_ASSERT(!m_inLoadPendingImages);
 
-    // Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
-    // will vanish if a style recalc happens during loading.
-    if (sharingBehavior == AllowStyleSharing && !m_document.haveStylesheetsLoaded() && !element.renderer()) {
-        if (!s_styleNotYetAvailable) {
-            s_styleNotYetAvailable = &RenderStyle::create().leakRef();
-            s_styleNotYetAvailable->setDisplay(NONE);
-            s_styleNotYetAvailable->fontCascade().update(&m_document.fontSelector());
-        }
-        m_document.setHasNodesWithPlaceholderStyle();
-        return *s_styleNotYetAvailable;
-    }
-
     m_state = State(element, parentStyle, regionForStyling, selectorFilter);
     State& state = m_state;
 
-    if (sharingBehavior == AllowStyleSharing) {
-        if (RenderStyle* sharedStyle = locateSharedStyle()) {
-            state.clear();
-            return *sharedStyle;
-        }
-    }
-
     if (state.parentStyle()) {
         state.setStyle(RenderStyle::create());
         state.style()->inheritFrom(state.parentStyle(), isAtShadowBoundary(&element) ? RenderStyle::AtShadowBoundary : RenderStyle::NotAtShadowBoundary);
index 8316211..752648b 100644 (file)
@@ -93,11 +93,6 @@ class ViewportStyleResolver;
 class WebKitCSSFilterValue;
 struct ResourceLoaderOptions;
 
-enum StyleSharingBehavior {
-    AllowStyleSharing,
-    DisallowStyleSharing,
-};
-
 // MatchOnlyUserAgentRules is used in media queries, where relative units
 // are interpreted according to the document root element style, and styled only
 // from the User Agent Stylesheet rules.
@@ -135,8 +130,7 @@ public:
     StyleResolver(Document&);
     ~StyleResolver();
 
-    Ref<RenderStyle> styleForElement(Element&, RenderStyle* parentStyle, StyleSharingBehavior = AllowStyleSharing,
-        RuleMatchingBehavior = MatchAllRules, const RenderRegion* regionForStyling = nullptr, const SelectorFilter* = nullptr);
+    Ref<RenderStyle> styleForElement(Element&, RenderStyle* parentStyle, RuleMatchingBehavior = MatchAllRules, const RenderRegion* regionForStyling = nullptr, const SelectorFilter* = nullptr);
 
     void keyframeStylesForAnimation(Element&, const RenderStyle*, KeyframeList&);
 
@@ -160,12 +154,6 @@ public:
     const MediaQueryEvaluator& mediaQueryEvaluator() const { return *m_medium; }
 
 private:
-    RenderStyle* locateSharedStyle();
-    bool styleSharingCandidateMatchesRuleSet(RuleSet*);
-    Node* locateCousinList(Element* parent, unsigned& visitedNodeCount) const;
-    StyledElement* findSiblingForStyleSharing(Node*, unsigned& count) const;
-    bool canShareStyleWithElement(StyledElement&) const;
-
     Ref<RenderStyle> styleForKeyframe(const RenderStyle*, const StyleKeyframe*, KeyframeValue&);
 
 public:
@@ -378,8 +366,6 @@ public:
 
         const RenderRegion* regionForStyling() const { return m_regionForStyling; }
         EInsideLink elementLinkState() const { return m_elementLinkState; }
-        void setElementAffectedByClassRules(bool isAffected) { m_elementAffectedByClassRules = isAffected; }
-        bool elementAffectedByClassRules() const { return m_elementAffectedByClassRules; }
 
         void setApplyPropertyToRegularStyle(bool isApply) { m_applyPropertyToRegularStyle = isApply; }
         void setApplyPropertyToVisitedLinkStyle(bool isApply) { m_applyPropertyToVisitedLinkStyle = isApply; }
@@ -435,7 +421,6 @@ public:
         
         EInsideLink m_elementLinkState { NotInsideLink };
 
-        bool m_elementAffectedByClassRules { false };
         bool m_applyPropertyToRegularStyle { true };
         bool m_applyPropertyToVisitedLinkStyle { false };
         bool m_fontDirty { false };
@@ -459,8 +444,6 @@ public:
 
     State& state() { return m_state; }
 
-    static RenderStyle* styleNotYetAvailable() { return s_styleNotYetAvailable; }
-
     PassRefPtr<StyleImage> styleImage(CSSPropertyID, CSSValue&);
     PassRefPtr<StyleImage> cachedOrPendingFromValue(CSSPropertyID, CSSImageValue&);
     PassRefPtr<StyleImage> generatedOrPendingFromValue(CSSPropertyID, CSSImageGeneratorValue&);
@@ -488,12 +471,8 @@ public:
     void setTextOrientation(TextOrientation textOrientation) { m_state.setTextOrientation(textOrientation); }
 
 private:
-    static RenderStyle* s_styleNotYetAvailable;
-
     void cacheBorderAndBackground();
 
-    bool canShareStyleWithControl(StyledElement&) const;
-
     void applyProperty(CSSPropertyID, CSSValue*, SelectorChecker::LinkMatchMask = SelectorChecker::MatchDefault, const MatchResult* = nullptr);
     RefPtr<CSSValue> resolvedVariableValue(CSSPropertyID, const CSSVariableDependentValue&);
 
@@ -520,9 +499,6 @@ private:
     // the last reference to a style declaration are garbage collected.
     void sweepMatchedPropertiesCache();
 
-    bool classNamesAffectedByRules(const SpaceSplitString&) const;
-    bool sharingCandidateHasIdenticalStyleAffectingAttributes(StyledElement&) const;
-
     unsigned m_matchedPropertiesCacheAdditionsSinceLastSweep;
 
     typedef HashMap<unsigned, MatchedPropertiesCacheItem> MatchedPropertiesCache;
index 586909a..6624d7f 100644 (file)
@@ -41,7 +41,7 @@ namespace WebCore {
 
 using namespace HTMLNames;
 
-inline static const AtomicString* linkAttribute(Element& element)
+inline static const AtomicString* linkAttribute(const Element& element)
 {
     if (!element.isLink())
         return 0;
@@ -67,7 +67,7 @@ void VisitedLinkState::invalidateStyleForAllLinks()
     }
 }
 
-inline static LinkHash linkHashForElement(Document& document, Element& element)
+inline static LinkHash linkHashForElement(Document& document, const Element& element)
 {
     if (is<HTMLAnchorElement>(element))
         return downcast<HTMLAnchorElement>(element).visitedLinkHash();
@@ -86,7 +86,7 @@ void VisitedLinkState::invalidateStyleForLink(LinkHash linkHash)
     }
 }
 
-EInsideLink VisitedLinkState::determineLinkStateSlowCase(Element& element)
+EInsideLink VisitedLinkState::determineLinkStateSlowCase(const Element& element)
 {
     ASSERT(element.isLink());
 
index f6f0db6..976ec15 100644 (file)
@@ -45,16 +45,16 @@ public:
 
     void invalidateStyleForAllLinks();
     void invalidateStyleForLink(LinkHash);
-    EInsideLink determineLinkState(Element&);
+    EInsideLink determineLinkState(const Element&);
 
 private:
-    EInsideLink determineLinkStateSlowCase(Element&);
+    EInsideLink determineLinkStateSlowCase(const Element&);
 
     Document& m_document;
     HashSet<LinkHash, LinkHashHash> m_linksCheckedForVisitedState;
 };
 
-inline EInsideLink VisitedLinkState::determineLinkState(Element& element)
+inline EInsideLink VisitedLinkState::determineLinkState(const Element& element)
 {
     if (!element.isLink())
         return NotInsideLink;
index 331e134..d483b11 100644 (file)
@@ -71,6 +71,7 @@ public:
     void dispatchFormControlInputEvent();
 
     virtual bool isDisabledFormControl() const override;
+    virtual bool isDefaultButtonForForm() const override;
 
     virtual bool isFocusable() const override;
     virtual bool isEnumeratable() const override { return false; }
@@ -168,7 +169,6 @@ private:
     virtual short tabIndex() const override final;
 
     virtual HTMLFormElement* virtualForm() const override;
-    virtual bool isDefaultButtonForForm() const override;
     bool isValidFormControlElement() const;
 
     bool computeIsDisabledByFieldsetAncestor() const;
index da19266..9257044 100644 (file)
@@ -1590,7 +1590,7 @@ PassRefPtr<RenderStyle> RenderElement::getUncachedPseudoStyle(const PseudoStyleR
     auto& styleResolver = element()->styleResolver();
 
     if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
-        RefPtr<RenderStyle> result = styleResolver.styleForElement(*element(), parentStyle, DisallowStyleSharing);
+        RefPtr<RenderStyle> result = styleResolver.styleForElement(*element(), parentStyle);
         result->setStyleType(FIRST_LINE_INHERITED);
         return result.release();
     }
index 131dea5..cda6af5 100644 (file)
@@ -352,7 +352,7 @@ PassRefPtr<RenderStyle> RenderNamedFlowFragment::computeStyleInRegion(RenderElem
     ASSERT(!renderer.isAnonymous());
 
     // FIXME: Region styling fails for pseudo-elements because the renderers don't have a node.
-    RefPtr<RenderStyle> renderObjectRegionStyle = renderer.element()->styleResolver().styleForElement(*renderer.element(), &parentStyle, DisallowStyleSharing, MatchAllRules, this);
+    RefPtr<RenderStyle> renderObjectRegionStyle = renderer.element()->styleResolver().styleForElement(*renderer.element(), &parentStyle, MatchAllRules, this);
 
     return renderObjectRegionStyle.release();
 }
index d80d07f..57f922e 100644 (file)
@@ -42,6 +42,7 @@
 #include "StyleResolver.h"
 #include "StyleScrollSnapPoints.h"
 #include "StyleSelfAlignmentData.h"
+#include "StyleTreeResolver.h"
 #include "WillChangeData.h"
 #include <wtf/MathExtras.h>
 #include <wtf/PointerComparison.h>
@@ -293,7 +294,7 @@ bool RenderStyle::operator==(const RenderStyle& o) const
 
 bool RenderStyle::isStyleAvailable() const
 {
-    return this != StyleResolver::styleNotYetAvailable();
+    return !Style::isPlaceholderStyle(*this);
 }
 
 bool RenderStyle::hasUniquePseudoStyle() const
diff --git a/Source/WebCore/style/StyleSharingResolver.cpp b/Source/WebCore/style/StyleSharingResolver.cpp
new file mode 100644 (file)
index 0000000..a00ba3a
--- /dev/null
@@ -0,0 +1,373 @@
+/*
+ * Copyright (C) 2016 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "StyleSharingResolver.h"
+
+#include "DocumentRuleSets.h"
+#include "ElementRuleCollector.h"
+#include "HTMLInputElement.h"
+#include "HTMLNames.h"
+#include "NodeRenderStyle.h"
+#include "RenderStyle.h"
+#include "SVGElement.h"
+#include "StyledElement.h"
+#include "VisitedLinkState.h"
+#include "WebVTTElement.h"
+#include "XMLNames.h"
+
+namespace WebCore {
+namespace Style {
+
+static const unsigned cStyleSearchThreshold = 10;
+static const unsigned cStyleSearchLevelThreshold = 10;
+
+struct SharingResolver::Context {
+    const StyledElement& element;
+    bool elementAffectedByClassRules;
+    EInsideLink elementLinkState;
+};
+
+SharingResolver::SharingResolver(const Document& document, const DocumentRuleSets& ruleSets, const SelectorFilter& selectorFilter)
+    : m_document(document)
+    , m_ruleSets(ruleSets)
+    , m_selectorFilter(selectorFilter)
+{
+}
+
+static inline bool parentElementPreventsSharing(const Element& parentElement)
+{
+    return parentElement.hasFlagsSetDuringStylingOfChildren();
+}
+
+static inline bool elementHasDirectionAuto(const Element& element)
+{
+    // FIXME: This line is surprisingly hot, we may wish to inline hasDirectionAuto into StyleResolver.
+    return is<HTMLElement>(element) && downcast<HTMLElement>(element).hasDirectionAuto();
+}
+
+const Element* SharingResolver::resolve(const Element& searchElement) const
+{
+    if (!is<StyledElement>(searchElement))
+        return nullptr;
+    auto& element = downcast<StyledElement>(searchElement);
+    if (!element.parentElement())
+        return nullptr;
+    auto& parentElement = *element.parentElement();
+    if (!parentElement.renderStyle())
+        return nullptr;
+    // If the element has inline style it is probably unique.
+    if (element.inlineStyle())
+        return nullptr;
+    if (element.isSVGElement() && downcast<SVGElement>(element).animatedSMILStyleProperties())
+        return nullptr;
+    // Ids stop style sharing if they show up in the stylesheets.
+    if (element.hasID() && m_ruleSets.features().idsInRules.contains(element.idForStyleResolution().impl()))
+        return nullptr;
+    if (parentElementPreventsSharing(parentElement))
+        return nullptr;
+    if (&element == m_document.cssTarget())
+        return nullptr;
+    if (elementHasDirectionAuto(element))
+        return nullptr;
+
+    Context context {
+        element,
+        element.hasClass() && classNamesAffectedByRules(element.classNames()),
+        m_document.visitedLinkState().determineLinkState(element)
+    };
+
+    // Check previous siblings and their cousins.
+    unsigned count = 0;
+    unsigned visitedNodeCount = 0;
+    StyledElement* shareElement = nullptr;
+    Node* cousinList = element.previousSibling();
+    while (cousinList) {
+        shareElement = findSibling(context, cousinList, count);
+        if (shareElement)
+            break;
+        cousinList = locateCousinList(cousinList->parentElement(), visitedNodeCount);
+    }
+
+    // If we have exhausted all our budget or our cousins.
+    if (!shareElement)
+        return nullptr;
+
+    // Can't share if sibling rules apply. This is checked at the end as it should rarely fail.
+    if (styleSharingCandidateMatchesRuleSet(element, m_ruleSets.sibling()))
+        return nullptr;
+    // Can't share if attribute rules apply.
+    if (styleSharingCandidateMatchesRuleSet(element, m_ruleSets.uncommonAttribute()))
+        return nullptr;
+    // Tracking child index requires unique style for each node. This may get set by the sibling rule match above.
+    if (parentElementPreventsSharing(parentElement))
+        return nullptr;
+
+    return shareElement;
+}
+
+StyledElement* SharingResolver::findSibling(const Context& context, Node* node, unsigned& count) const
+{
+    for (; node; node = node->previousSibling()) {
+        if (!is<StyledElement>(*node))
+            continue;
+        if (canShareStyleWithElement(context, downcast<StyledElement>(*node)))
+            break;
+        if (count++ == cStyleSearchThreshold)
+            return nullptr;
+    }
+    return downcast<StyledElement>(node);
+}
+
+Node* SharingResolver::locateCousinList(Element* parent, unsigned& visitedNodeCount) const
+{
+    if (visitedNodeCount >= cStyleSearchThreshold * cStyleSearchLevelThreshold)
+        return nullptr;
+    if (!is<StyledElement>(parent))
+        return nullptr;
+    auto& styledParent = downcast<StyledElement>(*parent);
+    if (styledParent.inlineStyle())
+        return nullptr;
+    if (is<SVGElement>(styledParent) && downcast<SVGElement>(styledParent).animatedSMILStyleProperties())
+        return nullptr;
+    if (styledParent.hasID() && m_ruleSets.features().idsInRules.contains(styledParent.idForStyleResolution().impl()))
+        return nullptr;
+
+    RenderStyle* parentStyle = styledParent.renderStyle();
+    unsigned subcount = 0;
+    Node* thisCousin = &styledParent;
+    Node* currentNode = styledParent.previousSibling();
+
+    // Reserve the tries for this level. This effectively makes sure that the algorithm
+    // will never go deeper than cStyleSearchLevelThreshold levels into recursion.
+    visitedNodeCount += cStyleSearchThreshold;
+    while (thisCousin) {
+        for (; currentNode; currentNode = currentNode->previousSibling()) {
+            if (++subcount > cStyleSearchThreshold)
+                return nullptr;
+            if (!is<Element>(*currentNode))
+                continue;
+            auto& currentElement = downcast<Element>(*currentNode);
+            if (currentElement.renderStyle() != parentStyle)
+                continue;
+            if (!currentElement.lastChild())
+                continue;
+            if (!parentElementPreventsSharing(currentElement)) {
+                // Adjust for unused reserved tries.
+                visitedNodeCount -= cStyleSearchThreshold - subcount;
+                return currentNode->lastChild();
+            }
+        }
+        currentNode = locateCousinList(thisCousin->parentElement(), visitedNodeCount);
+        thisCousin = currentNode;
+    }
+
+    return nullptr;
+}
+
+static bool canShareStyleWithControl(const HTMLFormControlElement& element, const HTMLFormControlElement& formElement)
+{
+    if (!is<HTMLInputElement>(formElement) || !is<HTMLInputElement>(element))
+        return false;
+
+    auto& thisInputElement = downcast<HTMLInputElement>(formElement);
+    auto& otherInputElement = downcast<HTMLInputElement>(element);
+
+    if (thisInputElement.isAutoFilled() != otherInputElement.isAutoFilled())
+        return false;
+    if (thisInputElement.shouldAppearChecked() != otherInputElement.shouldAppearChecked())
+        return false;
+    if (thisInputElement.shouldAppearIndeterminate() != otherInputElement.shouldAppearIndeterminate())
+        return false;
+    if (thisInputElement.isRequired() != otherInputElement.isRequired())
+        return false;
+
+    if (formElement.isDisabledFormControl() != element.isDisabledFormControl())
+        return false;
+
+    if (formElement.isDefaultButtonForForm() != element.isDefaultButtonForForm())
+        return false;
+
+    if (formElement.isInRange() != element.isInRange())
+        return false;
+
+    if (formElement.isOutOfRange() != element.isOutOfRange())
+        return false;
+
+    return true;
+}
+
+bool SharingResolver::canShareStyleWithElement(const Context& context, const StyledElement& candidateElement) const
+{
+    auto& element = context.element;
+    auto* style = candidateElement.renderStyle();
+    if (!style)
+        return false;
+    if (style->unique())
+        return false;
+    if (style->hasUniquePseudoStyle())
+        return false;
+    if (candidateElement.tagQName() != element.tagQName())
+        return false;
+    if (candidateElement.inlineStyle())
+        return false;
+    if (candidateElement.needsStyleRecalc())
+        return false;
+    if (candidateElement.isSVGElement() && downcast<SVGElement>(candidateElement).animatedSMILStyleProperties())
+        return false;
+    if (candidateElement.isLink() != element.isLink())
+        return false;
+    if (candidateElement.hovered() != element.hovered())
+        return false;
+    if (candidateElement.active() != element.active())
+        return false;
+    if (candidateElement.focused() != element.focused())
+        return false;
+    if (candidateElement.shadowPseudoId() != element.shadowPseudoId())
+        return false;
+    if (&candidateElement == m_document.cssTarget())
+        return false;
+    if (!sharingCandidateHasIdenticalStyleAffectingAttributes(context, candidateElement))
+        return false;
+    if (const_cast<StyledElement&>(candidateElement).additionalPresentationAttributeStyle() != const_cast<StyledElement&>(element).additionalPresentationAttributeStyle())
+        return false;
+    if (candidateElement.affectsNextSiblingElementStyle() || candidateElement.styleIsAffectedByPreviousSibling())
+        return false;
+
+    if (candidateElement.hasID() && m_ruleSets.features().idsInRules.contains(candidateElement.idForStyleResolution().impl()))
+        return false;
+
+    bool isControl = is<HTMLFormControlElement>(candidateElement);
+
+    if (isControl != is<HTMLFormControlElement>(element))
+        return false;
+
+    if (isControl && !canShareStyleWithControl(downcast<HTMLFormControlElement>(element), downcast<HTMLFormControlElement>(candidateElement)))
+        return false;
+
+    if (style->transitions() || style->animations())
+        return false;
+
+    // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
+    // See comments in RenderObject::setStyle().
+    if (candidateElement.hasTagName(HTMLNames::iframeTag) || candidateElement.hasTagName(HTMLNames::frameTag))
+        return false;
+
+    if (candidateElement.hasTagName(HTMLNames::embedTag) || candidateElement.hasTagName(HTMLNames::objectTag) || candidateElement.hasTagName(HTMLNames::appletTag) || candidateElement.hasTagName(HTMLNames::canvasTag))
+        return false;
+
+    if (elementHasDirectionAuto(candidateElement))
+        return false;
+
+    if (candidateElement.isLink() && context.elementLinkState != style->insideLink())
+        return false;
+
+    if (candidateElement.elementData() != element.elementData()) {
+        if (candidateElement.fastGetAttribute(HTMLNames::readonlyAttr) != element.fastGetAttribute(HTMLNames::readonlyAttr))
+            return false;
+        if (candidateElement.isSVGElement()) {
+            if (candidateElement.getAttribute(HTMLNames::typeAttr) != element.getAttribute(HTMLNames::typeAttr))
+                return false;
+        } else {
+            if (candidateElement.fastGetAttribute(HTMLNames::typeAttr) != element.fastGetAttribute(HTMLNames::typeAttr))
+                return false;
+        }
+    }
+
+    if (candidateElement.matchesValidPseudoClass() != element.matchesValidPseudoClass())
+        return false;
+
+    if (element.matchesInvalidPseudoClass() != element.matchesValidPseudoClass())
+        return false;
+
+#if ENABLE(VIDEO_TRACK)
+    // Deny sharing styles between WebVTT and non-WebVTT nodes.
+    if (is<WebVTTElement>(element))
+        return false;
+#endif
+
+#if ENABLE(FULLSCREEN_API)
+    if (&element == m_document.webkitCurrentFullScreenElement() || &element == m_document.webkitCurrentFullScreenElement())
+        return false;
+#endif
+    return true;
+}
+
+bool SharingResolver::styleSharingCandidateMatchesRuleSet(const StyledElement& element, const RuleSet* ruleSet) const
+{
+    if (!ruleSet)
+        return false;
+
+    ElementRuleCollector collector(const_cast<StyledElement&>(element), nullptr, m_ruleSets, &m_selectorFilter);
+    return collector.hasAnyMatchingRules(ruleSet);
+}
+
+bool SharingResolver::sharingCandidateHasIdenticalStyleAffectingAttributes(const Context& context, const StyledElement& sharingCandidate) const
+{
+    auto& element = context.element;
+    if (element.elementData() == sharingCandidate.elementData())
+        return true;
+    if (element.fastGetAttribute(XMLNames::langAttr) != sharingCandidate.fastGetAttribute(XMLNames::langAttr))
+        return false;
+    if (element.fastGetAttribute(HTMLNames::langAttr) != sharingCandidate.fastGetAttribute(HTMLNames::langAttr))
+        return false;
+
+    if (context.elementAffectedByClassRules) {
+        if (!sharingCandidate.hasClass())
+            return false;
+        // SVG elements require a (slow!) getAttribute comparision because "class" is an animatable attribute for SVG.
+        if (element.isSVGElement()) {
+            if (element.getAttribute(HTMLNames::classAttr) != sharingCandidate.getAttribute(HTMLNames::classAttr))
+                return false;
+        } else {
+            if (element.classNames() != sharingCandidate.classNames())
+                return false;
+        }
+    } else if (sharingCandidate.hasClass() && classNamesAffectedByRules(sharingCandidate.classNames()))
+        return false;
+
+    if (const_cast<StyledElement&>(element).presentationAttributeStyle() != const_cast<StyledElement&>(sharingCandidate).presentationAttributeStyle())
+        return false;
+
+    if (element.hasTagName(HTMLNames::progressTag)) {
+        if (element.shouldAppearIndeterminate() != sharingCandidate.shouldAppearIndeterminate())
+            return false;
+    }
+
+    return true;
+}
+
+bool SharingResolver::classNamesAffectedByRules(const SpaceSplitString& classNames) const
+{
+    for (unsigned i = 0; i < classNames.size(); ++i) {
+        if (m_ruleSets.features().classesInRules.contains(classNames[i].impl()))
+            return true;
+    }
+    return false;
+}
+
+
+}
+}
diff --git a/Source/WebCore/style/StyleSharingResolver.h b/Source/WebCore/style/StyleSharingResolver.h
new file mode 100644 (file)
index 0000000..8dcef27
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2016 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef StyleSharingResolver_h
+#define StyleSharingResolver_h
+
+namespace WebCore {
+
+class Document;
+class DocumentRuleSets;
+class Element;
+class Node;
+class RuleSet;
+class SelectorFilter;
+class SpaceSplitString;
+class StyledElement;
+
+namespace Style {
+
+class SharingResolver {
+public:
+    SharingResolver(const Document&, const DocumentRuleSets&, const SelectorFilter&);
+
+    const Element* resolve(const Element&) const;
+
+private:
+    struct Context;
+
+    StyledElement* findSibling(const Context&, Node*, unsigned& count) const;
+    Node* locateCousinList(Element* parent, unsigned& visitedNodeCount) const;
+    bool canShareStyleWithElement(const Context&, const StyledElement& candidateElement) const;
+    bool styleSharingCandidateMatchesRuleSet(const StyledElement&, const RuleSet*) const;
+    bool sharingCandidateHasIdenticalStyleAffectingAttributes(const Context&, const StyledElement& sharingCandidate) const;
+    bool classNamesAffectedByRules(const SpaceSplitString& classNames) const;
+
+    const Document& m_document;
+    const DocumentRuleSets& m_ruleSets;
+    const SelectorFilter& m_selectorFilter;
+};
+
+}
+}
+
+#endif
index c1ba962..e2fd37f 100644 (file)
@@ -96,10 +96,24 @@ private:
     bool m_didPush { false };
 };
 
+
+static RenderStyle* placeholderStyle;
+
+static void ensurePlaceholderStyle(Document& document)
+{
+    if (placeholderStyle)
+        return;
+    placeholderStyle = &RenderStyle::create().leakRef();
+    placeholderStyle->setDisplay(NONE);
+    placeholderStyle->fontCascade().update(&document.fontSelector());
+}
+
 TreeResolver::TreeResolver(Document& document)
     : m_document(document)
     , m_styleResolver(document.ensureStyleResolver())
+    , m_sharingResolver(document, m_styleResolver.ruleSets(), m_selectorFilter)
 {
+    ensurePlaceholderStyle(document);
 }
 
 TreeResolver::TreeResolver(ShadowRoot& shadowRoot, TreeResolver& shadowHostTreeResolver)
@@ -107,6 +121,7 @@ TreeResolver::TreeResolver(ShadowRoot& shadowRoot, TreeResolver& shadowHostTreeR
     , m_styleResolver(shadowRoot.styleResolver())
     , m_shadowRoot(&shadowRoot)
     , m_shadowHostTreeResolver(&shadowHostTreeResolver)
+    , m_sharingResolver(m_document, m_styleResolver.ruleSets(), m_selectorFilter)
 {
 }
 
@@ -123,11 +138,20 @@ static bool shouldCreateRenderer(const Element& element, const RenderElement& pa
 
 Ref<RenderStyle> TreeResolver::styleForElement(Element& element, RenderStyle& inheritedStyle)
 {
+    if (!m_document.haveStylesheetsLoaded() && !element.renderer()) {
+        m_document.setHasNodesWithPlaceholderStyle();
+        return *placeholderStyle;
+    }
+
     if (element.hasCustomStyleResolveCallbacks()) {
         if (RefPtr<RenderStyle> style = element.customStyleForRenderer(inheritedStyle))
             return style.releaseNonNull();
     }
-    return m_styleResolver.styleForElement(element, &inheritedStyle, AllowStyleSharing, MatchAllRules, nullptr, &m_selectorFilter);
+
+    if (auto* sharingElement = m_sharingResolver.resolve(element))
+        return *sharingElement->renderStyle();
+
+    return m_styleResolver.styleForElement(element, &inheritedStyle, MatchAllRules, nullptr, &m_selectorFilter);
 }
 
 #if ENABLE(CSS_REGIONS)
@@ -948,5 +972,10 @@ bool postResolutionCallbacksAreSuspended()
     return resolutionNestingDepth;
 }
 
+bool isPlaceholderStyle(const RenderStyle& style)
+{
+    return &style == placeholderStyle;
+}
+
 }
 }
index 624f9f9..fc3e416 100644 (file)
@@ -29,6 +29,7 @@
 #include "RenderStyleConstants.h"
 #include "SelectorFilter.h"
 #include "StyleChange.h"
+#include "StyleSharingResolver.h"
 #include <functional>
 #include <wtf/RefPtr.h>
 
@@ -85,6 +86,7 @@ private:
     TreeResolver* m_shadowHostTreeResolver { nullptr };
 
     SelectorFilter m_selectorFilter;
+    SharingResolver m_sharingResolver;
 };
 
 void detachRenderTree(Element&);
@@ -95,6 +97,8 @@ void updateTextRendererAfterContentChange(Text&, unsigned offsetOfReplacedData,
 void queuePostResolutionCallback(std::function<void ()>);
 bool postResolutionCallbacksAreSuspended();
 
+bool isPlaceholderStyle(const RenderStyle&);
+
 class PostResolutionCallbackDisabler {
 public:
     explicit PostResolutionCallbackDisabler(Document&);
index f8763a6..aa587ad 100644 (file)
@@ -793,7 +793,7 @@ RefPtr<RenderStyle> SVGElement::customStyleForRenderer(RenderStyle& parentStyle)
 {
     // If the element is in a <use> tree we get the style from the definition tree.
     if (auto* styleElement = this->correspondingElement())
-        return styleElement->styleResolver().styleForElement(*styleElement, &parentStyle, DisallowStyleSharing);
+        return styleElement->styleResolver().styleForElement(*styleElement, &parentStyle);
 
     return resolveStyle(&parentStyle);
 }
index c909b88..805e3e0 100644 (file)
@@ -71,7 +71,7 @@ public:
             return 0;
         if (!m_overrideComputedStyle || m_needsOverrideComputedStyleUpdate) {
             // The style computed here contains no CSS Animations/Transitions or SMIL induced rules - this is needed to compute the "base value" for the SMIL animation sandwhich model.
-            m_overrideComputedStyle = element.styleResolver().styleForElement(element, parentStyle, DisallowStyleSharing, MatchAllRulesExcludingSMIL);
+            m_overrideComputedStyle = element.styleResolver().styleForElement(element, parentStyle, MatchAllRulesExcludingSMIL);
             m_needsOverrideComputedStyleUpdate = false;
         }
         ASSERT(m_overrideComputedStyle);