Web Inspector: Native Memory Instrumentation: fix instrumentation for already instrum...
[WebKit-https.git] / Source / WebCore / css / RuleSet.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
4  * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
5  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
6  * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
7  * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
8  * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
9  * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
10  * Copyright (C) Research In Motion Limited 2011. All rights reserved.
11  * Copyright (C) 2012 Google Inc. All rights reserved.
12  *
13  * This library is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU Library General Public
15  * License as published by the Free Software Foundation; either
16  * version 2 of the License, or (at your option) any later version.
17  *
18  * This library is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21  * Library General Public License for more details.
22  *
23  * You should have received a copy of the GNU Library General Public License
24  * along with this library; see the file COPYING.LIB.  If not, write to
25  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26  * Boston, MA 02110-1301, USA.
27  */
28
29 #include "config.h"
30 #include "RuleSet.h"
31
32 #include "CSSFontSelector.h"
33 #include "CSSSelector.h"
34 #include "CSSSelectorList.h"
35 #include "HTMLNames.h"
36 #include "MediaQueryEvaluator.h"
37 #include "SecurityOrigin.h"
38 #include "SelectorChecker.h"
39 #include "SelectorFilter.h"
40 #include "StyleResolver.h"
41 #include "StyleRule.h"
42 #include "StyleRuleImport.h"
43 #include "StyleSheetContents.h"
44 #include "WebCoreMemoryInstrumentation.h"
45 #include "WebKitCSSKeyframesRule.h"
46 #include <wtf/MemoryInstrumentationHashMap.h>
47 #include <wtf/MemoryInstrumentationHashSet.h>
48 #include <wtf/MemoryInstrumentationVector.h>
49
50 namespace WebCore {
51
52 using namespace HTMLNames;
53
54 // -----------------------------------------------------------------
55
56 static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector* selector)
57 {
58     const AtomicString& selectorNamespace = selector->tag().namespaceURI();
59     if (selectorNamespace != starAtom && selectorNamespace != xhtmlNamespaceURI)
60         return false;
61     if (selector->m_match == CSSSelector::None)
62         return true;
63     if (selector->tag() != starAtom)
64         return false;
65     if (SelectorChecker::isCommonPseudoClassSelector(selector))
66         return true;
67     return selector->m_match == CSSSelector::Id || selector->m_match == CSSSelector::Class;
68 }
69
70 static inline bool selectorListContainsUncommonAttributeSelector(const CSSSelector* selector)
71 {
72     CSSSelectorList* selectorList = selector->selectorList();
73     if (!selectorList)
74         return false;
75     for (CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
76         if (subSelector->isAttributeSelector())
77             return true;
78     }
79     return false;
80 }
81
82 static inline bool isCommonAttributeSelectorAttribute(const QualifiedName& attribute)
83 {
84     // These are explicitly tested for equality in canShareStyleWithElement.
85     return attribute == typeAttr || attribute == readonlyAttr;
86 }
87
88 static inline bool containsUncommonAttributeSelector(const CSSSelector* selector)
89 {
90     for (; selector; selector = selector->tagHistory()) {
91         // Allow certain common attributes (used in the default style) in the selectors that match the current element.
92         if (selector->isAttributeSelector() && !isCommonAttributeSelectorAttribute(selector->attribute()))
93             return true;
94         if (selectorListContainsUncommonAttributeSelector(selector))
95             return true;
96         if (selector->relation() != CSSSelector::SubSelector) {
97             selector = selector->tagHistory();
98             break;
99         }
100     }
101
102     for (; selector; selector = selector->tagHistory()) {
103         if (selector->isAttributeSelector())
104             return true;
105         if (selectorListContainsUncommonAttributeSelector(selector))
106             return true;
107     }
108     return false;
109 }
110
111 RuleData::RuleData(StyleRule* rule, unsigned selectorIndex, unsigned position, AddRuleFlags addRuleFlags)
112     : m_rule(rule)
113     , m_selectorIndex(selectorIndex)
114     , m_position(position)
115     , m_specificity(selector()->specificity())
116     , m_hasFastCheckableSelector((addRuleFlags & RuleCanUseFastCheckSelector) && SelectorChecker::isFastCheckableSelector(selector()))
117     , m_hasMultipartSelector(!!selector()->tagHistory())
118     , m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash(isSelectorMatchingHTMLBasedOnRuleHash(selector()))
119     , m_containsUncommonAttributeSelector(WebCore::containsUncommonAttributeSelector(selector()))
120     , m_linkMatchType(SelectorChecker::determineLinkMatchType(selector()))
121     , m_hasDocumentSecurityOrigin(addRuleFlags & RuleHasDocumentSecurityOrigin)
122     , m_isInRegionRule(!!(addRuleFlags & RuleIsInRegionRule))
123 {
124     ASSERT(m_position == position);
125     ASSERT(m_selectorIndex == selectorIndex);
126     SelectorFilter::collectIdentifierHashes(selector(), m_descendantSelectorIdentifierHashes, maximumIdentifierCount);
127 }
128
129 void RuleData::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
130 {
131     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
132     info.addMember(m_rule);
133 }
134
135 static void reportAtomRuleMap(MemoryClassInfo* info, const RuleSet::AtomRuleMap& atomicRuleMap)
136 {
137     info->addMember(atomicRuleMap);
138     for (RuleSet::AtomRuleMap::const_iterator it = atomicRuleMap.begin(); it != atomicRuleMap.end(); ++it)
139         info->addMember(*it->value);
140 }
141
142 void RuleSet::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
143 {
144     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
145     reportAtomRuleMap(&info, m_idRules);
146     reportAtomRuleMap(&info, m_classRules);
147     reportAtomRuleMap(&info, m_tagRules);
148     reportAtomRuleMap(&info, m_shadowPseudoElementRules);
149     info.addMember(m_linkPseudoClassRules);
150 #if ENABLE(VIDEO_TRACK)
151     info.addMember(m_cuePseudoRules);
152 #endif
153     info.addMember(m_focusPseudoClassRules);
154     info.addMember(m_universalRules);
155     info.addMember(m_pageRules);
156     info.addMember(m_regionSelectorsAndRuleSets);
157     info.addMember(m_features);
158 }
159
160 void RuleSet::RuleSetSelectorPair::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
161 {
162     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
163     info.addMember(ruleSet);
164     info.addMember(selector);
165 }
166
167 static void collectFeaturesFromRuleData(RuleFeatureSet& features, const RuleData& ruleData)
168 {
169     bool foundSiblingSelector = false;
170     for (CSSSelector* selector = ruleData.selector(); selector; selector = selector->tagHistory()) {
171         features.collectFeaturesFromSelector(selector);
172         
173         if (CSSSelectorList* selectorList = selector->selectorList()) {
174             for (CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
175                 if (!foundSiblingSelector && selector->isSiblingSelector())
176                     foundSiblingSelector = true;
177                 features.collectFeaturesFromSelector(subSelector);
178             }
179         } else if (!foundSiblingSelector && selector->isSiblingSelector())
180             foundSiblingSelector = true;
181     }
182     if (foundSiblingSelector)
183         features.siblingRules.append(RuleFeature(ruleData.rule(), ruleData.selectorIndex(), ruleData.hasDocumentSecurityOrigin()));
184     if (ruleData.containsUncommonAttributeSelector())
185         features.uncommonAttributeRules.append(RuleFeature(ruleData.rule(), ruleData.selectorIndex(), ruleData.hasDocumentSecurityOrigin()));
186 }
187     
188 void RuleSet::addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map, const RuleData& ruleData)
189 {
190     if (!key)
191         return;
192     OwnPtr<Vector<RuleData> >& rules = map.add(key, nullptr).iterator->value;
193     if (!rules)
194         rules = adoptPtr(new Vector<RuleData>);
195     rules->append(ruleData);
196 }
197
198 void RuleSet::addRule(StyleRule* rule, unsigned selectorIndex, AddRuleFlags addRuleFlags)
199 {
200     RuleData ruleData(rule, selectorIndex, m_ruleCount++, addRuleFlags);
201
202     collectFeaturesFromRuleData(m_features, ruleData);
203
204     CSSSelector* selector = ruleData.selector();
205
206     if (selector->m_match == CSSSelector::Id) {
207         addToRuleSet(selector->value().impl(), m_idRules, ruleData);
208         return;
209     }
210     if (selector->m_match == CSSSelector::Class) {
211         addToRuleSet(selector->value().impl(), m_classRules, ruleData);
212         return;
213     }
214     if (selector->isCustomPseudoElement()) {
215         addToRuleSet(selector->value().impl(), m_shadowPseudoElementRules, ruleData);
216         return;
217     }
218 #if ENABLE(VIDEO_TRACK)
219     if (selector->pseudoType() == CSSSelector::PseudoCue) {
220         m_cuePseudoRules.append(ruleData);
221         return;
222     }
223 #endif
224     if (SelectorChecker::isCommonPseudoClassSelector(selector)) {
225         switch (selector->pseudoType()) {
226         case CSSSelector::PseudoLink:
227         case CSSSelector::PseudoVisited:
228         case CSSSelector::PseudoAnyLink:
229             m_linkPseudoClassRules.append(ruleData);
230             return;
231         case CSSSelector::PseudoFocus:
232             m_focusPseudoClassRules.append(ruleData);
233             return;
234         default:
235             ASSERT_NOT_REACHED();
236         }
237         return;
238     }
239     const AtomicString& localName = selector->tag().localName();
240     if (localName != starAtom) {
241         addToRuleSet(localName.impl(), m_tagRules, ruleData);
242         return;
243     }
244     m_universalRules.append(ruleData);
245 }
246
247 void RuleSet::addPageRule(StyleRulePage* rule)
248 {
249     m_pageRules.append(rule);
250 }
251
252 void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin)
253 {
254     OwnPtr<RuleSet> regionRuleSet = RuleSet::create();
255     // The region rule set should take into account the position inside the parent rule set.
256     // Otherwise, the rules inside region block might be incorrectly positioned before other similar rules from
257     // the stylesheet that contains the region block.
258     regionRuleSet->m_ruleCount = m_ruleCount;
259
260     // Collect the region rules into a rule set
261     const Vector<RefPtr<StyleRuleBase> >& childRules = regionRule->childRules();
262     AddRuleFlags addRuleFlags = hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState;
263     addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleCanUseFastCheckSelector | RuleIsInRegionRule);
264     for (unsigned i = 0; i < childRules.size(); ++i) {
265         StyleRuleBase* regionStylingRule = childRules[i].get();
266         if (regionStylingRule->isStyleRule())
267             regionRuleSet->addStyleRule(static_cast<StyleRule*>(regionStylingRule), addRuleFlags);
268     }
269     // Update the "global" rule count so that proper order is maintained
270     m_ruleCount = regionRuleSet->m_ruleCount;
271
272     m_regionSelectorsAndRuleSets.append(RuleSetSelectorPair(regionRule->selectorList().first(), regionRuleSet.release()));
273 }
274
275 void RuleSet::addRulesFromSheet(StyleSheetContents* sheet, const MediaQueryEvaluator& medium, StyleResolver* resolver, const ContainerNode* scope)
276 {
277     ASSERT(sheet);
278     
279     const Vector<RefPtr<StyleRuleImport> >& importRules = sheet->importRules();
280     for (unsigned i = 0; i < importRules.size(); ++i) {
281         StyleRuleImport* importRule = importRules[i].get();
282         if (importRule->styleSheet() && (!importRule->mediaQueries() || medium.eval(importRule->mediaQueries(), resolver)))
283             addRulesFromSheet(importRule->styleSheet(), medium, resolver, scope);
284     }
285     bool hasDocumentSecurityOrigin = resolver && resolver->document()->securityOrigin()->canRequest(sheet->baseURL());
286     AddRuleFlags addRuleFlags = static_cast<AddRuleFlags>((hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : 0) | (!scope ? RuleCanUseFastCheckSelector : 0));
287
288     const Vector<RefPtr<StyleRuleBase> >& rules = sheet->childRules();
289     for (unsigned i = 0; i < rules.size(); ++i) {
290         StyleRuleBase* rule = rules[i].get();
291
292         ASSERT(!rule->isImportRule());
293         if (rule->isStyleRule())
294             addStyleRule(static_cast<StyleRule*>(rule), addRuleFlags);
295         else if (rule->isPageRule())
296             addPageRule(static_cast<StyleRulePage*>(rule));
297         else if (rule->isMediaRule()) {
298             StyleRuleMedia* mediaRule = static_cast<StyleRuleMedia*>(rule);
299
300             if ((!mediaRule->mediaQueries() || medium.eval(mediaRule->mediaQueries(), resolver))) {
301                 // Traverse child elements of the @media rule.
302                 const Vector<RefPtr<StyleRuleBase> >& childRules = mediaRule->childRules();
303                 for (unsigned j = 0; j < childRules.size(); ++j) {
304                     StyleRuleBase* childRule = childRules[j].get();
305                     if (childRule->isStyleRule())
306                         addStyleRule(static_cast<StyleRule*>(childRule), addRuleFlags);
307                     else if (childRule->isPageRule())
308                         addPageRule(static_cast<StyleRulePage*>(childRule));
309                     else if (childRule->isFontFaceRule() && resolver) {
310                         // Add this font face to our set.
311                         // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
312                         if (scope)
313                             continue;
314                         const StyleRuleFontFace* fontFaceRule = static_cast<StyleRuleFontFace*>(childRule);
315                         resolver->fontSelector()->addFontFaceRule(fontFaceRule);
316                         resolver->invalidateMatchedPropertiesCache();
317                     } else if (childRule->isKeyframesRule() && resolver) {
318                         // Add this keyframe rule to our set.
319                         // FIXME(BUG 72462): We don't add @keyframe rules of scoped style sheets for the moment.
320                         if (scope)
321                             continue;
322                         resolver->addKeyframeStyle(static_cast<StyleRuleKeyframes*>(childRule));
323                     } else if (childRule->isRegionRule() && resolver) {
324                         // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment.
325                         if (scope)
326                             continue;
327                         addRegionRule(static_cast<StyleRuleRegion*>(childRule), hasDocumentSecurityOrigin);
328                     }
329 #if ENABLE(CSS_DEVICE_ADAPTATION)
330                     else if (childRule->isViewportRule() && resolver && !resolver->affectedByViewportChange()) {
331                         // @viewport should not be scoped.
332                         if (scope)
333                             continue;
334                         resolver->viewportStyleResolver()->addViewportRule(static_cast<StyleRuleViewport*>(childRule));
335                     }
336 #endif
337                 } // for rules
338             } // if rules
339         } else if (rule->isFontFaceRule() && resolver) {
340             // Add this font face to our set.
341             // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
342             if (scope)
343                 continue;
344             const StyleRuleFontFace* fontFaceRule = static_cast<StyleRuleFontFace*>(rule);
345             resolver->fontSelector()->addFontFaceRule(fontFaceRule);
346             resolver->invalidateMatchedPropertiesCache();
347         } else if (rule->isKeyframesRule() && resolver) {
348             // FIXME (BUG 72462): We don't add @keyframe rules of scoped style sheets for the moment.
349             if (scope)
350                 continue;
351             resolver->addKeyframeStyle(static_cast<StyleRuleKeyframes*>(rule));
352         }
353 #if ENABLE(CSS_REGIONS)
354         else if (rule->isRegionRule() && resolver) {
355             // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment.
356             if (scope)
357                 continue;
358             addRegionRule(static_cast<StyleRuleRegion*>(rule), hasDocumentSecurityOrigin);
359         }
360 #endif
361 #if ENABLE(SHADOW_DOM)
362         else if (rule->isHostRule())
363             resolver->addHostRule(static_cast<StyleRuleHost*>(rule), hasDocumentSecurityOrigin, scope);
364 #endif
365 #if ENABLE(CSS_DEVICE_ADAPTATION)
366         else if (rule->isViewportRule() && resolver) {
367             // @viewport should not be scoped.
368             if (scope)
369                 continue;
370             resolver->viewportStyleResolver()->addViewportRule(static_cast<StyleRuleViewport*>(rule));
371         }
372 #endif
373     }
374     if (m_autoShrinkToFitEnabled)
375         shrinkToFit();
376 }
377
378 void RuleSet::addStyleRule(StyleRule* rule, AddRuleFlags addRuleFlags)
379 {
380     for (size_t selectorIndex = 0; selectorIndex != notFound; selectorIndex = rule->selectorList().indexOfNextSelectorAfter(selectorIndex))
381         addRule(rule, selectorIndex, addRuleFlags);
382 }
383
384 static inline void shrinkMapVectorsToFit(RuleSet::AtomRuleMap& map)
385 {
386     RuleSet::AtomRuleMap::iterator end = map.end();
387     for (RuleSet::AtomRuleMap::iterator it = map.begin(); it != end; ++it)
388         it->value->shrinkToFit();
389 }
390
391 void RuleSet::shrinkToFit()
392 {
393     shrinkMapVectorsToFit(m_idRules);
394     shrinkMapVectorsToFit(m_classRules);
395     shrinkMapVectorsToFit(m_tagRules);
396     shrinkMapVectorsToFit(m_shadowPseudoElementRules);
397     m_linkPseudoClassRules.shrinkToFit();
398 #if ENABLE(VIDEO_TRACK)
399     m_cuePseudoRules.shrinkToFit();
400 #endif
401     m_focusPseudoClassRules.shrinkToFit();
402     m_universalRules.shrinkToFit();
403     m_pageRules.shrinkToFit();
404 }
405
406 } // namespace WebCore