Merge from Chromium at DEPS revision r210036

This commit was generated by merge_to_master.py.

Change-Id: Ib2112ed87a48d7a6d9c0563ba71850716d1475ef
diff --git a/Source/core/css/CSSAspectRatioValue.cpp b/Source/core/css/CSSAspectRatioValue.cpp
index 2f6c463..bced41f 100644
--- a/Source/core/css/CSSAspectRatioValue.cpp
+++ b/Source/core/css/CSSAspectRatioValue.cpp
@@ -30,7 +30,6 @@
 #include "core/css/CSSAspectRatioValue.h"
 
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSAspectRatioValue.h b/Source/core/css/CSSAspectRatioValue.h
index 4d640ca..a9c5cc2 100644
--- a/Source/core/css/CSSAspectRatioValue.h
+++ b/Source/core/css/CSSAspectRatioValue.h
@@ -29,7 +29,6 @@
 #ifndef CSSAspectRatioValue_h
 #define CSSAspectRatioValue_h
 
-#include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSValue.h"
 
 namespace WebCore {
diff --git a/Source/core/css/CSSBorderImage.h b/Source/core/css/CSSBorderImage.h
index f6c2f37..bdf13fe 100644
--- a/Source/core/css/CSSBorderImage.h
+++ b/Source/core/css/CSSBorderImage.h
@@ -22,8 +22,7 @@
 
 #include "core/css/CSSBorderImageSliceValue.h"
 #include "core/css/CSSValueList.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSComputedStyleDeclaration.cpp b/Source/core/css/CSSComputedStyleDeclaration.cpp
index 64defa5..a5fb17f 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.cpp
+++ b/Source/core/css/CSSComputedStyleDeclaration.cpp
@@ -63,9 +63,9 @@
 #include "core/rendering/style/ContentData.h"
 #include "core/rendering/style/CounterContent.h"
 #include "core/rendering/style/CursorList.h"
-#include "core/rendering/style/ExclusionShapeValue.h"
 #include "core/rendering/style/RenderStyle.h"
-#include <wtf/text/StringBuilder.h>
+#include "core/rendering/style/ShapeValue.h"
+#include "wtf/text/StringBuilder.h"
 
 #include "core/platform/graphics/filters/custom/CustomFilterArrayParameter.h"
 #include "core/platform/graphics/filters/custom/CustomFilterNumberParameter.h"
@@ -244,27 +244,27 @@
     CSSPropertyWebkitColumnSpan,
     CSSPropertyWebkitColumnWidth,
     CSSPropertyWebkitFilter,
-    CSSPropertyWebkitAlignContent,
-    CSSPropertyWebkitAlignItems,
-    CSSPropertyWebkitAlignSelf,
-    CSSPropertyWebkitFlexBasis,
-    CSSPropertyWebkitFlexGrow,
-    CSSPropertyWebkitFlexShrink,
-    CSSPropertyWebkitFlexDirection,
-    CSSPropertyWebkitFlexWrap,
-    CSSPropertyWebkitJustifyContent,
+    CSSPropertyAlignContent,
+    CSSPropertyAlignItems,
+    CSSPropertyAlignSelf,
+    CSSPropertyFlexBasis,
+    CSSPropertyFlexGrow,
+    CSSPropertyFlexShrink,
+    CSSPropertyFlexDirection,
+    CSSPropertyFlexWrap,
+    CSSPropertyJustifyContent,
     CSSPropertyWebkitFontKerning,
     CSSPropertyWebkitFontSmoothing,
     CSSPropertyWebkitFontVariantLigatures,
     CSSPropertyGridAutoColumns,
     CSSPropertyGridAutoFlow,
     CSSPropertyGridAutoRows,
-    CSSPropertyGridColumns,
-    CSSPropertyGridRows,
-    CSSPropertyGridStart,
-    CSSPropertyGridEnd,
-    CSSPropertyGridBefore,
-    CSSPropertyGridAfter,
+    CSSPropertyGridColumnEnd,
+    CSSPropertyGridColumnStart,
+    CSSPropertyGridDefinitionColumns,
+    CSSPropertyGridDefinitionRows,
+    CSSPropertyGridRowEnd,
+    CSSPropertyGridRowStart,
     CSSPropertyWebkitHighlight,
     CSSPropertyWebkitHyphenateCharacter,
     CSSPropertyWebkitHyphenateLimitAfter,
@@ -297,7 +297,7 @@
     CSSPropertyWebkitMaskPosition,
     CSSPropertyWebkitMaskRepeat,
     CSSPropertyWebkitMaskSize,
-    CSSPropertyWebkitOrder,
+    CSSPropertyOrder,
     CSSPropertyWebkitPerspective,
     CSSPropertyWebkitPerspectiveOrigin,
     CSSPropertyWebkitPrintColorAdjust,
@@ -634,7 +634,8 @@
             toRenderBox(renderer)->containingBlockLogicalWidthForContent() :
             toRenderBox(renderer)->containingBlockLogicalHeightForContent(ExcludeMarginBorderPadding);
         return zoomAdjustedPixelValue(valueForLength(l, containingBlockSize, 0), style);
-    } if (l.isViewportPercentage())
+    }
+    if (l.isViewportPercentage())
         return zoomAdjustedPixelValue(valueForLength(l, 0, renderView), style);
     if (l.isAuto()) {
         // FIXME: It's not enough to simply return "auto" values for one offset if the other side is defined.
@@ -1316,7 +1317,7 @@
 
     if (!list->length())
         return cssValuePool().createIdentifierValue(CSSValueNone);
-    return list;
+    return list.release();
 }
 
 static PassRefPtr<CSSValue> renderTextDecorationStyleFlagsToCSSValue(TextDecorationStyle textDecorationStyle)
@@ -1484,22 +1485,17 @@
     return cssValuePool().createIdentifierValue(CSSValueNormal);
 }
 
-static bool isLayoutDependentProperty(CSSPropertyID propertyID)
+static bool isLayoutDependent(CSSPropertyID propertyID, PassRefPtr<RenderStyle> style, RenderObject* renderer)
 {
+    // Some properties only depend on layout in certain conditions which
+    // are specified in the main switch statement below. So we can avoid
+    // forcing layout in those conditions. The conditions in this switch
+    // statement must remain in sync with the conditions in the main switch.
+    // FIXME: Some of these cases could be narrowed down or optimized better.
     switch (propertyID) {
     case CSSPropertyBottom:
     case CSSPropertyHeight:
     case CSSPropertyLeft:
-    case CSSPropertyMargin:
-    case CSSPropertyMarginBottom:
-    case CSSPropertyMarginLeft:
-    case CSSPropertyMarginRight:
-    case CSSPropertyMarginTop:
-    case CSSPropertyPadding:
-    case CSSPropertyPaddingBottom:
-    case CSSPropertyPaddingLeft:
-    case CSSPropertyPaddingRight:
-    case CSSPropertyPaddingTop:
     case CSSPropertyRight:
     case CSSPropertyTop:
     case CSSPropertyWebkitPerspectiveOrigin:
@@ -1508,11 +1504,47 @@
     case CSSPropertyWidth:
     case CSSPropertyWebkitFilter:
         return true;
+    case CSSPropertyMargin:
+        return renderer && renderer->isBox() && (!style || !style->marginBottom().isFixed() || !style->marginTop().isFixed() || !style->marginLeft().isFixed() || !style->marginRight().isFixed());
+    case CSSPropertyMarginLeft:
+        return renderer && renderer->isBox() && (!style || !style->marginLeft().isFixed());
+    case CSSPropertyMarginRight:
+        return renderer && renderer->isBox() && (!style || !style->marginRight().isFixed());
+    case CSSPropertyMarginTop:
+        return renderer && renderer->isBox() && (!style || !style->marginTop().isFixed());
+    case CSSPropertyMarginBottom:
+        return renderer && renderer->isBox() && (!style || !style->marginBottom().isFixed());
+    case CSSPropertyPadding:
+        return renderer && renderer->isBox() && (!style || !style->paddingBottom().isFixed() || !style->paddingTop().isFixed() || !style->paddingLeft().isFixed() || !style->paddingRight().isFixed());
+    case CSSPropertyPaddingBottom:
+        return renderer && renderer->isBox() && (!style || !style->paddingBottom().isFixed());
+    case CSSPropertyPaddingLeft:
+        return renderer && renderer->isBox() && (!style || !style->paddingLeft().isFixed());
+    case CSSPropertyPaddingRight:
+        return renderer && renderer->isBox() && (!style || !style->paddingRight().isFixed());
+    case CSSPropertyPaddingTop:
+        return renderer && renderer->isBox() && (!style || !style->paddingTop().isFixed());
     default:
         return false;
     }
 }
 
+PassRefPtr<RenderStyle> CSSComputedStyleDeclaration::computeRenderStyle(CSSPropertyID propertyID) const
+{
+    Node* styledNode = this->styledNode();
+    ASSERT(styledNode);
+    RenderObject* renderer = styledNode->renderer();
+    if (renderer && renderer->isComposited() && AnimationController::supportsAcceleratedAnimationOfProperty(propertyID)) {
+        AnimationUpdateBlock animationUpdateBlock(renderer->animation());
+        if (m_pseudoElementSpecifier && !styledNode->isPseudoElement()) {
+            // FIXME: This cached pseudo style will only exist if the animation has been run at least once.
+            return renderer->animation()->getAnimatedStyleForRenderer(renderer)->getCachedPseudoStyle(m_pseudoElementSpecifier);
+        }
+        return renderer->animation()->getAnimatedStyleForRenderer(renderer);
+    }
+    return styledNode->computedStyle(styledNode->isPseudoElement() ? NOPSEUDO : m_pseudoElementSpecifier);
+}
+
 Node* CSSComputedStyleDeclaration::styledNode() const
 {
     if (!m_node)
@@ -1529,42 +1561,35 @@
     Node* styledNode = this->styledNode();
     if (!styledNode)
         return 0;
+    RenderObject* renderer = styledNode->renderer();
+    RefPtr<RenderStyle> style;
 
     if (updateLayout) {
         Document* document = styledNode->document();
-        // FIXME: Some of these cases could be narrowed down or optimized better.
-        bool forceFullLayout = isLayoutDependentProperty(propertyID)
-            || styledNode->isInShadowTree()
-            || (document->styleResolverIfExists() && document->styleResolverIfExists()->hasViewportDependentMediaQueries() && document->ownerElement())
-            || document->seamlessParentIFrame();
 
-        if (forceFullLayout)
-            document->updateLayoutIgnorePendingStylesheets();
-        else {
-            bool needsStyleRecalc = document->hasPendingForcedStyleRecalc();
-            for (Node* n = styledNode; n && !needsStyleRecalc; n = n->parentNode())
-                needsStyleRecalc = n->needsStyleRecalc();
-            if (needsStyleRecalc)
-                document->updateStyleIfNeeded();
-        }
+        document->updateStyleForNodeIfNeeded(styledNode);
 
         // The style recalc could have caused the styled node to be discarded or replaced
         // if it was a PseudoElement so we need to update it.
         styledNode = this->styledNode();
-    }
+        renderer = styledNode->renderer();
 
-    RenderObject* renderer = styledNode->renderer();
+        style = computeRenderStyle(propertyID);
 
-    RefPtr<RenderStyle> style;
-    if (renderer && renderer->isComposited() && AnimationController::supportsAcceleratedAnimationOfProperty(propertyID)) {
-        AnimationUpdateBlock animationUpdateBlock(renderer->animation());
-        style = renderer->animation()->getAnimatedStyleForRenderer(renderer);
-        if (m_pseudoElementSpecifier && !styledNode->isPseudoElement()) {
-            // FIXME: This cached pseudo style will only exist if the animation has been run at least once.
-            style = style->getCachedPseudoStyle(m_pseudoElementSpecifier);
+        bool forceFullLayout = isLayoutDependent(propertyID, style, renderer)
+            || styledNode->isInShadowTree()
+            || (document->styleResolverIfExists() && document->styleResolverIfExists()->hasViewportDependentMediaQueries() && document->ownerElement())
+            || document->seamlessParentIFrame();
+
+        if (forceFullLayout) {
+            document->updateLayoutIgnorePendingStylesheets();
+            styledNode = this->styledNode();
+            style = computeRenderStyle(propertyID);
+            renderer = styledNode->renderer();
         }
-    } else
-        style = styledNode->computedStyle(styledNode->isPseudoElement() ? NOPSEUDO : m_pseudoElementSpecifier);
+    } else {
+        style = computeRenderStyle(propertyID);
+    }
 
     if (!style)
         return 0;
@@ -1841,11 +1866,11 @@
             return cssValuePool().createValue(style->display());
         case CSSPropertyEmptyCells:
             return cssValuePool().createValue(style->emptyCells());
-        case CSSPropertyWebkitAlignContent:
+        case CSSPropertyAlignContent:
             return cssValuePool().createValue(style->alignContent());
-        case CSSPropertyWebkitAlignItems:
+        case CSSPropertyAlignItems:
             return cssValuePool().createValue(style->alignItems());
-        case CSSPropertyWebkitAlignSelf:
+        case CSSPropertyAlignSelf:
             if (style->alignSelf() == AlignAuto) {
                 Node* parent = styledNode->parentNode();
                 if (parent && parent->computedStyle())
@@ -1853,23 +1878,23 @@
                 return cssValuePool().createValue(AlignStretch);
             }
             return cssValuePool().createValue(style->alignSelf());
-        case CSSPropertyWebkitFlex:
-            return getCSSPropertyValuesForShorthandProperties(webkitFlexShorthand());
-        case CSSPropertyWebkitFlexBasis:
+        case CSSPropertyFlex:
+            return getCSSPropertyValuesForShorthandProperties(flexShorthand());
+        case CSSPropertyFlexBasis:
             return cssValuePool().createValue(style->flexBasis());
-        case CSSPropertyWebkitFlexDirection:
+        case CSSPropertyFlexDirection:
             return cssValuePool().createValue(style->flexDirection());
-        case CSSPropertyWebkitFlexFlow:
-            return getCSSPropertyValuesForShorthandProperties(webkitFlexFlowShorthand());
-        case CSSPropertyWebkitFlexGrow:
+        case CSSPropertyFlexFlow:
+            return getCSSPropertyValuesForShorthandProperties(flexFlowShorthand());
+        case CSSPropertyFlexGrow:
             return cssValuePool().createValue(style->flexGrow());
-        case CSSPropertyWebkitFlexShrink:
+        case CSSPropertyFlexShrink:
             return cssValuePool().createValue(style->flexShrink());
-        case CSSPropertyWebkitFlexWrap:
+        case CSSPropertyFlexWrap:
             return cssValuePool().createValue(style->flexWrap());
-        case CSSPropertyWebkitJustifyContent:
+        case CSSPropertyJustifyContent:
             return cssValuePool().createValue(style->justifyContent());
-        case CSSPropertyWebkitOrder:
+        case CSSPropertyOrder:
             return cssValuePool().createValue(style->order(), CSSPrimitiveValue::CSS_NUMBER);
         case CSSPropertyFloat:
             if (style->display() != NONE && style->hasOutOfFlowPosition())
@@ -1919,19 +1944,19 @@
             return cssValuePool().createValue(style->gridAutoFlow());
         case CSSPropertyGridAutoRows:
             return valueForGridTrackSize(style->gridAutoRows(), style.get(), m_node->document()->renderView());
-        case CSSPropertyGridColumns:
-            return valueForGridTrackList(style->gridColumns(), style->namedGridColumnLines(), style.get(), m_node->document()->renderView());
-        case CSSPropertyGridRows:
-            return valueForGridTrackList(style->gridRows(), style->namedGridRowLines(), style.get(), m_node->document()->renderView());
+        case CSSPropertyGridDefinitionColumns:
+            return valueForGridTrackList(style->gridDefinitionColumns(), style->namedGridColumnLines(), style.get(), m_node->document()->renderView());
+        case CSSPropertyGridDefinitionRows:
+            return valueForGridTrackList(style->gridDefinitionRows(), style->namedGridRowLines(), style.get(), m_node->document()->renderView());
 
-        case CSSPropertyGridStart:
-            return valueForGridPosition(style->gridStart());
-        case CSSPropertyGridEnd:
-            return valueForGridPosition(style->gridEnd());
-        case CSSPropertyGridBefore:
-            return valueForGridPosition(style->gridBefore());
-        case CSSPropertyGridAfter:
-            return valueForGridPosition(style->gridAfter());
+        case CSSPropertyGridColumnStart:
+            return valueForGridPosition(style->gridColumnStart());
+        case CSSPropertyGridColumnEnd:
+            return valueForGridPosition(style->gridColumnEnd());
+        case CSSPropertyGridRowStart:
+            return valueForGridPosition(style->gridRowStart());
+        case CSSPropertyGridRowEnd:
+            return valueForGridPosition(style->gridRowEnd());
         case CSSPropertyGridColumn:
             return getCSSPropertyValuesForGridShorthand(gridColumnShorthand());
         case CSSPropertyGridRow:
@@ -2090,22 +2115,30 @@
             return cssValuePool().createValue(style->overflowX());
         case CSSPropertyOverflowY:
             return cssValuePool().createValue(style->overflowY());
-        case CSSPropertyPaddingTop:
-            if (renderer && renderer->isBox())
-                return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingTop(), style.get());
-            return zoomAdjustedPixelValueForLength(style->paddingTop(), style.get());
-        case CSSPropertyPaddingRight:
-            if (renderer && renderer->isBox())
-                return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingRight(), style.get());
-            return zoomAdjustedPixelValueForLength(style->paddingRight(), style.get());
-        case CSSPropertyPaddingBottom:
-            if (renderer && renderer->isBox())
-                return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingBottom(), style.get());
-            return zoomAdjustedPixelValueForLength(style->paddingBottom(), style.get());
-        case CSSPropertyPaddingLeft:
-            if (renderer && renderer->isBox())
-                return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingLeft(), style.get());
-            return zoomAdjustedPixelValueForLength(style->paddingLeft(), style.get());
+        case CSSPropertyPaddingTop: {
+            Length paddingTop = style->paddingTop();
+            if (paddingTop.isFixed() || !renderer || !renderer->isBox())
+                return zoomAdjustedPixelValueForLength(paddingTop, style.get());
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingTop(), style.get());
+        }
+        case CSSPropertyPaddingRight: {
+            Length paddingRight = style->paddingRight();
+            if (paddingRight.isFixed() || !renderer || !renderer->isBox())
+                return zoomAdjustedPixelValueForLength(paddingRight, style.get());
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingRight(), style.get());
+        }
+        case CSSPropertyPaddingBottom: {
+            Length paddingBottom = style->paddingBottom();
+            if (paddingBottom.isFixed() || !renderer || !renderer->isBox())
+                return zoomAdjustedPixelValueForLength(paddingBottom, style.get());
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingBottom(), style.get());
+        }
+        case CSSPropertyPaddingLeft: {
+            Length paddingLeft = style->paddingLeft();
+            if (paddingLeft.isFixed() || !renderer || !renderer->isBox())
+                return zoomAdjustedPixelValueForLength(paddingLeft, style.get());
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingLeft(), style.get());
+        }
         case CSSPropertyPageBreakAfter:
             return cssValuePool().createValue(style->pageBreakAfter());
         case CSSPropertyPageBreakBefore:
@@ -2576,24 +2609,24 @@
         case CSSPropertyWebkitShapeInside:
             if (!style->shapeInside())
                 return cssValuePool().createIdentifierValue(CSSValueAuto);
-            if (style->shapeInside()->type() == ExclusionShapeValue::Outside)
+            if (style->shapeInside()->type() == ShapeValue::Outside)
                 return cssValuePool().createIdentifierValue(CSSValueOutsideShape);
-            if (style->shapeInside()->type() == ExclusionShapeValue::Image) {
+            if (style->shapeInside()->type() == ShapeValue::Image) {
                 if (style->shapeInside()->image())
                     return style->shapeInside()->image()->cssValue();
                 return cssValuePool().createIdentifierValue(CSSValueNone);
             }
-            ASSERT(style->shapeInside()->type() == ExclusionShapeValue::Shape);
+            ASSERT(style->shapeInside()->type() == ShapeValue::Shape);
             return valueForBasicShape(style->shapeInside()->shape());
         case CSSPropertyWebkitShapeOutside:
             if (!style->shapeOutside())
                 return cssValuePool().createIdentifierValue(CSSValueAuto);
-            if (style->shapeOutside()->type() == ExclusionShapeValue::Image) {
+            if (style->shapeOutside()->type() == ShapeValue::Image) {
                 if (style->shapeOutside()->image())
                     return style->shapeOutside()->image()->cssValue();
                 return cssValuePool().createIdentifierValue(CSSValueNone);
             }
-            ASSERT(style->shapeOutside()->type() == ExclusionShapeValue::Shape);
+            ASSERT(style->shapeOutside()->type() == ShapeValue::Shape);
             return valueForBasicShape(style->shapeOutside()->shape());
         case CSSPropertyWebkitWrapThrough:
             return cssValuePool().createValue(style->wrapThrough());
diff --git a/Source/core/css/CSSComputedStyleDeclaration.h b/Source/core/css/CSSComputedStyleDeclaration.h
index 05c7cb3..e628cd8 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.h
+++ b/Source/core/css/CSSComputedStyleDeclaration.h
@@ -85,6 +85,7 @@
     virtual CSSRule* parentRule() const;
     virtual unsigned length() const;
     virtual String item(unsigned index) const;
+    PassRefPtr<RenderStyle> computeRenderStyle(CSSPropertyID) const;
     virtual PassRefPtr<CSSValue> getPropertyCSSValue(const String& propertyName);
     virtual String getPropertyValue(const String& propertyName);
     virtual String getPropertyPriority(const String& propertyName);
diff --git a/Source/core/css/CSSCrossfadeValue.h b/Source/core/css/CSSCrossfadeValue.h
index 9496f5d..c0c953c 100644
--- a/Source/core/css/CSSCrossfadeValue.h
+++ b/Source/core/css/CSSCrossfadeValue.h
@@ -32,7 +32,6 @@
 #include "core/loader/cache/CachedImageClient.h"
 #include "core/loader/cache/CachedResourceHandle.h"
 #include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/ImageObserver.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSCursorImageValue.cpp b/Source/core/css/CSSCursorImageValue.cpp
index 62bff86..a9f27c2 100644
--- a/Source/core/css/CSSCursorImageValue.cpp
+++ b/Source/core/css/CSSCursorImageValue.cpp
@@ -35,10 +35,9 @@
 #include "core/svg/SVGCursorElement.h"
 #include "core/svg/SVGLengthContext.h"
 #include "core/svg/SVGURIReference.h"
-#include <wtf/MathExtras.h>
-#include <wtf/MemoryInstrumentationHashSet.h>
-#include <wtf/UnusedParam.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/MathExtras.h"
+#include "wtf/MemoryInstrumentationHashSet.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -122,10 +121,10 @@
     return false;
 }
 
-StyleImage* CSSCursorImageValue::cachedImage(CachedResourceLoader* loader)
+StyleImage* CSSCursorImageValue::cachedImage(CachedResourceLoader* loader, float deviceScaleFactor)
 {
     if (m_imageValue->isImageSetValue())
-        return static_cast<CSSImageSetValue*>(m_imageValue.get())->cachedImageSet(loader);
+        return static_cast<CSSImageSetValue*>(m_imageValue.get())->cachedImageSet(loader, deviceScaleFactor);
 
     if (!m_accessedImage) {
         m_accessedImage = true;
@@ -154,11 +153,11 @@
     return 0;
 }
 
-StyleImage* CSSCursorImageValue::cachedOrPendingImage(Document* document)
+StyleImage* CSSCursorImageValue::cachedOrPendingImage(float deviceScaleFactor)
 {
     // Need to delegate completely so that changes in device scale factor can be handled appropriately.
     if (m_imageValue->isImageSetValue())
-        return static_cast<CSSImageSetValue*>(m_imageValue.get())->cachedOrPendingImageSet(document);
+        return static_cast<CSSImageSetValue*>(m_imageValue.get())->cachedOrPendingImageSet(deviceScaleFactor);
 
     if (!m_image)
         m_image = StylePendingImage::create(this);
@@ -204,7 +203,7 @@
 {
     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
     m_imageValue->reportMemoryUsage(memoryObjectInfo);
-    // No need to report m_image as it is counted as part of RenderArena.
+    // FIXME: report m_image. It has never been allocated from any of our rendering custom heaps.
     info.addMember(m_referencedElements, "referencedElements");
 }
 
diff --git a/Source/core/css/CSSCursorImageValue.h b/Source/core/css/CSSCursorImageValue.h
index e3a85e2..04723dd 100644
--- a/Source/core/css/CSSCursorImageValue.h
+++ b/Source/core/css/CSSCursorImageValue.h
@@ -27,7 +27,6 @@
 
 namespace WebCore {
 
-class Document;
 class Element;
 class SVGElement;
 
@@ -52,8 +51,8 @@
     String customCssText() const;
 
     bool updateIfSVGCursorIsUsed(Element*);
-    StyleImage* cachedImage(CachedResourceLoader*);
-    StyleImage* cachedOrPendingImage(Document*);
+    StyleImage* cachedImage(CachedResourceLoader*, float deviceScaleFactor);
+    StyleImage* cachedOrPendingImage(float deviceScaleFactor);
 
     void removeReferencedElement(SVGElement*);
 
diff --git a/Source/core/css/CSSFilterValue.h b/Source/core/css/CSSFilterValue.h
index 22500ed..5bf7355 100644
--- a/Source/core/css/CSSFilterValue.h
+++ b/Source/core/css/CSSFilterValue.h
@@ -28,7 +28,6 @@
 
 #include "core/css/CSSValueList.h"
 #include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSFontFace.cpp b/Source/core/css/CSSFontFace.cpp
index 4400c92..9196a3c 100644
--- a/Source/core/css/CSSFontFace.cpp
+++ b/Source/core/css/CSSFontFace.cpp
@@ -31,7 +31,6 @@
 #include "core/css/CSSSegmentedFontFace.h"
 #include "core/css/FontLoader.h"
 #include "core/dom/Document.h"
-#include "RuntimeEnabledFeatures.h"
 #include "core/platform/graphics/SimpleFontData.h"
 
 namespace WebCore {
@@ -88,11 +87,11 @@
     CSSFontSelector* fontSelector = (*m_segmentedFontFaces.begin())->fontSelector();
     fontSelector->fontLoaded();
 
-    if (RuntimeEnabledFeatures::fontLoadEventsEnabled() && m_loadState == Loading) {
+    if (m_loadState == Loading) {
         if (source->ensureFontData())
-            notifyFontLoader(Loaded);
+            setLoadState(Loaded);
         else if (!isValid())
-            notifyFontLoader(Error);
+            setLoadState(Error);
     }
 
     HashSet<CSSSegmentedFontFace*>::iterator end = m_segmentedFontFaces.end();
@@ -109,25 +108,25 @@
     ASSERT(!m_segmentedFontFaces.isEmpty());
     CSSFontSelector* fontSelector = (*m_segmentedFontFaces.begin())->fontSelector();
 
-    if (RuntimeEnabledFeatures::fontLoadEventsEnabled() && m_loadState == NotLoaded)
-        notifyFontLoader(Loading);
+    if (m_loadState == NotLoaded)
+        setLoadState(Loading);
 
     size_t size = m_sources.size();
     for (size_t i = 0; i < size; ++i) {
         if (RefPtr<SimpleFontData> result = m_sources[i]->getFontData(fontDescription, syntheticBold, syntheticItalic, fontSelector)) {
             m_activeSource = m_sources[i].get();
-            if (RuntimeEnabledFeatures::fontLoadEventsEnabled() && m_loadState == Loading && m_sources[i]->isLoaded())
-                notifyFontLoader(Loaded);
+            if (m_loadState == Loading && m_sources[i]->isLoaded())
+                setLoadState(Loaded);
             return result.release();
         }
     }
 
-    if (RuntimeEnabledFeatures::fontLoadEventsEnabled() && m_loadState == Loading)
-        notifyFontLoader(Error);
+    if (m_loadState == Loading)
+        setLoadState(Error);
     return 0;
 }
 
-void CSSFontFace::notifyFontLoader(LoadState newState)
+void CSSFontFace::setLoadState(LoadState newState)
 {
     m_loadState = newState;
 
diff --git a/Source/core/css/CSSFontFace.h b/Source/core/css/CSSFontFace.h
index 0acf394..31bf1b5 100644
--- a/Source/core/css/CSSFontFace.h
+++ b/Source/core/css/CSSFontFace.h
@@ -29,12 +29,11 @@
 #include "core/css/CSSFontFaceRule.h"
 #include "core/css/CSSFontFaceSource.h"
 #include "core/platform/graphics/FontTraitsMask.h"
-#include <wtf/Forward.h>
-#include <wtf/HashSet.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/unicode/Unicode.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/HashSet.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -99,6 +98,7 @@
     {
         UNUSED_PARAM(rule);
     }
+    void setLoadState(LoadState);
 
     FontTraitsMask m_traitsMask;
     Vector<UnicodeRange> m_ranges;
@@ -108,7 +108,6 @@
     bool m_isLocalFallback;
     LoadState m_loadState;
     RefPtr<CSSFontFaceRule> m_rule;
-    void notifyFontLoader(LoadState);
 };
 
 }
diff --git a/Source/core/css/CSSFontFaceLoadEvent.h b/Source/core/css/CSSFontFaceLoadEvent.h
index ac1a137..c2aca89 100644
--- a/Source/core/css/CSSFontFaceLoadEvent.h
+++ b/Source/core/css/CSSFontFaceLoadEvent.h
@@ -32,12 +32,11 @@
 #define CSSFontFaceLoadEvent_h
 
 #include "core/css/CSSFontFaceRule.h"
-#include "core/css/CSSValue.h"
 #include "core/dom/DOMError.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSFontSelector.h b/Source/core/css/CSSFontSelector.h
index 625dc0a..7c4da6d 100644
--- a/Source/core/css/CSSFontSelector.h
+++ b/Source/core/css/CSSFontSelector.h
@@ -29,11 +29,10 @@
 #include "core/loader/cache/CachedResourceHandle.h"
 #include "core/platform/Timer.h"
 #include "core/platform/graphics/FontSelector.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/StringHash.h>
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
+#include "wtf/text/StringHash.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSFunctionValue.cpp b/Source/core/css/CSSFunctionValue.cpp
index 07af686..176f856 100644
--- a/Source/core/css/CSSFunctionValue.cpp
+++ b/Source/core/css/CSSFunctionValue.cpp
@@ -29,8 +29,7 @@
 #include "core/css/CSSParserValues.h"
 #include "core/css/CSSValueList.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSGradientValue.cpp b/Source/core/css/CSSGradientValue.cpp
index 2ad4d59..4c1fe6b 100644
--- a/Source/core/css/CSSGradientValue.cpp
+++ b/Source/core/css/CSSGradientValue.cpp
@@ -28,7 +28,7 @@
 
 #include "CSSValueKeywords.h"
 #include "core/css/CSSCalculationValue.h"
-#include "core/css/resolver/StyleResolver.h"
+#include "core/css/resolver/StyleResolverState.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/platform/graphics/GeneratorGeneratedImage.h"
@@ -114,11 +114,11 @@
     { }
 };
 
-PassRefPtr<CSSGradientValue> CSSGradientValue::gradientWithStylesResolved(StyleResolver* styleResolver)
+PassRefPtr<CSSGradientValue> CSSGradientValue::gradientWithStylesResolved(StyleResolverState& styleResolverState)
 {
     bool derived = false;
     for (unsigned i = 0; i < m_stops.size(); i++)
-        if (styleResolver->colorFromPrimitiveValueIsDerivedFromElement(m_stops[i].m_color.get())) {
+        if (m_stops[i].m_color->colorIsDerivedFromElement()) {
             m_stops[i].m_colorIsDerivedFromElement = true;
             derived = true;
             break;
@@ -137,7 +137,7 @@
     }
 
     for (unsigned i = 0; i < result->m_stops.size(); i++)
-        result->m_stops[i].m_resolvedColor = styleResolver->colorFromPrimitiveValue(result->m_stops[i].m_color.get());
+        result->m_stops[i].m_resolvedColor = styleResolverState.resolveColorFromPrimitiveValue(result->m_stops[i].m_color.get());
 
     return result.release();
 }
diff --git a/Source/core/css/CSSGradientValue.h b/Source/core/css/CSSGradientValue.h
index ab8576f..1ed7c95 100644
--- a/Source/core/css/CSSGradientValue.h
+++ b/Source/core/css/CSSGradientValue.h
@@ -35,6 +35,7 @@
 
 class FloatPoint;
 class Gradient;
+class StyleResolverState;
 
 enum CSSGradientType {
     CSSDeprecatedLinearGradient,
@@ -89,7 +90,7 @@
     bool knownToBeOpaque(const RenderObject*) const;
 
     void loadSubimages(CachedResourceLoader*) { }
-    PassRefPtr<CSSGradientValue> gradientWithStylesResolved(StyleResolver*);
+    PassRefPtr<CSSGradientValue> gradientWithStylesResolved(StyleResolverState&);
 
 protected:
     CSSGradientValue(ClassType classType, CSSGradientRepeat repeat, CSSGradientType gradientType)
diff --git a/Source/core/css/CSSGrammar.y.in b/Source/core/css/CSSGrammar.y.in
index 9a4c5db..b398b89 100644
--- a/Source/core/css/CSSGrammar.y.in
+++ b/Source/core/css/CSSGrammar.y.in
@@ -77,6 +77,7 @@
     case CALCFUNCTION:
     case MINFUNCTION:
     case MAXFUNCTION:
+    case VARFUNCTION:
     case VAR_DEFINITION:
     case UNICODERANGE:
         return true;
@@ -132,17 +133,16 @@
 %token HOST_SYM
 %token CHARSET_SYM
 %token NAMESPACE_SYM
-%token VARFUNCTION
 %token VIEWPORT_RULE_SYM
 %token INTERNAL_DECLS_SYM
 %token INTERNAL_MEDIALIST_SYM
 %token INTERNAL_RULE_SYM
 %token INTERNAL_SELECTOR_SYM
 %token INTERNAL_VALUE_SYM
-%token WEBKIT_KEYFRAME_RULE_SYM
+%token INTERNAL_KEYFRAME_RULE_SYM
+%token INTERNAL_SUPPORTS_CONDITION_SYM
 %token WEBKIT_KEYFRAMES_SYM
 %token WEBKIT_REGION_RULE_SYM
-%token WEBKIT_SUPPORTS_CONDITION_SYM
 %token WEBKIT_FILTER_RULE_SYM
 %token <marginBox> TOPLEFTCORNER_SYM
 %token <marginBox> TOPLEFT_SYM
@@ -214,6 +214,7 @@
 %token <string> CALCFUNCTION
 %token <string> MINFUNCTION
 %token <string> MAXFUNCTION
+%token <string> VARFUNCTION
 %token <string> VAR_DEFINITION
 
 %token <string> UNICODERANGE
@@ -234,7 +235,7 @@
 %type <rule> rule
 %type <rule> valid_rule
 %type <ruleList> block_rule_body
-%type <ruleList> block_rule_list 
+%type <ruleList> block_rule_list
 %type <ruleList> region_block_rule_body
 %type <ruleList> region_block_rule_list
 %type <rule> block_rule
@@ -328,36 +329,36 @@
 
 stylesheet:
     maybe_charset maybe_sgml rule_list
-  | internal_decls maybe_space
-  | internal_rule maybe_space
-  | internal_selector maybe_space
-  | internal_value maybe_space
+  | internal_decls
+  | internal_rule
+  | internal_selector
+  | internal_value
   | internal_medialist
-  | webkit_keyframe_rule maybe_space
-  | webkit_supports_condition maybe_space
+  | internal_keyframe_rule
+  | internal_supports_condition
   ;
 
 internal_rule:
-    INTERNAL_RULE_SYM '{' maybe_space valid_rule maybe_space '}' {
-        parser->m_rule = $4;
+    INTERNAL_RULE_SYM maybe_space valid_rule maybe_space TOKEN_EOF {
+        parser->m_rule = $3;
     }
 ;
 
-webkit_keyframe_rule:
-    WEBKIT_KEYFRAME_RULE_SYM '{' maybe_space keyframe_rule maybe_space '}' {
-        parser->m_keyframe = $4;
+internal_keyframe_rule:
+    INTERNAL_KEYFRAME_RULE_SYM maybe_space keyframe_rule maybe_space TOKEN_EOF {
+        parser->m_keyframe = $3;
     }
 ;
 
 internal_decls:
-    INTERNAL_DECLS_SYM '{' maybe_space_before_declaration declaration_list '}' {
+    INTERNAL_DECLS_SYM maybe_space_before_declaration declaration_list TOKEN_EOF {
         /* can be empty */
     }
 ;
 
 internal_value:
-    INTERNAL_VALUE_SYM '{' maybe_space expr '}' {
-        parser->m_valueList = parser->sinkFloatingValueList($4);
+    INTERNAL_VALUE_SYM maybe_space expr TOKEN_EOF {
+        parser->m_valueList = parser->sinkFloatingValueList($3);
         int oldParsedProperties = parser->m_parsedProperties.size();
         if (!parser->parseValue(parser->m_id, parser->m_important))
             parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties);
@@ -366,21 +367,21 @@
 ;
 
 internal_medialist:
-    INTERNAL_MEDIALIST_SYM maybe_space maybe_media_list TOKEN_EOF {
-        parser->m_mediaList = $3;
+    INTERNAL_MEDIALIST_SYM maybe_space location_label maybe_media_list TOKEN_EOF {
+        parser->m_mediaList = $4;
     }
 ;
 
 internal_selector:
-    INTERNAL_SELECTOR_SYM '{' maybe_space selector_list '}' {
+    INTERNAL_SELECTOR_SYM maybe_space selector_list TOKEN_EOF {
         if (parser->m_selectorListForParseSelector)
-            parser->m_selectorListForParseSelector->adoptSelectorVector(*$4);
+            parser->m_selectorListForParseSelector->adoptSelectorVector(*$3);
     }
 ;
 
-webkit_supports_condition:
-    WEBKIT_SUPPORTS_CONDITION_SYM '{' maybe_space supports_condition '}' {
-        parser->m_supportsCondition = $4;
+internal_supports_condition:
+    INTERNAL_SUPPORTS_CONDITION_SYM maybe_space supports_condition TOKEN_EOF {
+        parser->m_supportsCondition = $3;
     }
 ;
 
@@ -410,8 +411,18 @@
   | %prec LOWEST_PREC TOKEN_EOF
   ;
 
+closing_square_bracket:
+    ']'
+  | %prec LOWEST_PREC TOKEN_EOF
+  ;
+
+semi_or_eof:
+    ';'
+  | TOKEN_EOF
+  ;
+
 charset:
-  CHARSET_SYM maybe_space STRING maybe_space ';' {
+  CHARSET_SYM maybe_space STRING maybe_space semi_or_eof {
      if (parser->m_styleSheet)
          parser->m_styleSheet->parserSetEncodingFromCharsetRule($3);
      parser->startEndUnknownRule();
@@ -457,9 +468,9 @@
   | block_rule_list error error_location rule_error_recovery {
         parser->reportError($3, CSSParser::InvalidRuleError);
     }
-    ; 
+    ;
 
-block_rule_list: 
+block_rule_list:
     /* empty */ { $$ = 0; }
   | block_rule_list block_rule maybe_sgml {
       $$ = $1;
@@ -523,13 +534,10 @@
     ;
 
 import:
-    before_import_rule IMPORT_SYM at_import_header_end_maybe_space string_or_uri maybe_space maybe_media_list ';' {
-        $$ = parser->createImportRule($4, $6);
+    before_import_rule IMPORT_SYM at_import_header_end_maybe_space string_or_uri maybe_space location_label maybe_media_list semi_or_eof {
+        $$ = parser->createImportRule($4, $7);
     }
-  | before_import_rule IMPORT_SYM at_import_header_end_maybe_space string_or_uri maybe_space maybe_media_list TOKEN_EOF {
-        $$ = parser->createImportRule($4, $6);
-    }
-  | before_import_rule IMPORT_SYM at_import_header_end_maybe_space string_or_uri maybe_space maybe_media_list invalid_block {
+  | before_import_rule IMPORT_SYM at_import_header_end_maybe_space string_or_uri maybe_space location_label maybe_media_list invalid_block {
         $$ = 0;
         parser->endRuleBody(true);
     }
@@ -546,7 +554,7 @@
     ;
 
 namespace:
-    before_namespace_rule NAMESPACE_SYM maybe_space maybe_ns_prefix string_or_uri maybe_space ';' {
+    before_namespace_rule NAMESPACE_SYM maybe_space maybe_ns_prefix string_or_uri maybe_space semi_or_eof {
         parser->addNamespace($4, $5);
         $$ = 0;
     }
@@ -560,7 +568,7 @@
 
 maybe_ns_prefix:
 /* empty */ { $$.clear(); }
-| IDENT maybe_space { $$ = $1; }
+| IDENT maybe_space
 ;
 
 string_or_uri:
@@ -634,10 +642,11 @@
 media_query:
     valid_media_query
     | valid_media_query error error_location rule_error_recovery {
+        parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidMediaQueryError);
         $$ = parser->createFloatingNotAllQuery();
     }
     | error error_location rule_error_recovery {
-        parser->reportError($2);
+        parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidMediaQueryError);
         $$ = parser->createFloatingNotAllQuery();
     }
     ;
@@ -653,26 +662,23 @@
     media_query {
         $$ = parser->createMediaQuerySet();
         $$->addMediaQuery(parser->sinkFloatingMediaQuery($1));
-        parser->updateLastMediaLine($$);
     }
     | mq_list media_query {
         $$ = $1;
         $$->addMediaQuery(parser->sinkFloatingMediaQuery($2));
-        parser->updateLastMediaLine($$);
     }
     | mq_list {
         $$ = $1;
         $$->addMediaQuery(parser->sinkFloatingMediaQuery(parser->createFloatingNotAllQuery()));
-        parser->updateLastMediaLine($$);
     }
     ;
 
 mq_list:
-    media_query ',' maybe_space {
+    media_query ',' maybe_space location_label {
         $$ = parser->createMediaQuerySet();
         $$->addMediaQuery(parser->sinkFloatingMediaQuery($1));
     }
-    | mq_list media_query ',' maybe_space {
+    | mq_list media_query ',' maybe_space location_label {
         $$ = $1;
         $$->addMediaQuery(parser->sinkFloatingMediaQuery($2));
     }
@@ -697,13 +703,13 @@
     ;
 
 media:
-    before_media_rule MEDIA_SYM maybe_space media_list at_rule_header_end '{' at_rule_body_start maybe_space block_rule_body closing_brace {
-        $$ = parser->createMediaRule($4, $9);
+    before_media_rule MEDIA_SYM maybe_space location_label media_list at_rule_header_end '{' at_rule_body_start maybe_space block_rule_body closing_brace {
+        $$ = parser->createMediaRule($5, $10);
     }
     | before_media_rule MEDIA_SYM at_rule_header_end_maybe_space '{' at_rule_body_start maybe_space block_rule_body closing_brace {
         $$ = parser->createMediaRule(0, $7);
     }
-    | before_media_rule MEDIA_SYM maybe_space media_list ';' {
+    | before_media_rule MEDIA_SYM maybe_space location_label media_list semi_or_eof {
         $$ = 0;
         parser->endRuleBody(true);
     }
@@ -714,9 +720,7 @@
     ;
 
 medium:
-  IDENT maybe_space {
-      $$ = $1;
-  }
+  IDENT maybe_space
   ;
 
 supports:
@@ -777,18 +781,18 @@
     ;
 
 supports_condition_in_parens:
-    '(' maybe_space supports_condition ')' maybe_space {
+    '(' maybe_space supports_condition closing_parenthesis maybe_space {
         $$ = $3;
     }
     | supports_declaration_condition
-    | '(' error error_location error_recovery ')' maybe_space {
+    | '(' error error_location error_recovery closing_parenthesis maybe_space {
         parser->reportError($3, CSSParser::InvalidSupportsConditionError);
         $$ = false;
     }
     ;
 
 supports_declaration_condition:
-    '(' maybe_space IDENT maybe_space ':' maybe_space expr prio ')' maybe_space {
+    '(' maybe_space IDENT maybe_space ':' maybe_space expr prio closing_parenthesis maybe_space {
         $$ = false;
         CSSPropertyID id = cssPropertyID($3);
         if (id != CSSPropertyInvalid) {
@@ -802,7 +806,7 @@
         parser->m_valueList = nullptr;
         parser->endProperty($8, false);
     }
-    | '(' maybe_space IDENT maybe_space ':' maybe_space error error_recovery ')' maybe_space {
+    | '(' maybe_space IDENT maybe_space ':' maybe_space error error_recovery closing_parenthesis maybe_space {
         $$ = false;
         parser->endProperty(false, false, CSSParser::GeneralError);
     }
@@ -815,15 +819,15 @@
     ;
 
 keyframes:
-    before_keyframes_rule WEBKIT_KEYFRAMES_SYM maybe_space keyframe_name at_rule_header_end_maybe_space '{' at_rule_body_start maybe_space keyframes_rule closing_brace {
-        $$ = parser->createKeyframesRule($4, parser->sinkFloatingKeyframeVector($9));
+    before_keyframes_rule WEBKIT_KEYFRAMES_SYM maybe_space keyframe_name at_rule_header_end_maybe_space '{' at_rule_body_start maybe_space location_label keyframes_rule closing_brace {
+        $$ = parser->createKeyframesRule($4, parser->sinkFloatingKeyframeVector($10));
     }
   | before_keyframes_rule WEBKIT_KEYFRAMES_SYM at_rule_recovery {
         $$ = 0;
         parser->endRuleBody(true);
     }
     ;
-  
+
 keyframe_name:
     IDENT
     | STRING
@@ -838,14 +842,15 @@
 keyframe_rule_list:
     /* empty */ {
         $$ = parser->createFloatingKeyframeVector();
+        parser->resumeErrorLogging();
     }
-    |  keyframe_rule_list keyframe_rule maybe_space {
+    |  keyframe_rule_list keyframe_rule maybe_space location_label {
         $$ = $1;
-        if ($2)
-            $$->append($2);
+        $$->append($2);
     }
-    | keyframe_rule_list keyframes_error_recovery invalid_block {
+    | keyframe_rule_list keyframes_error_recovery invalid_block maybe_space location_label {
         parser->clearProperties();
+        parser->resumeErrorLogging();
     }
     ;
 
@@ -862,8 +867,7 @@
     }
     | key_list ',' maybe_space key maybe_space {
         $$ = $1;
-        if ($$)
-            $$->addValue(parser->sinkFloatingValue($4));
+        $$->addValue(parser->sinkFloatingValue($4));
     }
     ;
 
@@ -883,7 +887,10 @@
     ;
 
 keyframes_error_recovery:
-    error error_location rule_error_recovery;
+    error rule_error_recovery {
+        parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidKeyframeSelectorError);
+    }
+    ;
 
 before_page_rule:
     /* empty */ {
@@ -917,15 +924,12 @@
     }
     | IDENT pseudo_page maybe_space {
         $$ = $2;
-        if ($$) {
-            $$->prependTagSelector(QualifiedName(nullAtom, $1, parser->m_defaultNamespace));
-            $$->setForPage();
-        }
+        $$->prependTagSelector(QualifiedName(nullAtom, $1, parser->m_defaultNamespace));
+        $$->setForPage();
     }
     | pseudo_page maybe_space {
         $$ = $1;
-        if ($$)
-            $$->setForPage();
+        $$->setForPage();
     }
     | /* empty */ {
         $$ = parser->createFloatingSelector();
@@ -1099,8 +1103,8 @@
   ;
 
 maybe_unary_operator:
-    unary_operator { $$ = $1; }
-    | { $$ = 1; }
+    unary_operator
+    | /* empty */ { $$ = 1; }
     ;
 
 unary_operator:
@@ -1194,9 +1198,9 @@
 namespace_selector:
     /* empty */ '|' { $$.clear(); }
     | '*' '|' { static LChar star = '*'; $$.init(&star, 1); }
-    | IDENT '|' { $$ = $1; }
-;
-    
+    | IDENT '|'
+    ;
+
 simple_selector:
     element_name {
         $$ = parser->createFloatingSelectorWithTagName(QualifiedName(nullAtom, $1, parser->m_defaultNamespace));
@@ -1252,9 +1256,7 @@
   ;
 
 specifier_list:
-    specifier {
-        $$ = $1;
-    }
+    specifier
     | specifier_list specifier {
         $$ = parser->rewriteSpecifiers($1, $2);
     }
@@ -1303,29 +1305,29 @@
     ;
 
 attrib:
-    '[' maybe_space attr_name ']' {
+    '[' maybe_space attr_name closing_square_bracket {
         $$ = parser->createFloatingSelector();
         $$->setAttribute(QualifiedName(nullAtom, $3, nullAtom));
         $$->setMatch(CSSSelector::Set);
     }
-    | '[' maybe_space attr_name match maybe_space ident_or_string maybe_space ']' {
+    | '[' maybe_space attr_name match maybe_space ident_or_string maybe_space closing_square_bracket {
         $$ = parser->createFloatingSelector();
         $$->setAttribute(QualifiedName(nullAtom, $3, nullAtom));
         $$->setMatch((CSSSelector::Match)$4);
         $$->setValue($6);
     }
-    | '[' maybe_space namespace_selector attr_name ']' {
+    | '[' maybe_space namespace_selector attr_name closing_square_bracket {
         $$ = parser->createFloatingSelector();
         $$->setAttribute(parser->determineNameInNamespace($3, $4));
         $$->setMatch(CSSSelector::Set);
     }
-    | '[' maybe_space namespace_selector attr_name match maybe_space ident_or_string maybe_space ']' {
+    | '[' maybe_space namespace_selector attr_name match maybe_space ident_or_string maybe_space closing_square_bracket {
         $$ = parser->createFloatingSelector();
         $$->setAttribute(parser->determineNameInNamespace($3, $4));
         $$->setMatch((CSSSelector::Match)$5);
         $$->setValue($7);
     }
-    | '[' selector_recovery ']' {
+    | '[' selector_recovery closing_square_bracket {
         YYERROR;
     }
   ;
@@ -1368,27 +1370,31 @@
     }
 
 pseudo:
-    ':' IDENT {
+    ':' error_location IDENT {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoClass);
-        parser->tokenToLowerCase($2);
-        $$->setValue($2);
-        CSSSelector::PseudoType type = $$->pseudoType();
-        if (type == CSSSelector::PseudoUnknown)
-            YYERROR;
-    }
-    | ':' ':' IDENT {
-        $$ = parser->createFloatingSelector();
-        $$->setMatch(CSSSelector::PseudoElement);
         parser->tokenToLowerCase($3);
         $$->setValue($3);
+        CSSSelector::PseudoType type = $$->pseudoType();
+        if (type == CSSSelector::PseudoUnknown) {
+            parser->reportError($2, CSSParser::InvalidSelectorPseudoError);
+            YYERROR;
+        }
+    }
+    | ':' ':' error_location IDENT {
+        $$ = parser->createFloatingSelector();
+        $$->setMatch(CSSSelector::PseudoElement);
+        parser->tokenToLowerCase($4);
+        $$->setValue($4);
         // FIXME: This call is needed to force selector to compute the pseudoType early enough.
         CSSSelector::PseudoType type = $$->pseudoType();
-        if (type == CSSSelector::PseudoUnknown)
+        if (type == CSSSelector::PseudoUnknown) {
+            parser->reportError($3, CSSParser::InvalidSelectorPseudoError);
             YYERROR;
+        }
     }
     // used by ::cue(:past/:future)
-    | ':' ':' CUEFUNCTION maybe_space simple_selector_list maybe_space ')' {
+    | ':' ':' CUEFUNCTION maybe_space simple_selector_list maybe_space closing_parenthesis {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoClass);
         $$->adoptSelectorVector(*parser->sinkFloatingSelectorVector($5));
@@ -1397,17 +1403,17 @@
         if (type != CSSSelector::PseudoCue)
             YYERROR;
     }
-    | ':' ':' CUEFUNCTION selector_recovery ')' {
+    | ':' ':' CUEFUNCTION selector_recovery closing_parenthesis {
         YYERROR;
     }
-    | ':' ':' DISTRIBUTEDFUNCTION maybe_space relative_selector ')' {
+    | ':' ':' DISTRIBUTEDFUNCTION maybe_space relative_selector closing_parenthesis {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoElement);
         $$->setFunctionArgumentSelector($5);
         parser->tokenToLowerCase($3);
         $$->setValue($3);
     }
-    | ':' ':' DISTRIBUTEDFUNCTION selector_recovery ')' {
+    | ':' ':' DISTRIBUTEDFUNCTION selector_recovery closing_parenthesis {
         YYERROR;
     }
     // use by :-webkit-any.
@@ -1415,7 +1421,7 @@
     // Use simple_selector_list for now to match -moz-any.
     // See http://lists.w3.org/Archives/Public/www-style/2010Sep/0566.html for some
     // related discussion with respect to :not.
-    | ':' ANYFUNCTION maybe_space simple_selector_list maybe_space ')' {
+    | ':' ANYFUNCTION maybe_space simple_selector_list maybe_space closing_parenthesis {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoClass);
         $$->adoptSelectorVector(*parser->sinkFloatingSelectorVector($4));
@@ -1425,11 +1431,11 @@
         if (type != CSSSelector::PseudoAny)
             YYERROR;
     }
-    | ':' ANYFUNCTION selector_recovery ')' {
+    | ':' ANYFUNCTION selector_recovery closing_parenthesis {
         YYERROR;
     }
     // used by :nth-*(ax+b)
-    | ':' FUNCTION maybe_space NTH maybe_space ')' {
+    | ':' FUNCTION maybe_space NTH maybe_space closing_parenthesis {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoClass);
         $$->setArgument($4);
@@ -1439,7 +1445,7 @@
             YYERROR;
     }
     // used by :nth-*
-    | ':' FUNCTION maybe_space maybe_unary_operator INTEGER maybe_space ')' {
+    | ':' FUNCTION maybe_space maybe_unary_operator INTEGER maybe_space closing_parenthesis {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoClass);
         $$->setArgument(String::number($4 * $5));
@@ -1449,7 +1455,7 @@
             YYERROR;
     }
     // used by :nth-*(odd/even) and :lang
-    | ':' FUNCTION maybe_space IDENT maybe_space ')' {
+    | ':' FUNCTION maybe_space IDENT maybe_space closing_parenthesis {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoClass);
         $$->setArgument($4);
@@ -1466,11 +1472,11 @@
                 YYERROR;
         }
     }
-    | ':' FUNCTION selector_recovery ')' {
+    | ':' FUNCTION selector_recovery closing_parenthesis {
         YYERROR;
     }
     // used by :not
-    | ':' NOTFUNCTION maybe_space simple_selector maybe_space ')' {
+    | ':' NOTFUNCTION maybe_space simple_selector maybe_space closing_parenthesis {
         if (!$4->isSimple())
             YYERROR;
         else {
@@ -1485,7 +1491,7 @@
             $$->setValue($2);
         }
     }
-    | ':' NOTFUNCTION selector_recovery ')' {
+    | ':' NOTFUNCTION selector_recovery closing_parenthesis {
         YYERROR;
     }
   ;
@@ -1495,17 +1501,11 @@
 
 declaration_list:
     /* empty */ { $$ = false; }
-    | declaration {
-        $$ = $1;
-    }
+    | declaration
     | decl_list declaration {
-        $$ = $1;
-        if ( $2 )
-            $$ = $2;
+        $$ = $1 || $2;
     }
-    | decl_list {
-        $$ = $1;
-    }
+    | decl_list
     ;
 
 decl_list:
@@ -1515,9 +1515,7 @@
     }
     | decl_list declaration ';' maybe_space {
         parser->startProperty();
-        $$ = $1;
-        if ($2)
-            $$ = $2;
+        $$ = $1 || $2;
     }
     ;
 
@@ -1591,10 +1589,13 @@
     }
     | expr operator term {
         $$ = $1;
-        if ($2)
-            $$->addValue(makeOperatorValue($2));
+        $$->addValue(makeOperatorValue($2));
         $$->addValue(parser->sinkFloatingValue($3));
     }
+    | expr term {
+        $$ = $1;
+        $$->addValue(parser->sinkFloatingValue($2));
+    }
   ;
 
 expr_recovery:
@@ -1610,13 +1611,10 @@
   | ',' maybe_space {
         $$ = ',';
     }
-  | /* empty */ {
-        $$ = 0;
-  }
   ;
 
 term:
-  unary_term maybe_space { $$ = $1; }
+  unary_term maybe_space
   | unary_operator unary_term maybe_space { $$ = $2; $$.fValue *= $1; }
   | STRING maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_STRING; }
   | IDENT maybe_space {
@@ -1636,16 +1634,13 @@
       $$.string = $3;
       $$.unit = CSSPrimitiveValue::CSS_VARIABLE_NAME;
   }
+  | VARFUNCTION maybe_space expr_recovery closing_parenthesis {
+      YYERROR;
+  }
   /* FIXME: according to the specs a function can have a unary_operator in front. I know no case where this makes sense */
-  | function maybe_space {
-      $$ = $1;
-  }
-  | calc_function maybe_space {
-      $$ = $1;
-  }
-  | min_or_max_function maybe_space {
-      $$ = $1;
-  }
+  | function maybe_space
+  | calc_function maybe_space
+  | min_or_max_function maybe_space
   | '%' maybe_space { /* Handle width: %; */
       $$.id = CSSValueInvalid; $$.unit = 0;
   }
@@ -1701,7 +1696,7 @@
   ;
 
 calc_func_term:
-  unary_term { $$ = $1; }
+  unary_term
   | VARFUNCTION maybe_space IDENT closing_parenthesis {
       $$.id = CSSValueInvalid;
       $$.string = $3;
@@ -1760,9 +1755,7 @@
   ;
 
 calc_func_expr_list:
-    calc_func_expr calc_maybe_space {
-        $$ = $1;
-    }    
+    calc_func_expr calc_maybe_space
     | calc_func_expr_list ',' maybe_space calc_func_expr calc_maybe_space {
         $$ = $1;
         $$->addValue(makeOperatorValue(','));
@@ -1781,18 +1774,14 @@
 
 
 min_or_max:
-    MINFUNCTION {
-        $$ = $1;
-    }
-    | MAXFUNCTION {
-        $$ = $1;
-    }
+    MINFUNCTION
+    | MAXFUNCTION
     ;
 
 min_or_max_function:
     min_or_max maybe_space calc_func_expr_list closing_parenthesis {
         $$.setFromFunction(parser->createFloatingFunction($1, parser->sinkFloatingValueList($3)));
-    } 
+    }
     | min_or_max maybe_space expr_recovery closing_parenthesis {
         YYERROR;
     }
@@ -1800,7 +1789,7 @@
 
 invalid_at:
     ATKEYWORD
-  | margin_sym 
+  | margin_sym
     ;
 
 at_rule_recovery:
@@ -1814,7 +1803,7 @@
     ;
 
 at_rule_end:
-    at_invalid_rule_header_end ';'
+    at_invalid_rule_header_end semi_or_eof
   | at_invalid_rule_header_end invalid_block
     ;
 
@@ -1843,8 +1832,7 @@
     ;
 
 invalid_square_brackets_block:
-    '[' error_recovery ']'
-  | '[' error_recovery TOKEN_EOF
+    '[' error_recovery closing_square_bracket
     ;
 
 invalid_parentheses_block:
@@ -1859,6 +1847,11 @@
     }
     ;
 
+location_label: {
+        parser->setLocationLabel(parser->currentLocation());
+    }
+    ;
+
 error_recovery:
     /* empty */
   | error_recovery error
diff --git a/Source/core/css/CSSGroupingRule.cpp b/Source/core/css/CSSGroupingRule.cpp
index 90b5256..3a592ff 100644
--- a/Source/core/css/CSSGroupingRule.cpp
+++ b/Source/core/css/CSSGroupingRule.cpp
@@ -38,8 +38,8 @@
 #include "core/css/StyleRule.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/MemoryInstrumentationVector.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSImageGeneratorValue.cpp b/Source/core/css/CSSImageGeneratorValue.cpp
index a9f5eb6..a850d34 100644
--- a/Source/core/css/CSSImageGeneratorValue.cpp
+++ b/Source/core/css/CSSImageGeneratorValue.cpp
@@ -31,9 +31,8 @@
 #include "core/css/CSSGradientValue.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/platform/graphics/Image.h"
-#include <wtf/MemoryInstrumentationHashCountedSet.h>
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/MemoryInstrumentationHashCountedSet.h"
+#include "wtf/MemoryInstrumentationHashMap.h"
 
 
 namespace WTF {
diff --git a/Source/core/css/CSSImageSetValue.cpp b/Source/core/css/CSSImageSetValue.cpp
index 1353606..387081e 100644
--- a/Source/core/css/CSSImageSetValue.cpp
+++ b/Source/core/css/CSSImageSetValue.cpp
@@ -34,7 +34,6 @@
 #include "core/loader/cache/CachedResourceLoader.h"
 #include "core/loader/cache/CachedResourceRequest.h"
 #include "core/loader/cache/CachedResourceRequestInitiators.h"
-#include "core/page/Page.h"
 #include "core/rendering/style/StyleCachedImageSet.h"
 #include "core/rendering/style/StylePendingImage.h"
 #include <wtf/MemoryInstrumentationVector.h>
@@ -90,15 +89,11 @@
     return image;
 }
 
-StyleCachedImageSet* CSSImageSetValue::cachedImageSet(CachedResourceLoader* loader)
+StyleCachedImageSet* CSSImageSetValue::cachedImageSet(CachedResourceLoader* loader, float deviceScaleFactor)
 {
     ASSERT(loader);
 
-    Document* document = loader->document();
-    if (Page* page = document->page())
-        m_scaleFactor = page->deviceScaleFactor();
-    else
-        m_scaleFactor = 1;
+    m_scaleFactor = deviceScaleFactor;
 
     if (!m_imagesInSet.size())
         fillImageSet();
@@ -108,25 +103,23 @@
         // All forms of scale should be included: Page::pageScaleFactor(), Frame::pageZoomFactor(),
         // and any CSS transforms. https://bugs.webkit.org/show_bug.cgi?id=81698
         ImageWithScale image = bestImageForScaleFactor();
-        CachedResourceRequest request(ResourceRequest(document->completeURL(image.imageURL)), cachedResourceRequestInitiators().css);
-        if (CachedResourceHandle<CachedImage> cachedImage = loader->requestImage(request)) {
-            m_imageSet = StyleCachedImageSet::create(cachedImage.get(), image.scaleFactor, this);
-            m_accessedBestFitImage = true;
+        if (Document* document = loader->document()) {
+            CachedResourceRequest request(ResourceRequest(document->completeURL(image.imageURL)), cachedResourceRequestInitiators().css);
+            if (CachedResourceHandle<CachedImage> cachedImage = loader->requestImage(request)) {
+                m_imageSet = StyleCachedImageSet::create(cachedImage.get(), image.scaleFactor, this);
+                m_accessedBestFitImage = true;
+            }
         }
     }
 
     return (m_imageSet && m_imageSet->isCachedImageSet()) ? static_cast<StyleCachedImageSet*>(m_imageSet.get()) : 0;
 }
 
-StyleImage* CSSImageSetValue::cachedOrPendingImageSet(Document* document)
+StyleImage* CSSImageSetValue::cachedOrPendingImageSet(float deviceScaleFactor)
 {
-    if (!m_imageSet)
+    if (!m_imageSet) {
         m_imageSet = StylePendingImage::create(this);
-    else if (document && !m_imageSet->isPendingImage()) {
-        float deviceScaleFactor = 1;
-        if (Page* page = document->page())
-            deviceScaleFactor = page->deviceScaleFactor();
-
+    } else if (!m_imageSet->isPendingImage()) {
         // If the deviceScaleFactor has changed, we may not have the best image loaded, so we have to re-assess.
         if (deviceScaleFactor != m_scaleFactor) {
             m_accessedBestFitImage = false;
diff --git a/Source/core/css/CSSImageSetValue.h b/Source/core/css/CSSImageSetValue.h
index 2f8b037..da81ad2 100644
--- a/Source/core/css/CSSImageSetValue.h
+++ b/Source/core/css/CSSImageSetValue.h
@@ -31,7 +31,6 @@
 namespace WebCore {
 
 class CachedResourceLoader;
-class Document;
 class StyleCachedImageSet;
 class StyleImage;
 
@@ -44,10 +43,10 @@
     }
     ~CSSImageSetValue();
 
-    StyleCachedImageSet* cachedImageSet(CachedResourceLoader*);
+    StyleCachedImageSet* cachedImageSet(CachedResourceLoader*, float deviceScaleFactor);
 
     // Returns a StyleCachedImageSet if the best fit image has been cached already, otherwise a StylePendingImage.
-    StyleImage* cachedOrPendingImageSet(Document*);
+    StyleImage* cachedOrPendingImageSet(float);
 
     String customCssText() const;
 
diff --git a/Source/core/css/CSSImageValue.cpp b/Source/core/css/CSSImageValue.cpp
index 9ee0508..2769433 100644
--- a/Source/core/css/CSSImageValue.cpp
+++ b/Source/core/css/CSSImageValue.cpp
@@ -60,14 +60,14 @@
     return m_image.get();
 }
 
-StyleCachedImage* CSSImageValue::cachedImage(CachedResourceLoader* loader)
+StyleCachedImage* CSSImageValue::cachedImage(CachedResourceLoader* loader, const ResourceLoaderOptions& options)
 {
     ASSERT(loader);
 
     if (!m_accessedImage) {
         m_accessedImage = true;
 
-        CachedResourceRequest request(ResourceRequest(loader->document()->completeURL(m_url)), m_initiatorName.isEmpty() ? cachedResourceRequestInitiators().css : m_initiatorName);
+        CachedResourceRequest request(ResourceRequest(loader->document()->completeURL(m_url)), m_initiatorName.isEmpty() ? cachedResourceRequestInitiators().css : m_initiatorName, options);
         if (CachedResourceHandle<CachedImage> cachedImage = loader->requestImage(request))
             m_image = StyleCachedImage::create(cachedImage.get());
     }
@@ -107,7 +107,7 @@
 {
     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
     info.addMember(m_url, "url");
-    // No need to report m_image as it is counted as part of RenderArena.
+    // FIXME: report m_image. It has never been allocated from any of our rendering custom heaps.
 }
 
 bool CSSImageValue::knownToBeOpaque(const RenderObject* renderer) const
diff --git a/Source/core/css/CSSImageValue.h b/Source/core/css/CSSImageValue.h
index 7b5522c..49e9818 100644
--- a/Source/core/css/CSSImageValue.h
+++ b/Source/core/css/CSSImageValue.h
@@ -22,11 +22,11 @@
 #define CSSImageValue_h
 
 #include "core/css/CSSValue.h"
+#include "core/loader/cache/CachedResourceLoader.h"
 #include <wtf/RefPtr.h>
 
 namespace WebCore {
 
-class CachedResourceLoader;
 class Element;
 class StyleCachedImage;
 class StyleImage;
@@ -38,7 +38,8 @@
     static PassRefPtr<CSSImageValue> create(const String& url, StyleImage* image) { return adoptRef(new CSSImageValue(url, image)); }
     ~CSSImageValue();
 
-    StyleCachedImage* cachedImage(CachedResourceLoader*);
+    StyleCachedImage* cachedImage(CachedResourceLoader*, const ResourceLoaderOptions&);
+    StyleCachedImage* cachedImage(CachedResourceLoader* loader) { return cachedImage(loader, CachedResourceLoader::defaultCachedResourceOptions()); }
     // Returns a StyleCachedImage if the image is cached already, otherwise a StylePendingImage.
     StyleImage* cachedOrPendingImage();
 
diff --git a/Source/core/css/CSSLineBoxContainValue.h b/Source/core/css/CSSLineBoxContainValue.h
index 79e36d5..5b68ba5 100644
--- a/Source/core/css/CSSLineBoxContainValue.h
+++ b/Source/core/css/CSSLineBoxContainValue.h
@@ -27,8 +27,7 @@
 #define CSSLineBoxContainValue_h
 
 #include "core/css/CSSValue.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSMatrix.h b/Source/core/css/CSSMatrix.h
index a353304..dea37ac 100644
--- a/Source/core/css/CSSMatrix.h
+++ b/Source/core/css/CSSMatrix.h
@@ -29,7 +29,6 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/platform/graphics/transforms/TransformationMatrix.h"
 #include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
diff --git a/Source/core/css/CSSMediaRule.cpp b/Source/core/css/CSSMediaRule.cpp
index c9b3548..b8f4ebb 100644
--- a/Source/core/css/CSSMediaRule.cpp
+++ b/Source/core/css/CSSMediaRule.cpp
@@ -25,8 +25,7 @@
 
 #include "core/css/StyleRule.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSOMUtils.h b/Source/core/css/CSSOMUtils.h
index 878669c..3239ada 100644
--- a/Source/core/css/CSSOMUtils.h
+++ b/Source/core/css/CSSOMUtils.h
@@ -31,9 +31,8 @@
 #ifndef CSSOMUtils_h
 #define CSSOMUtils_h
 
-#include <wtf/Forward.h>
-#include <wtf/Vector.h>
-#include <wtf/unicode/Unicode.h>
+#include "wtf/Forward.h"
+#include "wtf/unicode/Unicode.h"
 
 // Utilities for CSSOM http://dev.w3.org/csswg/cssom/
 
diff --git a/Source/core/css/CSSPageRule.cpp b/Source/core/css/CSSPageRule.cpp
index c13ba3a..d29dddb 100644
--- a/Source/core/css/CSSPageRule.cpp
+++ b/Source/core/css/CSSPageRule.cpp
@@ -28,8 +28,7 @@
 #include "core/css/PropertySetCSSStyleDeclaration.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleRule.h"
-#include <wtf/text/StringBuilder.h>
-#include <wtf/Vector.h>
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSParser.cpp b/Source/core/css/CSSParser.cpp
index 3ef33b0..63f4985 100644
--- a/Source/core/css/CSSParser.cpp
+++ b/Source/core/css/CSSParser.cpp
@@ -79,7 +79,6 @@
 #include "core/page/Settings.h"
 #include "core/platform/FloatConversion.h"
 #include "core/platform/HashTools.h"
-#include "core/platform/HistogramSupport.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/svg/SVGParserUtilities.h"
 #include "wtf/BitArray.h"
@@ -340,7 +339,8 @@
     for (unsigned i = 0; i < m_parsedTextPrefixLength; i++)
         m_dataStart16[i] = prefix[i];
 
-    memcpy(m_dataStart16.get() + m_parsedTextPrefixLength, string.characters(), stringLength * sizeof(UChar));
+    ASSERT(stringLength);
+    memcpy(m_dataStart16.get() + m_parsedTextPrefixLength, string.characters16(), stringLength * sizeof(UChar));
 
     unsigned start = m_parsedTextPrefixLength + stringLength;
     unsigned end = start + suffixLength;
@@ -379,7 +379,7 @@
 {
     setStyleSheet(sheet);
     m_allowNamespaceDeclarations = false;
-    setupParser("@-internal-rule{", string, "} ");
+    setupParser("@-internal-rule ", string, "");
     cssyyparse(this);
     return m_rule.release();
 }
@@ -387,7 +387,7 @@
 PassRefPtr<StyleKeyframe> CSSParser::parseKeyframeRule(StyleSheetContents* sheet, const String& string)
 {
     setStyleSheet(sheet);
-    setupParser("@-webkit-keyframe-rule{ ", string, "} ");
+    setupParser("@-internal-keyframe-rule ", string, "");
     cssyyparse(this);
     return m_keyframe.release();
 }
@@ -395,7 +395,7 @@
 bool CSSParser::parseSupportsCondition(const String& string)
 {
     m_supportsCondition = false;
-    setupParser("@-webkit-supports-condition{ ", string, "} ");
+    setupParser("@-internal-supports-condition ", string, "");
     cssyyparse(this);
     return m_supportsCondition;
 }
@@ -762,27 +762,27 @@
         if (valueID == CSSValueStart || valueID == CSSValueEnd || valueID == CSSValueCenter || valueID == CSSValueJustify)
             return true;
         break;
-    case CSSPropertyWebkitAlignContent:
+    case CSSPropertyAlignContent:
          if (valueID == CSSValueFlexStart || valueID == CSSValueFlexEnd || valueID == CSSValueCenter || valueID == CSSValueSpaceBetween || valueID == CSSValueSpaceAround || valueID == CSSValueStretch)
              return true;
          break;
-    case CSSPropertyWebkitAlignItems:
+    case CSSPropertyAlignItems:
         if (valueID == CSSValueFlexStart || valueID == CSSValueFlexEnd || valueID == CSSValueCenter || valueID == CSSValueBaseline || valueID == CSSValueStretch)
             return true;
         break;
-    case CSSPropertyWebkitAlignSelf:
+    case CSSPropertyAlignSelf:
         if (valueID == CSSValueAuto || valueID == CSSValueFlexStart || valueID == CSSValueFlexEnd || valueID == CSSValueCenter || valueID == CSSValueBaseline || valueID == CSSValueStretch)
             return true;
         break;
-    case CSSPropertyWebkitFlexDirection:
+    case CSSPropertyFlexDirection:
         if (valueID == CSSValueRow || valueID == CSSValueRowReverse || valueID == CSSValueColumn || valueID == CSSValueColumnReverse)
             return true;
         break;
-    case CSSPropertyWebkitFlexWrap:
+    case CSSPropertyFlexWrap:
         if (valueID == CSSValueNowrap || valueID == CSSValueWrap || valueID == CSSValueWrapReverse)
              return true;
         break;
-    case CSSPropertyWebkitJustifyContent:
+    case CSSPropertyJustifyContent:
         if (valueID == CSSValueFlexStart || valueID == CSSValueFlexEnd || valueID == CSSValueCenter || valueID == CSSValueSpaceBetween || valueID == CSSValueSpaceAround)
             return true;
         break;
@@ -985,12 +985,12 @@
     case CSSPropertyWebkitColumnBreakBefore:
     case CSSPropertyWebkitColumnBreakInside:
     case CSSPropertyWebkitColumnRuleStyle:
-    case CSSPropertyWebkitAlignContent:
-    case CSSPropertyWebkitAlignItems:
-    case CSSPropertyWebkitAlignSelf:
-    case CSSPropertyWebkitFlexDirection:
-    case CSSPropertyWebkitFlexWrap:
-    case CSSPropertyWebkitJustifyContent:
+    case CSSPropertyAlignContent:
+    case CSSPropertyAlignItems:
+    case CSSPropertyAlignSelf:
+    case CSSPropertyFlexDirection:
+    case CSSPropertyFlexWrap:
+    case CSSPropertyJustifyContent:
     case CSSPropertyWebkitFontKerning:
     case CSSPropertyWebkitFontSmoothing:
     case CSSPropertyWebkitHyphens:
@@ -1196,7 +1196,7 @@
 
     setStyleSheet(contextStyleSheet);
 
-    setupParser("@-internal-value{", string, "} ");
+    setupParser("@-internal-value ", string, "");
 
     m_id = propertyID;
     m_important = important;
@@ -1246,7 +1246,7 @@
 
 bool CSSParser::parseColor(const String& string)
 {
-    setupParser("@-internal-decls{color:", string, "} ");
+    setupParser("@-internal-decls color:", string, "");
     cssyyparse(this);
     m_rule = 0;
 
@@ -1272,7 +1272,7 @@
 {
     m_selectorListForParseSelector = &selectorList;
 
-    setupParser("@-internal-selector{", string, "}");
+    setupParser("@-internal-selector ", string, "");
 
     cssyyparse(this);
 
@@ -1291,7 +1291,7 @@
 {
     setStyleSheet(contextStyleSheet);
 
-    setupParser("@-internal-decls{", string, "} ");
+    setupParser("@-internal-decls ", string, "");
     cssyyparse(this);
     m_rule = 0;
 
@@ -1310,7 +1310,7 @@
 
     m_sourceDataHandler = sourceDataHandler;
 
-    setupParser("@-internal-decls{", string, "} ");
+    setupParser("@-internal-decls ", string, "");
     if (m_sourceDataHandler) {
         m_sourceDataHandler->startRuleHeader(CSSRuleSourceData::STYLE_RULE, 0);
         m_sourceDataHandler->endRuleHeader(1);
@@ -2287,28 +2287,28 @@
 
         validPrimitive = true;
         break;
-    case CSSPropertyWebkitFlex: {
+    case CSSPropertyFlex: {
         ShorthandScope scope(this, propId);
         if (id == CSSValueNone) {
-            addProperty(CSSPropertyWebkitFlexGrow, cssValuePool().createValue(0, CSSPrimitiveValue::CSS_NUMBER), important);
-            addProperty(CSSPropertyWebkitFlexShrink, cssValuePool().createValue(0, CSSPrimitiveValue::CSS_NUMBER), important);
-            addProperty(CSSPropertyWebkitFlexBasis, cssValuePool().createIdentifierValue(CSSValueAuto), important);
+            addProperty(CSSPropertyFlexGrow, cssValuePool().createValue(0, CSSPrimitiveValue::CSS_NUMBER), important);
+            addProperty(CSSPropertyFlexShrink, cssValuePool().createValue(0, CSSPrimitiveValue::CSS_NUMBER), important);
+            addProperty(CSSPropertyFlexBasis, cssValuePool().createIdentifierValue(CSSValueAuto), important);
             return true;
         }
         return parseFlex(m_valueList.get(), important);
     }
-    case CSSPropertyWebkitFlexBasis:
+    case CSSPropertyFlexBasis:
         // FIXME: Support intrinsic dimensions too.
         if (id == CSSValueAuto)
             validPrimitive = true;
         else
             validPrimitive = (!id && validUnit(value, FLength | FPercent | FNonNeg));
         break;
-    case CSSPropertyWebkitFlexGrow:
-    case CSSPropertyWebkitFlexShrink:
+    case CSSPropertyFlexGrow:
+    case CSSPropertyFlexShrink:
         validPrimitive = validUnit(value, FNumber | FNonNeg);
         break;
-    case CSSPropertyWebkitOrder:
+    case CSSPropertyOrder:
         if (validUnit(value, FInteger, CSSStrictMode)) {
             // We restrict the smallest value to int min + 2 because we use int min and int min + 1 as special values in a hash set.
             parsedValue = cssValuePool().createValue(max(static_cast<double>(std::numeric_limits<int>::min() + 2), value->fValue),
@@ -2432,19 +2432,19 @@
     case CSSPropertyGridAutoRows:
         if (!RuntimeEnabledFeatures::cssGridLayoutEnabled())
             return false;
-        parsedValue = parseGridTrackSize();
+        parsedValue = parseGridTrackSize(*m_valueList);
         break;
 
-    case CSSPropertyGridColumns:
-    case CSSPropertyGridRows:
+    case CSSPropertyGridDefinitionColumns:
+    case CSSPropertyGridDefinitionRows:
         if (!RuntimeEnabledFeatures::cssGridLayoutEnabled())
             return false;
         return parseGridTrackList(propId, important);
 
-    case CSSPropertyGridStart:
-    case CSSPropertyGridEnd:
-    case CSSPropertyGridBefore:
-    case CSSPropertyGridAfter:
+    case CSSPropertyGridColumnEnd:
+    case CSSPropertyGridColumnStart:
+    case CSSPropertyGridRowEnd:
+    case CSSPropertyGridRowStart:
         if (!RuntimeEnabledFeatures::cssGridLayoutEnabled())
             return false;
         parsedValue = parseGridPosition();
@@ -2647,8 +2647,8 @@
     case CSSPropertyPadding:
         // <padding-width>{1,4} | inherit
         return parse4Values(propId, paddingShorthand().properties(), important);
-    case CSSPropertyWebkitFlexFlow:
-        return parseShorthand(propId, webkitFlexFlowShorthand(), important);
+    case CSSPropertyFlexFlow:
+        return parseShorthand(propId, flexFlowShorthand(), important);
     case CSSPropertyFont:
         // [ [ 'font-style' || 'font-variant' || 'font-weight' ]? 'font-size' [ / 'line-height' ]?
         // 'font-family' ] | caption | icon | menu | message-box | small-caption | status-bar | inherit
@@ -2795,12 +2795,12 @@
     case CSSPropertyWebkitColumnBreakBefore:
     case CSSPropertyWebkitColumnBreakInside:
     case CSSPropertyWebkitColumnRuleStyle:
-    case CSSPropertyWebkitAlignContent:
-    case CSSPropertyWebkitAlignItems:
-    case CSSPropertyWebkitAlignSelf:
-    case CSSPropertyWebkitFlexDirection:
-    case CSSPropertyWebkitFlexWrap:
-    case CSSPropertyWebkitJustifyContent:
+    case CSSPropertyAlignContent:
+    case CSSPropertyAlignItems:
+    case CSSPropertyAlignSelf:
+    case CSSPropertyFlexDirection:
+    case CSSPropertyFlexWrap:
+    case CSSPropertyJustifyContent:
     case CSSPropertyWebkitFontKerning:
     case CSSPropertyWebkitFontSmoothing:
     case CSSPropertyWebkitHyphens:
@@ -3049,7 +3049,7 @@
     if (!value)
         return;
 
-    static const unsigned prefixLength = sizeof("-webkit-var-") - 1;
+    static const unsigned prefixLength = sizeof("var-") - 1;
 
     ASSERT(name.length() > prefixLength);
     AtomicString variableName = name.atomicSubstring(prefixLength, name.length() - prefixLength);
@@ -4595,34 +4595,93 @@
     }
 
     RefPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
-    size_t currentLineNumber = 0;
-    while (m_valueList->current()) {
+    // Handle leading <string>*.
+    while (m_valueList->current() && m_valueList->current()->unit == CSSPrimitiveValue::CSS_STRING) {
+        RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(m_valueList->current());
+        values->append(name);
+        m_valueList->next();
+    }
+
+    bool seenTrackSizeOrRepeatFunction = false;
+    while (CSSParserValue* currentValue = m_valueList->current()) {
+        if (currentValue->unit == CSSParserValue::Function && equalIgnoringCase(currentValue->function->name, "repeat(")) {
+            if (!parseGridTrackRepeatFunction(*values))
+                return false;
+            seenTrackSizeOrRepeatFunction = true;
+        } else {
+            RefPtr<CSSPrimitiveValue> primitiveValue = parseGridTrackSize(*m_valueList);
+            if (!primitiveValue)
+                return false;
+            values->append(primitiveValue);
+            seenTrackSizeOrRepeatFunction = true;
+        }
+
+        // This will handle the trailing <string>* in the grammar.
         while (m_valueList->current() && m_valueList->current()->unit == CSSPrimitiveValue::CSS_STRING) {
             RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(m_valueList->current());
             values->append(name);
             m_valueList->next();
         }
-
-        // This allows trailing <string>* per the specification.
-        if (!m_valueList->current())
-            break;
-
-        RefPtr<CSSPrimitiveValue> primitiveValue = parseGridTrackSize();
-        if (!primitiveValue)
-            return false;
-
-        values->append(primitiveValue.release());
     }
+
+    // We should have found a <track-size> or else it is not a valid <track-list>
+    if (!seenTrackSizeOrRepeatFunction)
+        return false;
+
     addProperty(propId, values.release(), important);
     return true;
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSParser::parseGridTrackSize()
+bool CSSParser::parseGridTrackRepeatFunction(CSSValueList& list)
+{
+    CSSParserValueList* arguments = m_valueList->current()->function->args.get();
+    if (!arguments || arguments->size() < 3 || !validUnit(arguments->valueAt(0), FPositiveInteger) || !isComma(arguments->valueAt(1)))
+        return false;
+
+    ASSERT_WITH_SECURITY_IMPLICATION(arguments->valueAt(0)->fValue > 0);
+    size_t repetitions = arguments->valueAt(0)->fValue;
+    RefPtr<CSSValueList> repeatedValues = CSSValueList::createSpaceSeparated();
+    arguments->next(); // Skip the repetition count.
+    arguments->next(); // Skip the comma.
+
+    // Handle leading <string>*.
+    while (arguments->current() && arguments->current()->unit == CSSPrimitiveValue::CSS_STRING) {
+        RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(arguments->current());
+        repeatedValues->append(name);
+        arguments->next();
+    }
+
+    while (CSSParserValue* argumentValue = arguments->current()) {
+        RefPtr<CSSPrimitiveValue> trackSize = parseGridTrackSize(*arguments);
+        if (!trackSize)
+            return false;
+
+        repeatedValues->append(trackSize);
+
+        // This takes care of any trailing <string>* in the grammar.
+        while (arguments->current() && arguments->current()->unit == CSSPrimitiveValue::CSS_STRING) {
+            RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(arguments->current());
+            repeatedValues->append(name);
+            arguments->next();
+        }
+    }
+
+    for (size_t i = 0; i < repetitions; ++i) {
+        for (size_t j = 0; j < repeatedValues->length(); ++j)
+            list.append(repeatedValues->itemWithoutBoundsCheck(j));
+    }
+
+    // parseGridTrackSize iterated over the repeat arguments, move to the next value.
+    m_valueList->next();
+    return true;
+}
+
+PassRefPtr<CSSPrimitiveValue> CSSParser::parseGridTrackSize(CSSParserValueList& inputList)
 {
     ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
 
-    CSSParserValue* currentValue = m_valueList->current();
-    m_valueList->next();
+    CSSParserValue* currentValue = inputList.current();
+    inputList.next();
 
     if (currentValue->id == CSSValueAuto)
         return cssValuePool().createIdentifierValue(CSSValueAuto);
@@ -4644,15 +4703,12 @@
         return createPrimitiveValuePair(minTrackBreadth, maxTrackBreadth);
     }
 
-    if (PassRefPtr<CSSPrimitiveValue> trackBreadth = parseGridBreadth(currentValue))
-        return trackBreadth;
-
-    return 0;
+    return parseGridBreadth(currentValue);
 }
 
 PassRefPtr<CSSPrimitiveValue> CSSParser::parseGridBreadth(CSSParserValue* currentValue)
 {
-    if (currentValue->id == CSSValueWebkitMinContent || currentValue->id == CSSValueWebkitMaxContent)
+    if (currentValue->id == CSSValueMinContent || currentValue->id == CSSValueMaxContent)
         return cssValuePool().createIdentifierValue(currentValue->id);
 
     if (currentValue->unit == CSSPrimitiveValue::CSS_FR) {
@@ -6276,9 +6332,9 @@
     if (!flexBasis)
         flexBasis = cssValuePool().createValue(0, CSSPrimitiveValue::CSS_PX);
 
-    addProperty(CSSPropertyWebkitFlexGrow, cssValuePool().createValue(clampToFloat(flexGrow), CSSPrimitiveValue::CSS_NUMBER), important);
-    addProperty(CSSPropertyWebkitFlexShrink, cssValuePool().createValue(clampToFloat(flexShrink), CSSPrimitiveValue::CSS_NUMBER), important);
-    addProperty(CSSPropertyWebkitFlexBasis, flexBasis, important);
+    addProperty(CSSPropertyFlexGrow, cssValuePool().createValue(clampToFloat(flexGrow), CSSPrimitiveValue::CSS_NUMBER), important);
+    addProperty(CSSPropertyFlexShrink, cssValuePool().createValue(clampToFloat(flexShrink), CSSPrimitiveValue::CSS_NUMBER), important);
+    addProperty(CSSPropertyFlexBasis, flexBasis, important);
     return true;
 }
 
@@ -7708,7 +7764,7 @@
             const LChar* start = string.characters8();
             parseDouble(start, start + length, 'x', imageScaleFactor);
         } else {
-            const UChar* start = string.characters();
+            const UChar* start = string.characters16();
             parseDouble(start, start + length, 'x', imageScaleFactor);
         }
         if (imageScaleFactor <= 0)
@@ -8686,7 +8742,7 @@
 
 bool CSSParser::parseFlowThread(const String& flowName)
 {
-    setupParser("@-internal-decls{-webkit-flow-into:", flowName, "}");
+    setupParser("@-internal-decls -webkit-flow-into:", flowName, "");
     cssyyparse(this);
 
     m_rule = 0;
@@ -9871,6 +9927,10 @@
             m_token = CUEFUNCTION;
             return true;
         }
+        if (RuntimeEnabledFeatures::cssVariablesEnabled() && isASCIIAlphaCaselessEqual(name[0], 'v') && isASCIIAlphaCaselessEqual(name[1], 'a') && isASCIIAlphaCaselessEqual(name[2], 'r')) {
+            m_token = VARFUNCTION;
+            return true;
+        }
         return false;
 
     case 4:
@@ -10067,8 +10127,6 @@
             m_token = MINFUNCTION;
         else if (isASCIIAlphaCaselessEqual(name[10], 'x') && isEqualToCSSIdentifier(name + 1, "webkit-ma"))
             m_token = MAXFUNCTION;
-        else if (RuntimeEnabledFeatures::cssVariablesEnabled() && isASCIIAlphaCaselessEqual(name[10], 'r') && isEqualToCSSIdentifier(name + 1, "webkit-va"))
-            m_token = VARFUNCTION;
     } else if (length == 12 && isEqualToCSSIdentifier(name + 1, "webkit-calc"))
         m_token = CALCFUNCTION;
     else if (length == 19 && isEqualToCSSIdentifier(name + 1, "webkit-distributed"))
@@ -10281,15 +10339,15 @@
             }
             return;
 
-        case 22:
-            if (!hasEscape && isEqualToCSSIdentifier(name + 2, "webkit-keyframe-rule"))
-                m_token = WEBKIT_KEYFRAME_RULE_SYM;
+        case 24:
+            if (!hasEscape && isEqualToCSSIdentifier(name + 2, "internal-keyframe-rule"))
+                m_token = INTERNAL_KEYFRAME_RULE_SYM;
             return;
 
-        case 27:
-            if (isEqualToCSSIdentifier(name + 2, "webkit-supports-condition")) {
+        case 29:
+            if (isEqualToCSSIdentifier(name + 2, "internal-supports-condition")) {
                 m_parsingMode = SupportsMode;
-                m_token = WEBKIT_SUPPORTS_CONDITION_SYM;
+                m_token = INTERNAL_SUPPORTS_CONDITION_SYM;
             }
             return;
         }
@@ -10314,16 +10372,17 @@
 }
 
 template <typename CharacterType>
-inline bool CSSParser::detectCSSVariablesToken(int length)
+inline void CSSParser::detectCSSVariableDefinitionToken(int length)
 {
-    ASSERT(tokenStart<CharacterType>()[0] == '-');
-    if (length < sizeof("-webkit-var-*") - 1)
-        return false;
+    static const unsigned prefixLength = sizeof("var-") - 1;
+    if (length <= prefixLength)
+        return;
     CharacterType* name = tokenStart<CharacterType>();
-    return name[11] == '-' && isIdentifierStartAfterDash(name + 12) && isEqualToCSSCaseSensitiveIdentifier(name + 1, "webkit-var");
+    COMPILE_ASSERT(prefixLength > 0, CSS_variable_prefix_must_be_nonempty);
+    if (name[prefixLength - 1] == '-' && isIdentifierStartAfterDash(name + prefixLength) && isEqualToCSSCaseSensitiveIdentifier(name, "var"))
+        m_token = VAR_DEFINITION;
 }
 
-
 template <typename SrcCharacterType>
 int CSSParser::realLex(void* yylvalWithoutType)
 {
@@ -10412,6 +10471,8 @@
                     }
                 }
             }
+        } else if (UNLIKELY(RuntimeEnabledFeatures::cssVariablesEnabled())) {
+            detectCSSVariableDefinitionToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
         }
         break;
 
@@ -10498,9 +10559,7 @@
             parseIdentifier(result, resultString, hasEscape);
             m_token = IDENT;
 
-            if (RuntimeEnabledFeatures::cssVariablesEnabled() && detectCSSVariablesToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>()))
-                m_token = VAR_DEFINITION;
-            else if (*currentCharacter<SrcCharacterType>() == '(') {
+            if (*currentCharacter<SrcCharacterType>() == '(') {
                 m_token = FUNCTION;
                 if (!hasEscape)
                     detectDashToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
@@ -10622,6 +10681,7 @@
     case CharacterSlash:
         // Ignore comments. They are not even considered as white spaces.
         if (*currentCharacter<SrcCharacterType>() == '*') {
+            const CSSParserLocation startLocation = currentLocation();
             if (m_sourceDataHandler) {
                 unsigned startOffset = (is8BitSource() ? currentCharacter<LChar>() - m_dataStart8.get() : currentCharacter<UChar>() - m_dataStart16.get()) - 1; // Start with a slash.
                 m_sourceDataHandler->startComment(startOffset - m_parsedTextPrefixLength);
@@ -10633,6 +10693,7 @@
                 if (*currentCharacter<SrcCharacterType>() == '\0') {
                     // Unterminated comments are simply ignored.
                     currentCharacter<SrcCharacterType>() -= 2;
+                    reportError(startLocation, UnterminatedCommentError);
                     break;
                 }
                 ++currentCharacter<SrcCharacterType>();
@@ -11029,7 +11090,7 @@
 
     m_ignoreErrors = true;
     CSSParserString content = location.token;
-    if (error == InvalidPropertyValueError || error == InvalidSelectorError) {
+    if (error == InvalidPropertyValueError || error == InvalidSelectorError || error == InvalidMediaQueryError || error == InvalidKeyframeSelectorError) {
         if (m_source) {
             if (is8BitSource())
                 content.init(*m_source, location.token.characters8() - m_dataStart8.get(), tokenStart<LChar>() - location.token.characters8());
@@ -11068,14 +11129,28 @@
         builder.appendLiteral("Invalid CSS rule at: ");
         break;
 
+    case InvalidMediaQueryError:
+        builder.appendLiteral("Invalid CSS media query: ");
+        break;
+
+    case InvalidSelectorPseudoError:
+        builder.appendLiteral("Invalid CSS selector pseudoclass: ");
+        break;
+
+    case InvalidKeyframeSelectorError:
+        builder.appendLiteral("Invalid CSS keyframe selector: ");
+        break;
+
+    case UnterminatedCommentError:
+        content.setLength(0);
+        builder.appendLiteral("Unterminated CSS comment");
+        break;
+
     default:
         builder.appendLiteral("Unexpected CSS token: ");
     }
 
-    if (content.is8Bit())
-        builder.append(content.characters8(), content.length());
-    else
-        builder.append(content.characters16(), content.length());
+    builder.append(content);
 
     logError(builder.toString(), location.lineNumber);
 }
@@ -11398,11 +11473,6 @@
     m_lastSelectorLineNumber = m_lineNumber;
 }
 
-void CSSParser::updateLastMediaLine(MediaQuerySet* media)
-{
-    media->setLastLine(m_lineNumber);
-}
-
 void CSSParser::startRuleHeader(CSSRuleSourceData::Type ruleType)
 {
     resumeErrorLogging();
@@ -11596,7 +11666,7 @@
     if (length > maxCSSPropertyNameLength)
         return CSSPropertyInvalid;
 
-    return string.is8Bit() ? cssPropertyID(string.characters8(), length) : cssPropertyID(string.characters(), length);
+    return string.is8Bit() ? cssPropertyID(string.characters8(), length) : cssPropertyID(string.characters16(), length);
 }
 
 CSSPropertyID cssPropertyID(const CSSParserString& string)
@@ -11682,7 +11752,7 @@
 
     if (string.is8Bit())
         return isCSSTokenizerIdentifier(string.characters8(), length);
-    return isCSSTokenizerIdentifier(string.characters(), length);
+    return isCSSTokenizerIdentifier(string.characters16(), length);
 }
 
 template <typename CharacterType>
@@ -11722,7 +11792,7 @@
 
     if (string.is8Bit())
         return isCSSTokenizerURL(string.characters8(), length);
-    return isCSSTokenizerURL(string.characters(), length);
+    return isCSSTokenizerURL(string.characters16(), length);
 }
 
 
diff --git a/Source/core/css/CSSParser.h b/Source/core/css/CSSParser.h
index 5631695..d1ecd6b 100644
--- a/Source/core/css/CSSParser.h
+++ b/Source/core/css/CSSParser.h
@@ -36,7 +36,6 @@
 #include "core/css/MediaQuery.h"
 #include "core/page/UseCounter.h"
 #include "core/platform/graphics/Color.h"
-#include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
 #include "wtf/OwnArrayPtr.h"
 #include "wtf/Vector.h"
@@ -66,9 +65,11 @@
 class StyleRuleKeyframes;
 class StyleKeyframe;
 class StyleSheetContents;
-class StyledElement;
 
-struct CSSParserLocation;
+struct CSSParserLocation {
+    int lineNumber;
+    CSSParserString token;
+};
 
 class CSSParser {
     friend inline int cssyylex(void*, CSSParser*);
@@ -83,6 +84,10 @@
         InvalidSelectorError,
         InvalidSupportsConditionError,
         InvalidRuleError,
+        InvalidMediaQueryError,
+        InvalidKeyframeSelectorError,
+        InvalidSelectorPseudoError,
+        UnterminatedCommentError,
         GeneralError
     };
 
@@ -166,7 +171,8 @@
     bool parseIntegerOrStringFromGridPosition(RefPtr<CSSPrimitiveValue>& numericValue, RefPtr<CSSPrimitiveValue>& gridLineName);
     bool parseGridItemPositionShorthand(CSSPropertyID, bool important);
     bool parseGridTrackList(CSSPropertyID, bool important);
-    PassRefPtr<CSSPrimitiveValue> parseGridTrackSize();
+    bool parseGridTrackRepeatFunction(CSSValueList&);
+    PassRefPtr<CSSPrimitiveValue> parseGridTrackSize(CSSParserValueList& inputList);
     PassRefPtr<CSSPrimitiveValue> parseGridBreadth(CSSParserValue*);
 
     bool parseClipShape(CSSPropertyID, bool important);
@@ -343,7 +349,6 @@
     Vector<OwnPtr<CSSParserSelector> >* reusableRegionSelectorVector() { return &m_reusableRegionSelectorVector; }
 
     void updateLastSelectorLineAndPosition();
-    void updateLastMediaLine(MediaQuerySet*);
 
     void clearProperties();
 
@@ -397,6 +402,8 @@
     void endInvalidRuleHeader();
     void reportError(const CSSParserLocation&, ErrorType = GeneralError);
     void resumeErrorLogging() { m_ignoreErrors = false; }
+    void setLocationLabel(const CSSParserLocation& location) { m_locationLabel = location; }
+    const CSSParserLocation& lastLocationLabel() const { return m_locationLabel; }
 
     inline int lex(void* yylval) { return (this->*m_lexFunc)(yylval); }
 
@@ -508,7 +515,7 @@
     template <typename CharacterType>
     inline void detectSupportsToken(int);
     template <typename CharacterType>
-    inline bool detectCSSVariablesToken(int);
+    inline void detectCSSVariableDefinitionToken(int);
 
     void setStyleSheet(StyleSheetContents* styleSheet) { m_styleSheet = styleSheet; }
 
@@ -590,6 +597,8 @@
     bool inViewport() const { return m_inViewport; }
     bool m_inViewport;
 
+    CSSParserLocation m_locationLabel;
+
     int (CSSParser::*m_lexFunc)(void*);
 
     Vector<RefPtr<StyleRuleBase> > m_parsedRules;
@@ -685,11 +694,6 @@
     CSSParser* m_parser;
 };
 
-struct CSSParserLocation {
-    int lineNumber;
-    CSSParserString token;
-};
-
 class CSSParser::SourceDataHandler {
 public:
     virtual void startRuleHeader(CSSRuleSourceData::Type, unsigned offset) = 0;
diff --git a/Source/core/css/CSSParserValues.h b/Source/core/css/CSSParserValues.h
index 79888d6..b136975 100644
--- a/Source/core/css/CSSParserValues.h
+++ b/Source/core/css/CSSParserValues.h
@@ -56,11 +56,11 @@
     void init(const String& string, unsigned startOffset, unsigned length)
     {
         m_length = length;
-        if (m_length && string.is8Bit()) {
+        if (!m_length || string.is8Bit()) {
             m_data.characters8 = const_cast<LChar*>(string.characters8()) + startOffset;
             m_is8Bit = true;
         } else {
-            m_data.characters16 = const_cast<UChar*>(string.characters()) + startOffset;
+            m_data.characters16 = const_cast<UChar*>(string.characters16()) + startOffset;
             m_is8Bit = false;
         }
     }
@@ -69,7 +69,7 @@
     {
         m_data.characters8 = 0;
         m_length = 0;
-        m_is8Bit = false;
+        m_is8Bit = true;
     }
 
     void trimTrailingWhitespace();
@@ -111,7 +111,7 @@
         return is8Bit() ? WTF::equalIgnoringCase(str, characters8(), strLength) : WTF::equalIgnoringCase(str, characters16(), strLength);
     }
 
-    operator String() const { return is8Bit() ? String(m_data.characters8, m_length) : String(m_data.characters16, m_length); }
+    operator String() const { return is8Bit() ? String(m_data.characters8, m_length) : StringImpl::create8BitIfPossible(m_data.characters16, m_length); }
     operator AtomicString() const { return is8Bit() ? AtomicString(m_data.characters8, m_length) : AtomicString(m_data.characters16, m_length); }
 
     AtomicString atomicSubstring(unsigned position, unsigned length) const;
diff --git a/Source/core/css/CSSPrimitiveValue.cpp b/Source/core/css/CSSPrimitiveValue.cpp
index 92f8ada..f1345e1 100644
--- a/Source/core/css/CSSPrimitiveValue.cpp
+++ b/Source/core/css/CSSPrimitiveValue.cpp
@@ -38,11 +38,10 @@
 #include "core/platform/LayoutUnit.h"
 #include "core/platform/graphics/Color.h"
 #include "core/rendering/style/RenderStyle.h"
-#include <wtf/ASCIICType.h>
-#include <wtf/DecimalNumber.h>
-#include <wtf/StdLibExtras.h>
-#include <wtf/text/StringBuffer.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/DecimalNumber.h"
+#include "wtf/StdLibExtras.h"
+#include "wtf/text/StringBuffer.h"
+#include "wtf/text/StringBuilder.h"
 
 using namespace WTF;
 
@@ -157,6 +156,20 @@
     }
 }
 
+bool CSSPrimitiveValue::colorIsDerivedFromElement() const
+{
+    int valueID = getValueID();
+    switch (valueID) {
+    case CSSValueWebkitText:
+    case CSSValueWebkitLink:
+    case CSSValueWebkitActivelink:
+    case CSSValueCurrentcolor:
+        return true;
+    default:
+        return false;
+    }
+}
+
 typedef HashMap<const CSSPrimitiveValue*, String> CSSTextCache;
 static CSSTextCache& cssTextCache()
 {
@@ -284,11 +297,11 @@
             break;
         case MinContent:
             m_primitiveUnitType = CSS_VALUE_ID;
-            m_value.valueID = CSSValueWebkitMinContent;
+            m_value.valueID = CSSValueMinContent;
             break;
         case MaxContent:
             m_primitiveUnitType = CSS_VALUE_ID;
-            m_value.valueID = CSSValueWebkitMaxContent;
+            m_value.valueID = CSSValueMaxContent;
             break;
         case FillAvailable:
             m_primitiveUnitType = CSS_VALUE_ID;
@@ -860,7 +873,7 @@
     return formatNumber(number, characters, characterCount - 1);
 }
 
-String CSSPrimitiveValue::customCssText() const
+String CSSPrimitiveValue::customCssText(CssTextFormattingFlags formattingFlag) const
 {
     // FIXME: return the original value instead of a generated one (e.g. color
     // name if it was specified) - check what spec says about this
@@ -949,7 +962,7 @@
             text = m_value.string;
             break;
         case CSS_STRING:
-            text = quoteCSSStringIfNeeded(m_value.string);
+            text = formattingFlag == AlwaysQuoteCSSString ? quoteCSSString(m_value.string) : quoteCSSStringIfNeeded(m_value.string);
             break;
         case CSS_URI:
             text = "url(" + quoteCSSURLIfNeeded(m_value.string) + ")";
@@ -1066,7 +1079,7 @@
             text = formatNumber(m_value.num, "vmax");
             break;
         case CSS_VARIABLE_NAME:
-            text = "-webkit-var(" + String(m_value.string) + ")";
+            text = "var(" + String(m_value.string) + ")";
             break;
     }
 
diff --git a/Source/core/css/CSSPrimitiveValue.h b/Source/core/css/CSSPrimitiveValue.h
index 8e677b1..3571cb0 100644
--- a/Source/core/css/CSSPrimitiveValue.h
+++ b/Source/core/css/CSSPrimitiveValue.h
@@ -120,7 +120,7 @@
         // This is used internally for counter names (as opposed to counter values)
         CSS_COUNTER_NAME = 110,
 
-        // This is used by the CSS Exclusions draft
+        // This is used by the CSS Shapes draft
         CSS_SHAPE = 111,
 
         // Used by border images.
@@ -195,6 +195,7 @@
     bool isViewportPercentageLength() const { return m_primitiveUnitType >= CSS_VW && m_primitiveUnitType <= CSS_VMAX; }
     bool isFlex() const { return primitiveType() == CSS_FR; }
     bool isValueID() const { return m_primitiveUnitType == CSS_VALUE_ID; }
+    bool colorIsDerivedFromElement() const;
 
     static PassRefPtr<CSSPrimitiveValue> createIdentifier(CSSValueID valueID) { return adoptRef(new CSSPrimitiveValue(valueID)); }
     static PassRefPtr<CSSPrimitiveValue> createIdentifier(CSSPropertyID propertyID) { return adoptRef(new CSSPrimitiveValue(propertyID)); }
@@ -305,7 +306,7 @@
 
     template<typename T> inline operator T() const; // Defined in CSSPrimitiveValueMappings.h
 
-    String customCssText() const;
+    String customCssText(CssTextFormattingFlags = QuoteCSSStringIfNeeded) const;
     String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
     bool hasVariableReference() const;
 
diff --git a/Source/core/css/CSSPrimitiveValueMappings.h b/Source/core/css/CSSPrimitiveValueMappings.h
index 28ff567..d9a01fb 100644
--- a/Source/core/css/CSSPrimitiveValueMappings.h
+++ b/Source/core/css/CSSPrimitiveValueMappings.h
@@ -1242,10 +1242,10 @@
         m_value.valueID = CSSValueWebkitInlineBox;
         break;
     case FLEX:
-        m_value.valueID = CSSValueWebkitFlex;
+        m_value.valueID = CSSValueFlex;
         break;
     case INLINE_FLEX:
-        m_value.valueID = CSSValueWebkitInlineFlex;
+        m_value.valueID = CSSValueInlineFlex;
         break;
     case GRID:
         m_value.valueID = CSSValueGrid;
@@ -1267,6 +1267,11 @@
     if (m_value.valueID == CSSValueNone)
         return NONE;
 
+    if (m_value.valueID == CSSValueWebkitFlex)
+        return FLEX;
+    if (m_value.valueID == CSSValueWebkitInlineFlex)
+        return INLINE_FLEX;
+
     EDisplay display = static_cast<EDisplay>(m_value.valueID - CSSValueInline);
     ASSERT(display >= INLINE && display <= NONE);
     return display;
diff --git a/Source/core/css/CSSProperties.in b/Source/core/css/CSSProperties.in
index 5ccc5c5..cefab14 100644
--- a/Source/core/css/CSSProperties.in
+++ b/Source/core/css/CSSProperties.in
@@ -2,6 +2,9 @@
 //   should use this for make_css_property_names.py
 // Note: Mandatory blank line to skip parameter parsing phase
 
+align-content
+align-items
+align-self type_name=EAlignItems
 background-attachment custom_all
 background-blend-mode custom_all
 background-clip custom_all
@@ -28,9 +31,15 @@
 clear
 color custom_all
 empty-cells type_name=EEmptyCell
+flex-basis apply_type=length, use_auto
+flex-direction
+flex-grow type_name=float
+flex-shrink type_name=float
+flex-wrap
 float type_name=EFloat, name_for_methods=Floating
 grid-auto-flow type_name=GridAutoFlow
 height apply_type=length, initial=initialSize, use_auto, use_intrinsic
+justify-content
 image-rendering
 left apply_type=length, initial=initialOffset, use_auto
 list-style-position
@@ -45,6 +54,7 @@
 min-width apply_type=length, initial=initialMinSize, use_auto, use_intrinsic
 mix-blend-mode type_name=BlendMode, name_for_methods=BlendMode
 opacity type_name=float
+order type_name=int
 orphans type_name=short, custom_all
 outline-color custom_all
 overflow-wrap
@@ -80,9 +90,14 @@
 zoom custom_all
 z-index type_name=int, custom_all
 
--webkit-align-content
--webkit-align-items
--webkit-align-self type_name=EAlignItems
+-webkit-animation-delay custom_all
+-webkit-animation-direction custom_all
+-webkit-animation-duration custom_all
+-webkit-animation-fillMode custom_all
+-webkit-animation-iteration-count custom_all
+-webkit-animation-name custom_all
+-webkit-animation-play-state custom_all
+-webkit-animation-timing-function custom_all
 -webkit-appearance type_name=ControlPart
 -webkit-backface-visibility
 -webkit-background-clip use_handlers_for=CSSPropertyBackgroundClip
@@ -111,11 +126,6 @@
 -webkit-column-rule-style type_name=EBorderStyle, initial=initialBorderStyle
 -webkit-column-span type_name=ColumnSpan
 -webkit-column-width type_name=float, custom_all
--webkit-flex-basis apply_type=length, use_auto
--webkit-flex-direction
--webkit-flex-grow type_name=float
--webkit-flex-shrink type_name=float
--webkit-flex-wrap
 -webkit-flow-from type_name=const AtomicString&, name_for_methods=RegionThread, custom_value
 -webkit-flow-into type_name=const AtomicString&, name_for_methods=FlowThread, custom_value
 -webkit-highlight type_name=const AtomicString&, custom_value
@@ -124,7 +134,6 @@
 -webkit-hyphenate-limit-before type_name=short, name_for_methods=HyphenationLimitBefore, custom_value
 -webkit-hyphenate-limit-lines type_name=short, name_for_methods=HyphenationLimitLines, custom_value
 -webkit-hyphens type_name=Hyphens
--webkit-justify-content
 -webkit-line-align type_name=LineAlign
 -webkit-line-break type_name=LineBreak
 -webkit-line-clamp type_name=LineClampValue
@@ -148,7 +157,6 @@
 -webkit-mask-repeat-x custom_all
 -webkit-mask-repeat-y custom_all
 -webkit-mask-size custom_all
--webkit-order type_name=int
 -webkit-perspective-origin-x apply_type=length
 -webkit-perspective-origin-y apply_type=length
 -webkit-print-color-adjust type_name=PrintColorAdjust
@@ -170,6 +178,10 @@
 -webkit-transform-origin-x apply_type=length
 -webkit-transform-origin-y apply_type=length
 -webkit-transform-style name_for_methods=TransformStyle3D
+-webkit-transition-delay custom_all
+-webkit-transition-duration custom_all
+-webkit-transition-property custom_all
+-webkit-transition-timing-function custom_all
 -webkit-user-drag
 -webkit-user-modify
 -webkit-user-select
diff --git a/Source/core/css/CSSProperty.cpp b/Source/core/css/CSSProperty.cpp
index d5cca5e..57f9439 100644
--- a/Source/core/css/CSSProperty.cpp
+++ b/Source/core/css/CSSProperty.cpp
@@ -26,8 +26,6 @@
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 
-#include <wtf/text/StringBuilder.h>
-
 namespace WebCore {
 
 struct SameSizeAsCSSProperty {
@@ -503,9 +501,9 @@
     case CSSPropertyUnicodeRange:
     case CSSPropertyVectorEffect:
     case CSSPropertyVerticalAlign:
-    case CSSPropertyWebkitAlignContent:
-    case CSSPropertyWebkitAlignItems:
-    case CSSPropertyWebkitAlignSelf:
+    case CSSPropertyAlignContent:
+    case CSSPropertyAlignItems:
+    case CSSPropertyAlignSelf:
     case CSSPropertyWebkitAnimation:
     case CSSPropertyWebkitAnimationDelay:
     case CSSPropertyWebkitAnimationDirection:
@@ -566,27 +564,27 @@
     case CSSPropertyWebkitColumnWidth:
     case CSSPropertyWebkitColumns:
     case CSSPropertyWebkitFilter:
-    case CSSPropertyWebkitFlex:
-    case CSSPropertyWebkitFlexBasis:
-    case CSSPropertyWebkitFlexDirection:
-    case CSSPropertyWebkitFlexFlow:
-    case CSSPropertyWebkitFlexGrow:
-    case CSSPropertyWebkitFlexShrink:
-    case CSSPropertyWebkitFlexWrap:
+    case CSSPropertyFlex:
+    case CSSPropertyFlexBasis:
+    case CSSPropertyFlexDirection:
+    case CSSPropertyFlexFlow:
+    case CSSPropertyFlexGrow:
+    case CSSPropertyFlexShrink:
+    case CSSPropertyFlexWrap:
     case CSSPropertyWebkitFontSizeDelta:
-    case CSSPropertyGridAfter:
+    case CSSPropertyGridArea:
     case CSSPropertyGridAutoColumns:
     case CSSPropertyGridAutoFlow:
     case CSSPropertyGridAutoRows:
-    case CSSPropertyGridBefore:
     case CSSPropertyGridColumn:
-    case CSSPropertyGridColumns:
-    case CSSPropertyGridEnd:
+    case CSSPropertyGridColumnEnd:
+    case CSSPropertyGridColumnStart:
+    case CSSPropertyGridDefinitionColumns:
+    case CSSPropertyGridDefinitionRows:
     case CSSPropertyGridRow:
-    case CSSPropertyGridRows:
-    case CSSPropertyGridStart:
-    case CSSPropertyGridArea:
-    case CSSPropertyWebkitJustifyContent:
+    case CSSPropertyGridRowEnd:
+    case CSSPropertyGridRowStart:
+    case CSSPropertyJustifyContent:
     case CSSPropertyWebkitLineClamp:
     case CSSPropertyWebkitLogicalHeight:
     case CSSPropertyWebkitLogicalWidth:
@@ -604,7 +602,7 @@
     case CSSPropertyWebkitMarqueeIncrement:
     case CSSPropertyWebkitMarqueeRepetition:
     case CSSPropertyWebkitMarqueeSpeed:
-    case CSSPropertyWebkitOrder:
+    case CSSPropertyOrder:
     case CSSPropertyWebkitMarqueeStyle:
     case CSSPropertyWebkitMask:
     case CSSPropertyWebkitMaskBoxImage:
diff --git a/Source/core/css/CSSProperty.h b/Source/core/css/CSSProperty.h
index 1435888..7b12f9b 100644
--- a/Source/core/css/CSSProperty.h
+++ b/Source/core/css/CSSProperty.h
@@ -25,7 +25,6 @@
 #include "core/css/CSSValue.h"
 #include "core/platform/text/TextDirection.h"
 #include "core/platform/text/WritingMode.h"
-#include "core/rendering/style/RenderStyleConstants.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
 
diff --git a/Source/core/css/CSSPropertyNames.in b/Source/core/css/CSSPropertyNames.in
index 4cf9805..7faa2a5 100644
--- a/Source/core/css/CSSPropertyNames.in
+++ b/Source/core/css/CSSPropertyNames.in
@@ -265,30 +265,41 @@
 -webkit-columns
 -webkit-box-decoration-break
 -webkit-filter
--webkit-align-content
--webkit-align-items
--webkit-align-self
--webkit-flex
--webkit-flex-basis
--webkit-flex-direction
--webkit-flex-flow
--webkit-flex-grow
--webkit-flex-shrink
--webkit-flex-wrap
--webkit-justify-content
+align-content
+-webkit-align-content alias_for=align-content
+align-items
+-webkit-align-items alias_for=align-items
+align-self
+-webkit-align-self alias_for=align-self
+flex
+-webkit-flex alias_for=flex
+flex-basis
+-webkit-flex-basis alias_for=flex-basis
+flex-direction
+-webkit-flex-direction alias_for=flex-direction
+flex-flow
+-webkit-flex-flow alias_for=flex-flow
+flex-grow
+-webkit-flex-grow alias_for=flex-grow
+flex-shrink
+-webkit-flex-shrink alias_for=flex-shrink
+flex-wrap
+-webkit-flex-wrap alias_for=flex-wrap
+justify-content
+-webkit-justify-content alias_for=justify-content
 -webkit-font-size-delta
 grid-auto-columns
-grid-auto-rows
-grid-columns
-grid-rows
-grid-start
-grid-end
-grid-before
-grid-after
-grid-column
-grid-row
 grid-auto-flow
+grid-auto-rows
 grid-area
+grid-column
+grid-column-end
+grid-column-start
+grid-definition-columns
+grid-definition-rows
+grid-row
+grid-row-end
+grid-row-start
 -webkit-highlight
 -webkit-hyphenate-character
 -webkit-hyphenate-limit-after
@@ -341,7 +352,8 @@
 -webkit-max-logical-height
 -webkit-min-logical-width
 -webkit-min-logical-height
--webkit-order
+order
+-webkit-order alias_for=order
 -webkit-padding-after
 -webkit-padding-before
 -webkit-padding-end
diff --git a/Source/core/css/CSSPropertySourceData.h b/Source/core/css/CSSPropertySourceData.h
index 8dd3d43..f08deea 100644
--- a/Source/core/css/CSSPropertySourceData.h
+++ b/Source/core/css/CSSPropertySourceData.h
@@ -31,12 +31,10 @@
 #ifndef CSSPropertySourceData_h
 #define CSSPropertySourceData_h
 
-#include <utility>
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/RefCounted.h>
-#include <wtf/Vector.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/Forward.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSReflectValue.cpp b/Source/core/css/CSSReflectValue.cpp
index 56ac5d0..6a8d2c9 100644
--- a/Source/core/css/CSSReflectValue.cpp
+++ b/Source/core/css/CSSReflectValue.cpp
@@ -28,7 +28,6 @@
 
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/text/StringBuilder.h>
 
 using namespace std;
 
diff --git a/Source/core/css/CSSReflectValue.h b/Source/core/css/CSSReflectValue.h
index 7a97e3d..82b5ea8 100644
--- a/Source/core/css/CSSReflectValue.h
+++ b/Source/core/css/CSSReflectValue.h
@@ -26,10 +26,9 @@
 #ifndef CSSReflectValue_h
 #define CSSReflectValue_h
 
-#include "core/css/CSSReflectionDirection.h"
 #include "core/css/CSSValue.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSRegionRule.cpp b/Source/core/css/CSSRegionRule.cpp
index 7a34ab1..27278dc 100644
--- a/Source/core/css/CSSRegionRule.cpp
+++ b/Source/core/css/CSSRegionRule.cpp
@@ -33,10 +33,7 @@
 #include "core/css/CSSRegionRule.h"
 
 #include "RuntimeEnabledFeatures.h"
-#include "core/css/CSSParser.h"
-#include "core/css/CSSRuleList.h"
 #include "core/css/StyleRule.h"
-#include "wtf/MemoryInstrumentationVector.h"
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
diff --git a/Source/core/css/CSSRuleList.cpp b/Source/core/css/CSSRuleList.cpp
index 8b7fcea..3a21a47 100644
--- a/Source/core/css/CSSRuleList.cpp
+++ b/Source/core/css/CSSRuleList.cpp
@@ -23,7 +23,7 @@
 #include "core/css/CSSRuleList.h"
 
 #include "core/css/CSSRule.h"
-#include <wtf/MemoryInstrumentationVector.h>
+#include "wtf/MemoryInstrumentationVector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSRuleList.h b/Source/core/css/CSSRuleList.h
index d7bf17d..f63c3cd 100644
--- a/Source/core/css/CSSRuleList.h
+++ b/Source/core/css/CSSRuleList.h
@@ -23,11 +23,9 @@
 #define CSSRuleList_h
 
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSSegmentedFontFace.h b/Source/core/css/CSSSegmentedFontFace.h
index 6507d17..662045d 100644
--- a/Source/core/css/CSSSegmentedFontFace.h
+++ b/Source/core/css/CSSSegmentedFontFace.h
@@ -26,11 +26,10 @@
 #ifndef CSSSegmentedFontFace_h
 #define CSSSegmentedFontFace_h
 
-#include <wtf/HashMap.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/Vector.h>
-#include <wtf/unicode/Unicode.h>
+#include "wtf/HashMap.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSSelector.cpp b/Source/core/css/CSSSelector.cpp
index 74adeb1..9d471fb 100644
--- a/Source/core/css/CSSSelector.cpp
+++ b/Source/core/css/CSSSelector.cpp
@@ -30,11 +30,10 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSOMUtils.h"
 #include "core/css/CSSSelectorList.h"
-#include <wtf/Assertions.h>
-#include <wtf/HashMap.h>
-#include <wtf/StdLibExtras.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/Vector.h>
+#include "wtf/Assertions.h"
+#include "wtf/HashMap.h"
+#include "wtf/StdLibExtras.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
@@ -182,8 +181,6 @@
         return FULL_SCREEN_DOCUMENT;
     case PseudoFullScreenAncestor:
         return FULL_SCREEN_ANCESTOR;
-    case PseudoAnimatingFullScreenTransition:
-        return ANIMATING_FULL_SCREEN_TRANSITION;
     case PseudoUnknown:
     case PseudoEmpty:
     case PseudoFirstChild:
@@ -327,7 +324,6 @@
     DEFINE_STATIC_LOCAL(AtomicString, fullScreen, ("-webkit-full-screen", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, fullScreenDocument, ("-webkit-full-screen-document", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, fullScreenAncestor, ("-webkit-full-screen-ancestor", AtomicString::ConstructFromLiteral));
-    DEFINE_STATIC_LOCAL(AtomicString, animatingFullScreenTransition, ("-webkit-animating-full-screen-transition", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, cue, ("cue(", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, futureCue, ("future", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, pastCue, ("past", AtomicString::ConstructFromLiteral));
@@ -408,7 +404,6 @@
         nameToPseudoType->set(fullScreen.impl(), CSSSelector::PseudoFullScreen);
         nameToPseudoType->set(fullScreenDocument.impl(), CSSSelector::PseudoFullScreenDocument);
         nameToPseudoType->set(fullScreenAncestor.impl(), CSSSelector::PseudoFullScreenAncestor);
-        nameToPseudoType->set(animatingFullScreenTransition.impl(), CSSSelector::PseudoAnimatingFullScreenTransition);
         nameToPseudoType->set(cue.impl(), CSSSelector::PseudoCue);
         nameToPseudoType->set(futureCue.impl(), CSSSelector::PseudoFutureCue);
         nameToPseudoType->set(pastCue.impl(), CSSSelector::PseudoPastCue);
@@ -526,7 +521,6 @@
     case PseudoFullScreen:
     case PseudoFullScreenDocument:
     case PseudoFullScreenAncestor:
-    case PseudoAnimatingFullScreenTransition:
     case PseudoSeamlessDocument:
     case PseudoInRange:
     case PseudoOutOfRange:
diff --git a/Source/core/css/CSSSelector.h b/Source/core/css/CSSSelector.h
index e8fc3ae..6a460c8 100644
--- a/Source/core/css/CSSSelector.h
+++ b/Source/core/css/CSSSelector.h
@@ -24,9 +24,8 @@
 
 #include "core/dom/QualifiedName.h"
 #include "core/rendering/style/RenderStyleConstants.h"
-#include <wtf/Noncopyable.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
     class CSSSelectorList;
@@ -153,7 +152,6 @@
             PseudoFullScreen,
             PseudoFullScreenDocument,
             PseudoFullScreenAncestor,
-            PseudoAnimatingFullScreenTransition,
             PseudoInRange,
             PseudoOutOfRange,
             PseudoUserAgentCustomElement,
diff --git a/Source/core/css/CSSStyleDeclaration.cpp b/Source/core/css/CSSStyleDeclaration.cpp
deleted file mode 100644
index 538e17e..0000000
--- a/Source/core/css/CSSStyleDeclaration.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2013 Google 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:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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 "core/css/CSSStyleDeclaration.h"
-
-#include "core/css/CSSParser.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/css/CSSStyleSheet.h"
-#include "core/css/CSSValue.h"
-#include "core/dom/Document.h"
-#include "core/dom/DocumentStyleSheetCollection.h"
-#include "core/dom/EventTarget.h"
-#include "core/html/HTMLStyleElement.h"
-#include "core/page/RuntimeCSSEnabled.h"
-
-namespace WebCore {
-
-} // namespace WebCore
diff --git a/Source/core/css/CSSStyleDeclaration.h b/Source/core/css/CSSStyleDeclaration.h
index 69939ce..68405ad 100644
--- a/Source/core/css/CSSStyleDeclaration.h
+++ b/Source/core/css/CSSStyleDeclaration.h
@@ -33,7 +33,6 @@
 class CSSValue;
 class MutableStylePropertySet;
 class StylePropertySet;
-class StyledElement;
 
 typedef int ExceptionCode;
 
diff --git a/Source/core/css/CSSStyleSheet.h b/Source/core/css/CSSStyleSheet.h
index bcc6550..37f83ab 100644
--- a/Source/core/css/CSSStyleSheet.h
+++ b/Source/core/css/CSSStyleSheet.h
@@ -21,12 +21,9 @@
 #ifndef CSSStyleSheet_h
 #define CSSStyleSheet_h
 
-#include "core/css/CSSParserMode.h"
 #include "core/css/CSSRule.h"
 #include "core/css/StyleSheet.h"
-#include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
-#include "wtf/text/AtomicStringHash.h"
 #include "wtf/text/TextPosition.h"
 
 namespace WebCore {
diff --git a/Source/core/css/CSSSupportsRule.cpp b/Source/core/css/CSSSupportsRule.cpp
index 8c96b05..08244c6 100644
--- a/Source/core/css/CSSSupportsRule.cpp
+++ b/Source/core/css/CSSSupportsRule.cpp
@@ -31,8 +31,7 @@
 
 #include "core/css/CSSRule.h"
 #include "core/css/StyleRule.h"
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSTransformValue.h b/Source/core/css/CSSTransformValue.h
index 635a608..de0637a 100644
--- a/Source/core/css/CSSTransformValue.h
+++ b/Source/core/css/CSSTransformValue.h
@@ -28,7 +28,6 @@
 
 #include "core/css/CSSValueList.h"
 #include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSUnicodeRangeValue.h b/Source/core/css/CSSUnicodeRangeValue.h
index 6360df2..3fa3647 100644
--- a/Source/core/css/CSSUnicodeRangeValue.h
+++ b/Source/core/css/CSSUnicodeRangeValue.h
@@ -27,8 +27,7 @@
 #define CSSUnicodeRangeValue_h
 
 #include "core/css/CSSValue.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/unicode/Unicode.h>
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSValue.h b/Source/core/css/CSSValue.h
index 18c0cb6..9fe4b60 100644
--- a/Source/core/css/CSSValue.h
+++ b/Source/core/css/CSSValue.h
@@ -31,6 +31,8 @@
 
 class StyleSheetContents;
 
+enum CssTextFormattingFlags { QuoteCSSStringIfNeeded, AlwaysQuoteCSSString };
+
 // FIXME: The current CSSValue and subclasses should be turned into internal types (StyleValue).
 // The few subtypes that are actually exposed in CSSOM can be seen in the cloneForCSSOM() function.
 // They should be handled by separate wrapper classes.
diff --git a/Source/core/css/CSSValueKeywords.in b/Source/core/css/CSSValueKeywords.in
index 6dfc4fa..a7d1e7e 100644
--- a/Source/core/css/CSSValueKeywords.in
+++ b/Source/core/css/CSSValueKeywords.in
@@ -340,12 +340,14 @@
 table-caption
 -webkit-box
 -webkit-inline-box
--webkit-flex
--webkit-inline-flex
+flex
+inline-flex
 grid
 inline-grid
 lazy-block
 //none
+-webkit-flex
+-webkit-inline-flex
 //
 // CSS_PROP_CURSOR:
 // The order here must match the order of the ECursor enum in RenderStyleConstants.h.
@@ -581,6 +583,9 @@
 -webkit-max-content
 -webkit-fill-available
 -webkit-fit-content
+// Unprefixed for CSS Grid Layout.
+min-content
+max-content
 
 //
 // CSS_PROP_TEXT_OVERFLOW
diff --git a/Source/core/css/CSSValueList.cpp b/Source/core/css/CSSValueList.cpp
index 1a6adf9..960ef32 100644
--- a/Source/core/css/CSSValueList.cpp
+++ b/Source/core/css/CSSValueList.cpp
@@ -23,9 +23,8 @@
 
 #include "core/css/CSSParserValues.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/MemoryInstrumentationVector.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
@@ -97,7 +96,7 @@
     return newList.release();
 }
 
-String CSSValueList::customCssText() const
+String CSSValueList::customCssText(CssTextFormattingFlags formattingFlag) const
 {
     StringBuilder result;
     String separator;
@@ -119,7 +118,10 @@
     for (unsigned i = 0; i < size; i++) {
         if (!result.isEmpty())
             result.append(separator);
-        result.append(m_values[i]->cssText());
+        if (formattingFlag == AlwaysQuoteCSSString && m_values[i]->isPrimitiveValue())
+            result.append(toCSSPrimitiveValue(m_values[i].get())->customCssText(AlwaysQuoteCSSString));
+        else
+            result.append(m_values[i]->cssText());
     }
 
     return result.toString();
diff --git a/Source/core/css/CSSValueList.h b/Source/core/css/CSSValueList.h
index 7532e37..ef47a42 100644
--- a/Source/core/css/CSSValueList.h
+++ b/Source/core/css/CSSValueList.h
@@ -59,7 +59,7 @@
     bool hasValue(CSSValue*) const;
     PassRefPtr<CSSValueList> copy();
 
-    String customCssText() const;
+    String customCssText(CssTextFormattingFlags = QuoteCSSStringIfNeeded) const;
     bool equals(const CSSValueList&) const;
     bool equals(const CSSValue&) const;
     String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
diff --git a/Source/core/css/DeprecatedStyleBuilder.cpp b/Source/core/css/DeprecatedStyleBuilder.cpp
index d3292f3..1553246 100644
--- a/Source/core/css/DeprecatedStyleBuilder.cpp
+++ b/Source/core/css/DeprecatedStyleBuilder.cpp
@@ -43,10 +43,10 @@
 #include "core/rendering/RenderView.h"
 #include "core/rendering/style/BasicShapes.h"
 #include "core/rendering/style/CursorList.h"
-#include "core/rendering/style/ExclusionShapeValue.h"
 #include "core/rendering/style/RenderStyle.h"
-#include <wtf/StdLibExtras.h>
-#include <wtf/UnusedParam.h>
+#include "core/rendering/style/ShapeValue.h"
+#include "wtf/StdLibExtras.h"
+#include "wtf/UnusedParam.h"
 
 using namespace std;
 
@@ -1282,82 +1282,6 @@
     static PropertyHandler createHandler() { return PropertyHandler(&applyInheritValue, &applyInitialValue, &applyValue); }
 };
 
-template <typename T,
-          T (CSSAnimationData::*getterFunction)() const,
-          void (CSSAnimationData::*setterFunction)(T),
-          bool (CSSAnimationData::*testFunction)() const,
-          void (CSSAnimationData::*clearFunction)(),
-          T (*initialFunction)(),
-          void (CSSToStyleMap::*mapFunction)(CSSAnimationData*, CSSValue*),
-          CSSAnimationDataList* (RenderStyle::*animationGetterFunction)(),
-          const CSSAnimationDataList* (RenderStyle::*immutableAnimationGetterFunction)() const>
-class ApplyPropertyAnimation {
-public:
-    static void setValue(CSSAnimationData* animation, T value) { (animation->*setterFunction)(value); }
-    static T value(const CSSAnimationData* animation) { return (animation->*getterFunction)(); }
-    static bool test(const CSSAnimationData* animation) { return (animation->*testFunction)(); }
-    static void clear(CSSAnimationData* animation) { (animation->*clearFunction)(); }
-    static T initial() { return (*initialFunction)(); }
-    static void map(StyleResolver* styleResolver, CSSAnimationData* animation, CSSValue* value) { (styleResolver->styleMap()->*mapFunction)(animation, value); }
-    static CSSAnimationDataList* accessAnimations(RenderStyle* style) { return (style->*animationGetterFunction)(); }
-    static const CSSAnimationDataList* animations(RenderStyle* style) { return (style->*immutableAnimationGetterFunction)(); }
-
-    static void applyInheritValue(CSSPropertyID, StyleResolver* styleResolver)
-    {
-        CSSAnimationDataList* list = accessAnimations(styleResolver->style());
-        const CSSAnimationDataList* parentList = animations(styleResolver->parentStyle());
-        size_t i = 0, parentSize = parentList ? parentList->size() : 0;
-        for ( ; i < parentSize && test(parentList->animation(i)); ++i) {
-            if (list->size() <= i)
-                list->append(CSSAnimationData::create());
-            setValue(list->animation(i), value(parentList->animation(i)));
-            list->animation(i)->setAnimationMode(parentList->animation(i)->animationMode());
-        }
-
-        /* Reset any remaining animations to not have the property set. */
-        for ( ; i < list->size(); ++i)
-            clear(list->animation(i));
-    }
-
-    static void applyInitialValue(CSSPropertyID propertyID, StyleResolver* styleResolver)
-    {
-        CSSAnimationDataList* list = accessAnimations(styleResolver->style());
-        if (list->isEmpty())
-            list->append(CSSAnimationData::create());
-        setValue(list->animation(0), initial());
-        if (propertyID == CSSPropertyWebkitTransitionProperty)
-            list->animation(0)->setAnimationMode(CSSAnimationData::AnimateAll);
-        for (size_t i = 1; i < list->size(); ++i)
-            clear(list->animation(i));
-    }
-
-    static void applyValue(CSSPropertyID, StyleResolver* styleResolver, CSSValue* value)
-    {
-        CSSAnimationDataList* list = accessAnimations(styleResolver->style());
-        size_t childIndex = 0;
-        if (value->isValueList()) {
-            /* Walk each value and put it into an animation, creating new animations as needed. */
-            for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
-                if (childIndex <= list->size())
-                    list->append(CSSAnimationData::create());
-                map(styleResolver, list->animation(childIndex), i.value());
-                ++childIndex;
-            }
-        } else {
-            if (list->isEmpty())
-                list->append(CSSAnimationData::create());
-            map(styleResolver, list->animation(childIndex), value);
-            childIndex = 1;
-        }
-        for ( ; childIndex < list->size(); ++childIndex) {
-            /* Reset all remaining animations to not have the property set. */
-            clear(list->animation(childIndex));
-        }
-    }
-
-    static PropertyHandler createHandler() { return PropertyHandler(&applyInheritValue, &applyInitialValue, &applyValue); }
-};
-
 class ApplyPropertyOutlineStyle {
 public:
     static void applyInheritValue(CSSPropertyID propertyID, StyleResolver* styleResolver)
@@ -1537,10 +1461,10 @@
     }
 };
 
-template <ExclusionShapeValue* (RenderStyle::*getterFunction)() const, void (RenderStyle::*setterFunction)(PassRefPtr<ExclusionShapeValue>), ExclusionShapeValue* (*initialFunction)()>
-class ApplyPropertyExclusionShape {
+template <ShapeValue* (RenderStyle::*getterFunction)() const, void (RenderStyle::*setterFunction)(PassRefPtr<ShapeValue>), ShapeValue* (*initialFunction)()>
+class ApplyPropertyShape {
 public:
-    static void setValue(RenderStyle* style, PassRefPtr<ExclusionShapeValue> value) { (style->*setterFunction)(value); }
+    static void setValue(RenderStyle* style, PassRefPtr<ShapeValue> value) { (style->*setterFunction)(value); }
     static void applyValue(CSSPropertyID property, StyleResolver* styleResolver, CSSValue* value)
     {
         if (value->isPrimitiveValue()) {
@@ -1549,19 +1473,19 @@
                 setValue(styleResolver->style(), 0);
             // FIXME Bug 102571: Layout for the value 'outside-shape' is not yet implemented
             else if (primitiveValue->getValueID() == CSSValueOutsideShape)
-                setValue(styleResolver->style(), ExclusionShapeValue::createOutsideValue());
+                setValue(styleResolver->style(), ShapeValue::createOutsideValue());
             else if (primitiveValue->isShape()) {
-                RefPtr<ExclusionShapeValue> shape = ExclusionShapeValue::createShapeValue(basicShapeForValue(styleResolver, primitiveValue->getShapeValue()));
+                RefPtr<ShapeValue> shape = ShapeValue::createShapeValue(basicShapeForValue(styleResolver, primitiveValue->getShapeValue()));
                 setValue(styleResolver->style(), shape.release());
             }
         } else if (value->isImageValue()) {
-            RefPtr<ExclusionShapeValue> shape = ExclusionShapeValue::createImageValue(styleResolver->styleImage(property, value));
+            RefPtr<ShapeValue> shape = ShapeValue::createImageValue(styleResolver->styleImage(property, value));
             setValue(styleResolver->style(), shape.release());
         }
     }
     static PropertyHandler createHandler()
     {
-        PropertyHandler handler = ApplyPropertyDefaultBase<ExclusionShapeValue*, getterFunction, PassRefPtr<ExclusionShapeValue>, setterFunction, ExclusionShapeValue*, initialFunction>::createHandler();
+        PropertyHandler handler = ApplyPropertyDefaultBase<ShapeValue*, getterFunction, PassRefPtr<ShapeValue>, setterFunction, ShapeValue*, initialFunction>::createHandler();
         return PropertyHandler(handler.inheritFunction(), handler.initialFunction(), &applyValue);
     }
 };
@@ -1671,14 +1595,6 @@
     setPropertyHandler(CSSPropertyTextIndent, ApplyPropertyTextIndent::createHandler());
     setPropertyHandler(CSSPropertyTextRendering, ApplyPropertyFont<TextRenderingMode, &FontDescription::textRenderingMode, &FontDescription::setTextRenderingMode, AutoTextRendering>::createHandler());
     setPropertyHandler(CSSPropertyVerticalAlign, ApplyPropertyVerticalAlign::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationDelay, ApplyPropertyAnimation<double, &CSSAnimationData::delay, &CSSAnimationData::setDelay, &CSSAnimationData::isDelaySet, &CSSAnimationData::clearDelay, &CSSAnimationData::initialAnimationDelay, &CSSToStyleMap::mapAnimationDelay, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationDirection, ApplyPropertyAnimation<CSSAnimationData::AnimationDirection, &CSSAnimationData::direction, &CSSAnimationData::setDirection, &CSSAnimationData::isDirectionSet, &CSSAnimationData::clearDirection, &CSSAnimationData::initialAnimationDirection, &CSSToStyleMap::mapAnimationDirection, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationDuration, ApplyPropertyAnimation<double, &CSSAnimationData::duration, &CSSAnimationData::setDuration, &CSSAnimationData::isDurationSet, &CSSAnimationData::clearDuration, &CSSAnimationData::initialAnimationDuration, &CSSToStyleMap::mapAnimationDuration, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationFillMode, ApplyPropertyAnimation<unsigned, &CSSAnimationData::fillMode, &CSSAnimationData::setFillMode, &CSSAnimationData::isFillModeSet, &CSSAnimationData::clearFillMode, &CSSAnimationData::initialAnimationFillMode, &CSSToStyleMap::mapAnimationFillMode, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationIterationCount, ApplyPropertyAnimation<double, &CSSAnimationData::iterationCount, &CSSAnimationData::setIterationCount, &CSSAnimationData::isIterationCountSet, &CSSAnimationData::clearIterationCount, &CSSAnimationData::initialAnimationIterationCount, &CSSToStyleMap::mapAnimationIterationCount, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationName, ApplyPropertyAnimation<const String&, &CSSAnimationData::name, &CSSAnimationData::setName, &CSSAnimationData::isNameSet, &CSSAnimationData::clearName, &CSSAnimationData::initialAnimationName, &CSSToStyleMap::mapAnimationName, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationPlayState, ApplyPropertyAnimation<EAnimPlayState, &CSSAnimationData::playState, &CSSAnimationData::setPlayState, &CSSAnimationData::isPlayStateSet, &CSSAnimationData::clearPlayState, &CSSAnimationData::initialAnimationPlayState, &CSSToStyleMap::mapAnimationPlayState, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationTimingFunction, ApplyPropertyAnimation<const PassRefPtr<TimingFunction>, &CSSAnimationData::timingFunction, &CSSAnimationData::setTimingFunction, &CSSAnimationData::isTimingFunctionSet, &CSSAnimationData::clearTimingFunction, &CSSAnimationData::initialAnimationTimingFunction, &CSSToStyleMap::mapAnimationTimingFunction, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
     setPropertyHandler(CSSPropertyWebkitAspectRatio, ApplyPropertyAspectRatio::createHandler());
     setPropertyHandler(CSSPropertyWebkitBorderHorizontalSpacing, ApplyPropertyComputeLength<short, &RenderStyle::horizontalBorderSpacing, &RenderStyle::setHorizontalBorderSpacing, &RenderStyle::initialHorizontalBorderSpacing>::createHandler());
     setPropertyHandler(CSSPropertyWebkitBorderVerticalSpacing, ApplyPropertyComputeLength<short, &RenderStyle::verticalBorderSpacing, &RenderStyle::setVerticalBorderSpacing, &RenderStyle::initialVerticalBorderSpacing>::createHandler());
@@ -1695,13 +1611,9 @@
     setPropertyHandler(CSSPropertyWebkitPerspectiveOrigin, ApplyPropertyExpanding<SuppressValue, CSSPropertyWebkitPerspectiveOriginX, CSSPropertyWebkitPerspectiveOriginY>::createHandler());
     setPropertyHandler(CSSPropertyWebkitTextEmphasisStyle, ApplyPropertyTextEmphasisStyle::createHandler());
     setPropertyHandler(CSSPropertyWebkitTransformOriginZ, ApplyPropertyComputeLength<float, &RenderStyle::transformOriginZ, &RenderStyle::setTransformOriginZ, &RenderStyle::initialTransformOriginZ>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitTransitionDelay, ApplyPropertyAnimation<double, &CSSAnimationData::delay, &CSSAnimationData::setDelay, &CSSAnimationData::isDelaySet, &CSSAnimationData::clearDelay, &CSSAnimationData::initialAnimationDelay, &CSSToStyleMap::mapAnimationDelay, &RenderStyle::accessTransitions, &RenderStyle::transitions>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitTransitionDuration, ApplyPropertyAnimation<double, &CSSAnimationData::duration, &CSSAnimationData::setDuration, &CSSAnimationData::isDurationSet, &CSSAnimationData::clearDuration, &CSSAnimationData::initialAnimationDuration, &CSSToStyleMap::mapAnimationDuration, &RenderStyle::accessTransitions, &RenderStyle::transitions>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitTransitionProperty, ApplyPropertyAnimation<CSSPropertyID, &CSSAnimationData::property, &CSSAnimationData::setProperty, &CSSAnimationData::isPropertySet, &CSSAnimationData::clearProperty, &CSSAnimationData::initialAnimationProperty, &CSSToStyleMap::mapAnimationProperty, &RenderStyle::accessTransitions, &RenderStyle::transitions>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitTransitionTimingFunction, ApplyPropertyAnimation<const PassRefPtr<TimingFunction>, &CSSAnimationData::timingFunction, &CSSAnimationData::setTimingFunction, &CSSAnimationData::isTimingFunctionSet, &CSSAnimationData::clearTimingFunction, &CSSAnimationData::initialAnimationTimingFunction, &CSSToStyleMap::mapAnimationTimingFunction, &RenderStyle::accessTransitions, &RenderStyle::transitions>::createHandler());
     setPropertyHandler(CSSPropertyWebkitClipPath, ApplyPropertyClipPath<&RenderStyle::clipPath, &RenderStyle::setClipPath, &RenderStyle::initialClipPath>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitShapeInside, ApplyPropertyExclusionShape<&RenderStyle::shapeInside, &RenderStyle::setShapeInside, &RenderStyle::initialShapeInside>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitShapeOutside, ApplyPropertyExclusionShape<&RenderStyle::shapeOutside, &RenderStyle::setShapeOutside, &RenderStyle::initialShapeOutside>::createHandler());
+    setPropertyHandler(CSSPropertyWebkitShapeInside, ApplyPropertyShape<&RenderStyle::shapeInside, &RenderStyle::setShapeInside, &RenderStyle::initialShapeInside>::createHandler());
+    setPropertyHandler(CSSPropertyWebkitShapeOutside, ApplyPropertyShape<&RenderStyle::shapeOutside, &RenderStyle::setShapeOutside, &RenderStyle::initialShapeOutside>::createHandler());
     setPropertyHandler(CSSPropertyWordSpacing, ApplyPropertyComputeLength<int, &RenderStyle::wordSpacing, &RenderStyle::setWordSpacing, &RenderStyle::initialLetterWordSpacing, NormalEnabled, ThicknessDisabled, SVGZoomEnabled>::createHandler());
 }
 
diff --git a/Source/core/css/DeprecatedStyleBuilder.h b/Source/core/css/DeprecatedStyleBuilder.h
index a21d42f..4d4d254 100644
--- a/Source/core/css/DeprecatedStyleBuilder.h
+++ b/Source/core/css/DeprecatedStyleBuilder.h
@@ -27,8 +27,6 @@
 
 #include "CSSPropertyNames.h"
 #include "core/css/StylePropertyShorthand.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
 
 namespace WebCore {
 
diff --git a/Source/core/css/DocumentRuleSets.cpp b/Source/core/css/DocumentRuleSets.cpp
index 213e9fb..4e72f57 100644
--- a/Source/core/css/DocumentRuleSets.cpp
+++ b/Source/core/css/DocumentRuleSets.cpp
@@ -31,7 +31,6 @@
 
 #include "core/css/CSSDefaultStyleSheets.h"
 #include "core/css/CSSStyleSheet.h"
-#include "core/css/MediaQueryEvaluator.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/DocumentStyleSheetCollection.h"
@@ -40,14 +39,14 @@
 
 namespace WebCore {
 
-void ShadowDistributedRules::addRule(StyleRule* rule, size_t selectorIndex, ContainerNode* scope, AddRuleFlags addRuleFlags)
+void ShadowDistributedRules::addRule(StyleRule* rule, size_t selectorIndex, ContainerNode* scopingNode, AddRuleFlags addRuleFlags)
 {
-    if (m_shadowDistributedRuleSetMap.contains(scope))
-        m_shadowDistributedRuleSetMap.get(scope)->addRule(rule, selectorIndex, addRuleFlags);
+    if (m_shadowDistributedRuleSetMap.contains(scopingNode))
+        m_shadowDistributedRuleSetMap.get(scopingNode)->addRule(rule, selectorIndex, addRuleFlags);
     else {
-        OwnPtr<RuleSet> ruleSetForScope = adoptPtr(new RuleSet());
+        OwnPtr<RuleSet> ruleSetForScope = RuleSet::create();
         ruleSetForScope->addRule(rule, selectorIndex, addRuleFlags);
-        m_shadowDistributedRuleSetMap.add(scope, ruleSetForScope.release());
+        m_shadowDistributedRuleSetMap.add(scopingNode, ruleSetForScope.release());
     }
 }
 
@@ -57,6 +56,11 @@
         matchRequests.append(MatchRequest(it->value.get(), includeEmptyRules, it->key));
 }
 
+void ShadowDistributedRules::reset(const ContainerNode* scopingNode)
+{
+    m_shadowDistributedRuleSetMap.remove(scopingNode);
+}
+
 void ShadowDistributedRules::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
 {
     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
@@ -84,7 +88,7 @@
         tempUserStyle->addRulesFromSheet(pageUserSheet->contents(), medium, &resolver);
     collectRulesFromUserStyleSheets(styleSheetCollection->injectedUserStyleSheets(), *tempUserStyle, medium, resolver);
     collectRulesFromUserStyleSheets(styleSheetCollection->documentUserStyleSheets(), *tempUserStyle, medium, resolver);
-    if (tempUserStyle->m_ruleCount > 0 || tempUserStyle->m_pageRules.size() > 0)
+    if (tempUserStyle->ruleCount() > 0 || tempUserStyle->pageRules().size() > 0)
         m_userStyle = tempUserStyle.release();
 }
 
diff --git a/Source/core/css/DocumentRuleSets.h b/Source/core/css/DocumentRuleSets.h
index 77a024d..dd047ea 100644
--- a/Source/core/css/DocumentRuleSets.h
+++ b/Source/core/css/DocumentRuleSets.h
@@ -42,9 +42,10 @@
 
 class ShadowDistributedRules {
 public:
-    void addRule(StyleRule*, size_t selectorIndex, ContainerNode* scope, AddRuleFlags);
+    void addRule(StyleRule*, size_t selectorIndex, ContainerNode* scopingNode, AddRuleFlags);
     void collectMatchRequests(bool includeEmptyRules, Vector<MatchRequest>&);
     void clear() { m_shadowDistributedRuleSetMap.clear(); }
+    void reset(const ContainerNode* scopingNode);
     bool isEmpty() const { return m_shadowDistributedRuleSetMap.isEmpty(); }
     void reportMemoryUsage(MemoryObjectInfo*) const;
     void collectFeaturesTo(RuleFeatureSet&);
diff --git a/Source/core/css/ElementRuleCollector.cpp b/Source/core/css/ElementRuleCollector.cpp
index a89f953..3f6e411 100644
--- a/Source/core/css/ElementRuleCollector.cpp
+++ b/Source/core/css/ElementRuleCollector.cpp
@@ -34,11 +34,8 @@
 #include "core/css/SelectorCheckerFastPath.h"
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/css/StylePropertySet.h"
-#include "core/dom/StyledElement.h"
 #include "core/rendering/RenderRegion.h"
 
-#include <wtf/TemporaryChange.h>
-
 namespace WebCore {
 
 StyleResolver::MatchResult& ElementRuleCollector::matchedResult()
@@ -92,7 +89,7 @@
 
     const StyleResolverState& state = m_state;
     Element* element = state.element();
-    const StyledElement* styledElement = state.styledElement();
+    const Element* styledElement = state.styledElement();
     const AtomicString& pseudoId = element->shadowPseudoId();
     if (!pseudoId.isEmpty()) {
         ASSERT(styledElement);
@@ -209,57 +206,66 @@
     return true;
 }
 
+void ElementRuleCollector::collectRuleIfMatches(const RuleData& ruleData, const MatchRequest& matchRequest, StyleResolver::RuleRange& ruleRange)
+{
+    if (m_canUseFastReject && m_selectorFilter.fastRejectSelector(ruleData.selector()))
+        return;
+
+    StyleRule* rule = ruleData.rule();
+    InspectorInstrumentationCookie cookie = InspectorInstrumentation::willMatchRule(document(), rule, m_inspectorCSSOMWrappers, document()->styleSheetCollection());
+    PseudoId dynamicPseudo = NOPSEUDO;
+    if (ruleMatches(ruleData, matchRequest.scope, dynamicPseudo)) {
+        // If the rule has no properties to apply, then ignore it in the non-debug mode.
+        const StylePropertySet* properties = rule->properties();
+        if (!properties || (properties->isEmpty() && !matchRequest.includeEmptyRules)) {
+            InspectorInstrumentation::didMatchRule(cookie, false);
+            return;
+        }
+        // FIXME: Exposing the non-standard getMatchedCSSRules API to web is the only reason this is needed.
+        if (m_sameOriginOnly && !ruleData.hasDocumentSecurityOrigin()) {
+            InspectorInstrumentation::didMatchRule(cookie, false);
+            return;
+        }
+        // If we're matching normal rules, set a pseudo bit if
+        // we really just matched a pseudo-element.
+        if (dynamicPseudo != NOPSEUDO && m_pseudoStyleRequest.pseudoId == NOPSEUDO) {
+            if (m_mode == SelectorChecker::CollectingRules) {
+                InspectorInstrumentation::didMatchRule(cookie, false);
+                return;
+            }
+            if (dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
+                m_state.style()->setHasPseudoStyle(dynamicPseudo);
+        } else {
+            // Update our first/last rule indices in the matched rules array.
+            ++ruleRange.lastRuleIndex;
+            if (ruleRange.firstRuleIndex == -1)
+                ruleRange.firstRuleIndex = ruleRange.lastRuleIndex;
+
+            // Add this rule to our list of matched rules.
+            addMatchedRule(&ruleData);
+            InspectorInstrumentation::didMatchRule(cookie, true);
+            return;
+        }
+    }
+    InspectorInstrumentation::didMatchRule(cookie, false);
+}
+
+void ElementRuleCollector::collectMatchingRulesForList(const RuleData* rules, const MatchRequest& matchRequest, StyleResolver::RuleRange& ruleRange)
+{
+    if (!rules)
+        return;
+    while (!rules->isLastInArray())
+        collectRuleIfMatches(*rules++, matchRequest, ruleRange);
+    collectRuleIfMatches(*rules, matchRequest, ruleRange);
+}
+
 void ElementRuleCollector::collectMatchingRulesForList(const Vector<RuleData>* rules, const MatchRequest& matchRequest, StyleResolver::RuleRange& ruleRange)
 {
     if (!rules)
         return;
-
-    const StyleResolverState& state = m_state;
-
     unsigned size = rules->size();
-    for (unsigned i = 0; i < size; ++i) {
-        const RuleData& ruleData = rules->at(i);
-        if (m_canUseFastReject && m_selectorFilter.fastRejectSelector<RuleData::maximumIdentifierCount>(ruleData.descendantSelectorIdentifierHashes()))
-            continue;
-
-        StyleRule* rule = ruleData.rule();
-        InspectorInstrumentationCookie cookie = InspectorInstrumentation::willMatchRule(document(), rule, m_inspectorCSSOMWrappers, document()->styleSheetCollection());
-        PseudoId dynamicPseudo = NOPSEUDO;
-        if (ruleMatches(ruleData, matchRequest.scope, dynamicPseudo)) {
-            // If the rule has no properties to apply, then ignore it in the non-debug mode.
-            const StylePropertySet* properties = rule->properties();
-            if (!properties || (properties->isEmpty() && !matchRequest.includeEmptyRules)) {
-                InspectorInstrumentation::didMatchRule(cookie, false);
-                continue;
-            }
-            // FIXME: Exposing the non-standard getMatchedCSSRules API to web is the only reason this is needed.
-            if (m_sameOriginOnly && !ruleData.hasDocumentSecurityOrigin()) {
-                InspectorInstrumentation::didMatchRule(cookie, false);
-                continue;
-            }
-            // If we're matching normal rules, set a pseudo bit if
-            // we really just matched a pseudo-element.
-            if (dynamicPseudo != NOPSEUDO && m_pseudoStyleRequest.pseudoId == NOPSEUDO) {
-                if (m_mode == SelectorChecker::CollectingRules) {
-                    InspectorInstrumentation::didMatchRule(cookie, false);
-                    continue;
-                }
-                if (dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
-                    state.style()->setHasPseudoStyle(dynamicPseudo);
-            } else {
-                // Update our first/last rule indices in the matched rules array.
-                ++ruleRange.lastRuleIndex;
-                if (ruleRange.firstRuleIndex == -1)
-                    ruleRange.firstRuleIndex = ruleRange.lastRuleIndex;
-
-                // Add this rule to our list of matched rules.
-                addMatchedRule(&ruleData);
-                InspectorInstrumentation::didMatchRule(cookie, true);
-                continue;
-            }
-        }
-        InspectorInstrumentation::didMatchRule(cookie, false);
-    }
+    for (unsigned i = 0; i < size; ++i)
+        collectRuleIfMatches(rules->at(i), matchRequest, ruleRange);
 }
 
 static inline bool compareRules(const RuleData* r1, const RuleData* r2)
diff --git a/Source/core/css/ElementRuleCollector.h b/Source/core/css/ElementRuleCollector.h
index 4f34110..5d4328b 100644
--- a/Source/core/css/ElementRuleCollector.h
+++ b/Source/core/css/ElementRuleCollector.h
@@ -22,11 +22,10 @@
 #ifndef ElementRuleCollector_h
 #define ElementRuleCollector_h
 
-#include "core/css/MediaQueryEvaluator.h"
 #include "core/css/SelectorChecker.h"
 #include "core/css/resolver/StyleResolver.h"
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -78,7 +77,9 @@
 private:
     Document* document() { return m_state.document(); }
 
+    void collectRuleIfMatches(const RuleData&, const MatchRequest&, StyleResolver::RuleRange&);
     void collectMatchingRulesForList(const Vector<RuleData>*, const MatchRequest&, StyleResolver::RuleRange&);
+    void collectMatchingRulesForList(const RuleData*, const MatchRequest&, StyleResolver::RuleRange&);
     bool ruleMatches(const RuleData&, const ContainerNode* scope, PseudoId&);
 
     void sortMatchedRules();
diff --git a/Source/core/css/FontLoader.cpp b/Source/core/css/FontLoader.cpp
index 564cfd8..6005643 100644
--- a/Source/core/css/FontLoader.cpp
+++ b/Source/core/css/FontLoader.cpp
@@ -34,8 +34,10 @@
 #include "core/css/CSSSegmentedFontFace.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/resolver/StyleResolver.h"
+#include "core/dom/DOMException.h"
 #include "core/dom/Document.h"
 #include "core/page/FrameView.h"
+#include "core/platform/HistogramSupport.h"
 
 namespace WebCore {
 
@@ -147,6 +149,10 @@
 
 void FontLoader::didLayout()
 {
+    if (m_document->page() && m_document->page()->mainFrame() == m_document->frame())
+        m_histogram.record();
+    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
+        return;
     if (m_loadingCount || (!m_pendingDoneEvent && m_fontsReadyCallbacks.isEmpty()))
         return;
     if (!m_timer.isActive())
@@ -198,6 +204,10 @@
 
 void FontLoader::beginFontLoading(CSSFontFaceRule* rule)
 {
+    m_histogram.incrementCount();
+    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
+        return;
+
     ++m_loadingCount;
     if (m_loadingCount == 1 && !m_pendingDoneEvent)
         scheduleEvent(CSSFontFaceLoadEvent::createForFontFaceRule(eventNames().loadingEvent, rule));
@@ -207,14 +217,18 @@
 
 void FontLoader::fontLoaded(CSSFontFaceRule* rule)
 {
+    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
+        return;
     scheduleEvent(CSSFontFaceLoadEvent::createForFontFaceRule(eventNames().loadEvent, rule));
     queueDoneEvent(rule);
 }
 
 void FontLoader::loadError(CSSFontFaceRule* rule, CSSFontFaceSource* source)
 {
+    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
+        return;
     // FIXME: We should report NetworkError in case of timeout, etc.
-    String errorName = (source && source->isDecodeError()) ? "InvalidFontDataError" : ExceptionCodeDescription(NOT_FOUND_ERR).name;
+    String errorName = (source && source->isDecodeError()) ? "InvalidFontDataError" : DOMException::getErrorName(NOT_FOUND_ERR);
     scheduleEvent(CSSFontFaceLoadEvent::createForError(rule, DOMError::create(errorName)));
     queueDoneEvent(rule);
 }
@@ -349,4 +363,12 @@
     return true;
 }
 
+void FontLoader::FontLoadHistogram::record()
+{
+    if (m_recorded)
+        return;
+    m_recorded = true;
+    HistogramSupport::histogramCustomCounts("WebFont.WebFontsInPage", m_count, 1, 100, 50);
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/FontLoader.h b/Source/core/css/FontLoader.h
index 1e17800..b8e39d8 100644
--- a/Source/core/css/FontLoader.h
+++ b/Source/core/css/FontLoader.h
@@ -82,6 +82,17 @@
     void scheduleCallback(PassRefPtr<VoidCallback>);
 
 private:
+    class FontLoadHistogram {
+    public:
+        FontLoadHistogram() : m_count(0), m_recorded(false) { }
+        void incrementCount() { m_count++; }
+        void record();
+
+    private:
+        int m_count;
+        bool m_recorded;
+    };
+
     FontLoader(Document*);
 
     virtual void refEventTarget() { ref(); }
@@ -105,6 +116,7 @@
     Vector<RefPtr<VoidCallback> > m_fontsReadyCallbacks;
     RefPtr<Event> m_pendingDoneEvent;
     Timer<FontLoader> m_timer;
+    FontLoadHistogram m_histogram;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/FontSize.h b/Source/core/css/FontSize.h
index 3c309f3..bcc624e 100644
--- a/Source/core/css/FontSize.h
+++ b/Source/core/css/FontSize.h
@@ -22,8 +22,6 @@
 #ifndef FontSize_h
 #define FontSize_h
 
-#include "core/platform/graphics/FontDescription.h"
-
 namespace WebCore {
 
 class Document;
diff --git a/Source/core/css/InspectorCSSOMWrappers.cpp b/Source/core/css/InspectorCSSOMWrappers.cpp
index a84449a..fb1d485 100644
--- a/Source/core/css/InspectorCSSOMWrappers.cpp
+++ b/Source/core/css/InspectorCSSOMWrappers.cpp
@@ -41,8 +41,8 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/DocumentStyleSheetCollection.h"
 
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationHashSet.h>
+#include "wtf/MemoryInstrumentationHashMap.h"
+#include "wtf/MemoryInstrumentationHashSet.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/InspectorCSSOMWrappers.h b/Source/core/css/InspectorCSSOMWrappers.h
index bfe15d7..aca07f7 100644
--- a/Source/core/css/InspectorCSSOMWrappers.h
+++ b/Source/core/css/InspectorCSSOMWrappers.h
@@ -23,11 +23,10 @@
 #ifndef InspectorCSSOMWrappers_h
 #define InspectorCSSOMWrappers_h
 
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/MediaList.cpp b/Source/core/css/MediaList.cpp
index 5d63f29..e746db2 100644
--- a/Source/core/css/MediaList.cpp
+++ b/Source/core/css/MediaList.cpp
@@ -55,13 +55,11 @@
  */
 
 MediaQuerySet::MediaQuerySet()
-    : m_lastLine(0)
 {
 }
 
 MediaQuerySet::MediaQuerySet(const MediaQuerySet& o)
     : RefCounted<MediaQuerySet>()
-    , m_lastLine(o.m_lastLine)
     , m_queries(o.m_queries.size())
 {
     for (unsigned i = 0; i < m_queries.size(); ++i)
diff --git a/Source/core/css/MediaList.h b/Source/core/css/MediaList.h
index 96b5af6..2702137 100644
--- a/Source/core/css/MediaList.h
+++ b/Source/core/css/MediaList.h
@@ -53,9 +53,6 @@
 
     const Vector<OwnPtr<MediaQuery> >& queryVector() const { return m_queries; }
 
-    int lastLine() const { return m_lastLine; }
-    void setLastLine(int lastLine) { m_lastLine = lastLine; }
-
     String mediaText() const;
 
     PassRefPtr<MediaQuerySet> copy() const { return adoptRef(new MediaQuerySet(*this)); }
@@ -66,7 +63,6 @@
     MediaQuerySet();
     MediaQuerySet(const MediaQuerySet&);
 
-    unsigned m_lastLine;
     Vector<OwnPtr<MediaQuery> > m_queries;
 };
 
diff --git a/Source/core/css/MediaQueryEvaluator.cpp b/Source/core/css/MediaQueryEvaluator.cpp
index f647c4b..68d654c 100644
--- a/Source/core/css/MediaQueryEvaluator.cpp
+++ b/Source/core/css/MediaQueryEvaluator.cpp
@@ -68,7 +68,7 @@
 {
 }
 
-MediaQueryEvaluator::MediaQueryEvaluator(const String& acceptedMediaType, bool mediaFeatureResult)
+MediaQueryEvaluator::MediaQueryEvaluator(const AtomicString& acceptedMediaType, bool mediaFeatureResult)
     : m_mediaType(acceptedMediaType)
     , m_frame(0)
     , m_style(0)
@@ -84,7 +84,7 @@
 {
 }
 
-MediaQueryEvaluator::MediaQueryEvaluator(const String& acceptedMediaType, Frame* frame, RenderStyle* style)
+MediaQueryEvaluator::MediaQueryEvaluator(const AtomicString& acceptedMediaType, Frame* frame, RenderStyle* style)
     : m_mediaType(acceptedMediaType)
     , m_frame(frame)
     , m_style(style)
@@ -96,7 +96,7 @@
 {
 }
 
-bool MediaQueryEvaluator::mediaTypeMatch(const String& mediaTypeToMatch) const
+bool MediaQueryEvaluator::mediaTypeMatch(const AtomicString& mediaTypeToMatch) const
 {
     return mediaTypeToMatch.isEmpty()
         || equalIgnoringCase(mediaTypeToMatch, "all")
@@ -108,7 +108,7 @@
     // Like mediaTypeMatch, but without the special cases for "" and "all".
     ASSERT(mediaTypeToMatch);
     ASSERT(mediaTypeToMatch[0] != '\0');
-    ASSERT(!equalIgnoringCase(mediaTypeToMatch, String("all")));
+    ASSERT(!equalIgnoringCase(mediaTypeToMatch, AtomicString("all")));
     return equalIgnoringCase(mediaTypeToMatch, m_mediaType);
 }
 
@@ -347,7 +347,7 @@
     }
 
     if (primitiveValue->isLength()) {
-        result = primitiveValue->computeLength<int>(style, rootStyle);
+        result = primitiveValue->computeLength<int>(style, rootStyle, 1.0 /* multiplier */, true /* computingFontSize */);
         return true;
     }
 
diff --git a/Source/core/css/MediaQueryEvaluator.h b/Source/core/css/MediaQueryEvaluator.h
index dec0c86..eb67ac7 100644
--- a/Source/core/css/MediaQueryEvaluator.h
+++ b/Source/core/css/MediaQueryEvaluator.h
@@ -62,15 +62,15 @@
      *  Evaluator  returns true for acceptedMediaType and returns value of \mediafeatureResult
      *  for any media features
      */
-    MediaQueryEvaluator(const String& acceptedMediaType, bool mediaFeatureResult = false);
+    MediaQueryEvaluator(const AtomicString& acceptedMediaType, bool mediaFeatureResult = false);
     MediaQueryEvaluator(const char* acceptedMediaType, bool mediaFeatureResult = false);
 
     /** Creates evaluator which evaluates full media queries */
-    MediaQueryEvaluator(const String& acceptedMediaType, Frame*, RenderStyle*);
+    MediaQueryEvaluator(const AtomicString& acceptedMediaType, Frame*, RenderStyle*);
 
     ~MediaQueryEvaluator();
 
-    bool mediaTypeMatch(const String& mediaTypeToMatch) const;
+    bool mediaTypeMatch(const AtomicString& mediaTypeToMatch) const;
     bool mediaTypeMatchSpecific(const char* mediaTypeToMatch) const;
 
     /** Evaluates a list of media queries */
@@ -80,7 +80,7 @@
     bool eval(const MediaQueryExp*) const;
 
 private:
-    String m_mediaType;
+    AtomicString m_mediaType;
     Frame* m_frame; // Not owned.
     RefPtr<RenderStyle> m_style;
     bool m_expResult;
diff --git a/Source/core/css/MediaQueryExp.cpp b/Source/core/css/MediaQueryExp.cpp
index d68df26..03a29f7 100644
--- a/Source/core/css/MediaQueryExp.cpp
+++ b/Source/core/css/MediaQueryExp.cpp
@@ -34,7 +34,6 @@
 #include "core/css/CSSAspectRatioValue.h"
 #include "core/css/CSSParser.h"
 #include "core/css/CSSPrimitiveValue.h"
-#include "core/css/CSSValueList.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "wtf/text/StringBuilder.h"
 
diff --git a/Source/core/css/MediaQueryListListener.h b/Source/core/css/MediaQueryListListener.h
index f1d4441..fccf99d 100644
--- a/Source/core/css/MediaQueryListListener.h
+++ b/Source/core/css/MediaQueryListListener.h
@@ -23,7 +23,6 @@
 #include "bindings/v8/ScriptState.h"
 #include "bindings/v8/ScriptValue.h"
 #include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/MediaQueryMatcher.cpp b/Source/core/css/MediaQueryMatcher.cpp
index 094341e..0d3e7c40 100644
--- a/Source/core/css/MediaQueryMatcher.cpp
+++ b/Source/core/css/MediaQueryMatcher.cpp
@@ -66,10 +66,10 @@
     m_document = 0;
 }
 
-String MediaQueryMatcher::mediaType() const
+AtomicString MediaQueryMatcher::mediaType() const
 {
     if (!m_document || !m_document->frame() || !m_document->frame()->view())
-        return String();
+        return nullAtom;
 
     return m_document->frame()->view()->mediaType();
 }
diff --git a/Source/core/css/MediaQueryMatcher.h b/Source/core/css/MediaQueryMatcher.h
index 6293f82..42945b4 100644
--- a/Source/core/css/MediaQueryMatcher.h
+++ b/Source/core/css/MediaQueryMatcher.h
@@ -71,7 +71,7 @@
 
     MediaQueryMatcher(Document*);
     PassOwnPtr<MediaQueryEvaluator> prepareEvaluator() const;
-    String mediaType() const;
+    AtomicString mediaType() const;
 
     Document* m_document;
     Vector<OwnPtr<Listener> > m_listeners;
diff --git a/Source/core/css/PageRuleCollector.cpp b/Source/core/css/PageRuleCollector.cpp
index b09d3a1..3caf4c0 100644
--- a/Source/core/css/PageRuleCollector.cpp
+++ b/Source/core/css/PageRuleCollector.cpp
@@ -71,6 +71,7 @@
     if (!rules)
         return;
 
+    rules->compactRulesIfNeeded();
     Vector<StyleRulePage*> matchedPageRules;
     matchPageRulesForList(matchedPageRules, rules->pageRules(), m_isLeftPage, m_isFirstPage, m_pageName);
     if (matchedPageRules.isEmpty())
diff --git a/Source/core/css/PageRuleCollector.h b/Source/core/css/PageRuleCollector.h
index 544ea38..4fd7dfd 100644
--- a/Source/core/css/PageRuleCollector.h
+++ b/Source/core/css/PageRuleCollector.h
@@ -22,10 +22,8 @@
 #ifndef PageRuleCollector_h
 #define PageRuleCollector_h
 
-#include "core/css/DocumentRuleSets.h"
 #include "core/css/resolver/StyleResolver.h"
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/PropertySetCSSStyleDeclaration.cpp b/Source/core/css/PropertySetCSSStyleDeclaration.cpp
index 356824f..e941cec 100644
--- a/Source/core/css/PropertySetCSSStyleDeclaration.cpp
+++ b/Source/core/css/PropertySetCSSStyleDeclaration.cpp
@@ -26,9 +26,9 @@
 #include "core/css/CSSParser.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/StylePropertySet.h"
+#include "core/dom/Element.h"
 #include "core/dom/MutationObserverInterestGroup.h"
 #include "core/dom/MutationRecord.h"
-#include "core/dom/StyledElement.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include <wtf/MemoryInstrumentationHashMap.h>
diff --git a/Source/core/css/PropertySetCSSStyleDeclaration.h b/Source/core/css/PropertySetCSSStyleDeclaration.h
index ea40793..96fabbe 100644
--- a/Source/core/css/PropertySetCSSStyleDeclaration.h
+++ b/Source/core/css/PropertySetCSSStyleDeclaration.h
@@ -36,13 +36,13 @@
 class CSSValue;
 class MutableStylePropertySet;
 class StyleSheetContents;
-class StyledElement;
+class Element;
 
 class PropertySetCSSStyleDeclaration : public CSSStyleDeclaration {
 public:
     PropertySetCSSStyleDeclaration(MutableStylePropertySet* propertySet) : m_propertySet(propertySet) { }
     
-    virtual StyledElement* parentElement() const { return 0; }
+    virtual Element* parentElement() const { return 0; }
     virtual void clearParentElement() { ASSERT_NOT_REACHED(); }
     StyleSheetContents* contextStyleSheet() const;
     
@@ -117,7 +117,7 @@
 class InlineCSSStyleDeclaration : public PropertySetCSSStyleDeclaration
 {
 public:
-    InlineCSSStyleDeclaration(MutableStylePropertySet* propertySet, StyledElement* parentElement)
+    InlineCSSStyleDeclaration(MutableStylePropertySet* propertySet, Element* parentElement)
         : PropertySetCSSStyleDeclaration(propertySet)
         , m_parentElement(parentElement) 
     {
@@ -127,12 +127,12 @@
     
 private:
     virtual CSSStyleSheet* parentStyleSheet() const OVERRIDE;
-    virtual StyledElement* parentElement() const OVERRIDE { return m_parentElement; }
+    virtual Element* parentElement() const OVERRIDE { return m_parentElement; }
     virtual void clearParentElement() OVERRIDE { m_parentElement = 0; }
 
     virtual void didMutate(MutationType) OVERRIDE;
 
-    StyledElement* m_parentElement;
+    Element* m_parentElement;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/RuleFeature.cpp b/Source/core/css/RuleFeature.cpp
index ea4ad36..29d233d 100644
--- a/Source/core/css/RuleFeature.cpp
+++ b/Source/core/css/RuleFeature.cpp
@@ -31,9 +31,8 @@
 
 #include "core/css/CSSSelector.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationHashSet.h>
-#include <wtf/MemoryInstrumentationVector.h>
+#include "wtf/MemoryInstrumentationHashSet.h"
+#include "wtf/MemoryInstrumentationVector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/RuleFeature.h b/Source/core/css/RuleFeature.h
index 0ffc6e5..1fd7a7c 100644
--- a/Source/core/css/RuleFeature.h
+++ b/Source/core/css/RuleFeature.h
@@ -22,10 +22,9 @@
 #ifndef RuleFeature_h
 #define RuleFeature_h
 
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/text/AtomicString.h>
+#include "wtf/Forward.h"
+#include "wtf/HashSet.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/RuleSet.cpp b/Source/core/css/RuleSet.cpp
index d283692..7d81c94 100644
--- a/Source/core/css/RuleSet.cpp
+++ b/Source/core/css/RuleSet.cpp
@@ -29,9 +29,6 @@
 #include "config.h"
 #include "core/css/RuleSet.h"
 
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationHashSet.h>
-#include <wtf/MemoryInstrumentationVector.h>
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSFontSelector.h"
@@ -47,9 +44,10 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include "weborigin/SecurityOrigin.h"
-
 #include "core/html/track/TextTrackCue.h"
+#include "weborigin/SecurityOrigin.h"
+#include "wtf/MemoryInstrumentationHashMap.h"
+#include "wtf/MemoryInstrumentationVector.h"
 
 namespace WebCore {
 
@@ -62,6 +60,11 @@
     return !scope || scope->isDocumentNode();
 }
 
+static inline bool isScopingNodeInShadowTree(const ContainerNode* scopingNode)
+{
+    return scopingNode && scopingNode->isInShadowTree();
+}
+
 static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector* selector)
 {
     ASSERT(selector);
@@ -132,9 +135,80 @@
     return PropertyWhitelistNone;
 }
 
+namespace {
+
+// FIXME: Should we move this class to WTF?
+template<typename T>
+class TerminatedArrayBuilder {
+public:
+    explicit TerminatedArrayBuilder(PassOwnPtr<T> array)
+        : m_array(array)
+        , m_count(0)
+        , m_capacity(0)
+    {
+        if (!m_array)
+            return;
+        for (T* item = m_array.get(); !item->isLastInArray(); ++item)
+            ++m_count;
+        ++m_count; // To count the last item itself.
+        m_capacity = m_count;
+    }
+
+    void grow(size_t count)
+    {
+        ASSERT(count);
+        if (!m_array) {
+            ASSERT(!m_count);
+            ASSERT(!m_capacity);
+            m_capacity = count;
+            m_array = adoptPtr(static_cast<T*>(fastMalloc(m_capacity * sizeof(T))));
+            return;
+        }
+        m_capacity += count;
+        m_array = adoptPtr(static_cast<T*>(fastRealloc(m_array.leakPtr(), m_capacity * sizeof(T))));
+        m_array.get()[m_count - 1].setLastInArray(false);
+    }
+
+    void append(const T& item)
+    {
+        RELEASE_ASSERT(m_count < m_capacity);
+        ASSERT(!item.isLastInArray());
+        m_array.get()[m_count++] = item;
+    }
+
+    PassOwnPtr<T> release()
+    {
+        RELEASE_ASSERT(m_count == m_capacity);
+        if (m_array)
+            m_array.get()[m_count - 1].setLastInArray(true);
+        assertValid();
+        return m_array.release();
+    }
+
+private:
+#ifndef NDEBUG
+    void assertValid()
+    {
+        for (size_t i = 0; i < m_count; ++i) {
+            bool isLastInArray = (i + 1 == m_count);
+            ASSERT(m_array.get()[i].isLastInArray() == isLastInArray);
+        }
+    }
+#else
+    void assertValid() { }
+#endif
+
+    OwnPtr<T> m_array;
+    size_t m_count;
+    size_t m_capacity;
+};
+
+}
+
 RuleData::RuleData(StyleRule* rule, unsigned selectorIndex, unsigned position, AddRuleFlags addRuleFlags)
     : m_rule(rule)
     , m_selectorIndex(selectorIndex)
+    , m_isLastInArray(false)
     , m_position(position)
     , m_hasFastCheckableSelector((addRuleFlags & RuleCanUseFastCheckSelector) && SelectorCheckerFastPath::canUse(selector()))
     , m_specificity(selector()->specificity())
@@ -147,7 +221,6 @@
 {
     ASSERT(m_position == position);
     ASSERT(m_selectorIndex == selectorIndex);
-    SelectorFilter::collectIdentifierHashes(selector(), m_descendantSelectorIdentifierHashes, maximumIdentifierCount);
 }
 
 void RuleData::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
@@ -200,28 +273,28 @@
         features.uncommonAttributeRules.append(RuleFeature(ruleData.rule(), ruleData.selectorIndex(), ruleData.hasDocumentSecurityOrigin()));
 }
     
-void RuleSet::addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map, const RuleData& ruleData)
+void RuleSet::addToRuleSet(AtomicStringImpl* key, PendingRuleMap& map, const RuleData& ruleData)
 {
     if (!key)
         return;
-    OwnPtr<Vector<RuleData> >& rules = map.add(key, nullptr).iterator->value;
+    OwnPtr<LinkedStack<RuleData> >& rules = map.add(key, nullptr).iterator->value;
     if (!rules)
-        rules = adoptPtr(new Vector<RuleData>);
-    rules->append(ruleData);
+        rules = adoptPtr(new LinkedStack<RuleData>);
+    rules->push(ruleData);
 }
 
 bool RuleSet::findBestRuleSetAndAdd(const CSSSelector* component, RuleData& ruleData)
 {
     if (component->m_match == CSSSelector::Id) {
-        addToRuleSet(component->value().impl(), m_idRules, ruleData);
+        addToRuleSet(component->value().impl(), ensurePendingRules()->idRules, ruleData);
         return true;
     }
     if (component->m_match == CSSSelector::Class) {
-        addToRuleSet(component->value().impl(), m_classRules, ruleData);
+        addToRuleSet(component->value().impl(), ensurePendingRules()->classRules, ruleData);
         return true;
     }
     if (component->isCustomPseudoElement()) {
-        addToRuleSet(component->value().impl(), m_shadowPseudoElementRules, ruleData);
+        addToRuleSet(component->value().impl(), ensurePendingRules()->shadowPseudoElementRules, ruleData);
         return true;
     }
     if (component->pseudoType() == CSSSelector::PseudoCue) {
@@ -252,7 +325,7 @@
                 && findBestRuleSetAndAdd(component->tagHistory(), ruleData))
                 return true;
 
-            addToRuleSet(component->tagQName().localName().impl(), m_tagRules, ruleData);
+            addToRuleSet(component->tagQName().localName().impl(), ensurePendingRules()->tagRules, ruleData);
             return true;
         }
     }
@@ -272,11 +345,13 @@
 
 void RuleSet::addPageRule(StyleRulePage* rule)
 {
+    ensurePendingRules(); // So that m_pageRules.shrinkToFit() gets called.
     m_pageRules.append(rule);
 }
 
 void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin)
 {
+    ensurePendingRules(); // So that m_regionSelectorsAndRuleSets.shrinkToFit() gets called.
     OwnPtr<RuleSet> regionRuleSet = RuleSet::create();
     // The region rule set should take into account the position inside the parent rule set.
     // Otherwise, the rules inside region block might be incorrectly positioned before other similar rules from
@@ -339,10 +414,14 @@
         else if (rule->isRegionRule() && resolver) {
             // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment.
             addRegionRule(static_cast<StyleRuleRegion*>(rule), hasDocumentSecurityOrigin);
-        }
-        else if (rule->isHostRule())
+        } else if (rule->isHostRule() && resolver) {
+            if (!isScopingNodeInShadowTree(scope))
+                continue;
+            bool enabled = resolver->buildScopedStyleTreeInDocumentOrder();
+            resolver->setBuildScopedStyleTreeInDocumentOrder(false);
             resolver->ensureScopedStyleResolver(scope->shadowHost())->addHostRule(static_cast<StyleRuleHost*>(rule), hasDocumentSecurityOrigin, scope);
-        else if (RuntimeEnabledFeatures::cssViewportEnabled() && rule->isViewportRule() && resolver) {
+            resolver->setBuildScopedStyleTreeInDocumentOrder(enabled);
+        } else if (RuntimeEnabledFeatures::cssViewportEnabled() && rule->isViewportRule() && resolver) {
             // @viewport should not be scoped.
             if (!isDocumentScope(scope))
                 continue;
@@ -368,9 +447,6 @@
     AddRuleFlags addRuleFlags = static_cast<AddRuleFlags>((hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : 0) | (!scope ? RuleCanUseFastCheckSelector : 0));
 
     addChildRules(sheet->childRules(), medium, resolver, scope, hasDocumentSecurityOrigin, addRuleFlags);
-
-    if (m_autoShrinkToFitEnabled)
-        shrinkToFit();
 }
 
 void RuleSet::addStyleRule(StyleRule* rule, AddRuleFlags addRuleFlags)
@@ -379,19 +455,32 @@
         addRule(rule, selectorIndex, addRuleFlags);
 }
 
-static inline void shrinkMapVectorsToFit(RuleSet::AtomRuleMap& map)
+void RuleSet::compactPendingRules(PendingRuleMap& pendingMap, CompactRuleMap& compactMap)
 {
-    RuleSet::AtomRuleMap::iterator end = map.end();
-    for (RuleSet::AtomRuleMap::iterator it = map.begin(); it != end; ++it)
-        it->value->shrinkToFit();
+    PendingRuleMap::iterator end = pendingMap.end();
+    for (PendingRuleMap::iterator it = pendingMap.begin(); it != end; ++it) {
+        OwnPtr<LinkedStack<RuleData> > pendingRules = it->value.release();
+        CompactRuleMap::iterator compactRules = compactMap.add(it->key, nullptr).iterator;
+
+        TerminatedArrayBuilder<RuleData> builder(compactRules->value.release());
+        builder.grow(pendingRules->size());
+        while (!pendingRules->isEmpty()) {
+            builder.append(pendingRules->peek());
+            pendingRules->pop();
+        }
+
+        compactRules->value = builder.release();
+    }
 }
 
-void RuleSet::shrinkToFit()
+void RuleSet::compactRules()
 {
-    shrinkMapVectorsToFit(m_idRules);
-    shrinkMapVectorsToFit(m_classRules);
-    shrinkMapVectorsToFit(m_tagRules);
-    shrinkMapVectorsToFit(m_shadowPseudoElementRules);
+    ASSERT(m_pendingRules);
+    OwnPtr<PendingRuleMaps> pendingRules = m_pendingRules.release();
+    compactPendingRules(pendingRules->idRules, m_idRules);
+    compactPendingRules(pendingRules->classRules, m_classRules);
+    compactPendingRules(pendingRules->tagRules, m_tagRules);
+    compactPendingRules(pendingRules->shadowPseudoElementRules, m_shadowPseudoElementRules);
     m_linkPseudoClassRules.shrinkToFit();
     m_cuePseudoRules.shrinkToFit();
     m_focusPseudoClassRules.shrinkToFit();
diff --git a/Source/core/css/RuleSet.h b/Source/core/css/RuleSet.h
index 82c3103..bddf7df 100644
--- a/Source/core/css/RuleSet.h
+++ b/Source/core/css/RuleSet.h
@@ -24,10 +24,9 @@
 
 #include "core/css/RuleFeature.h"
 #include "core/css/StyleRule.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/text/AtomicString.h>
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/LinkedStack.h"
 
 namespace WebCore {
 
@@ -52,6 +51,7 @@
 class StyleSheetContents;
 
 class RuleData {
+    NEW_DELETE_SAME_AS_MALLOC_FREE;
 public:
     RuleData(StyleRule*, unsigned selectorIndex, unsigned position, AddRuleFlags);
 
@@ -60,6 +60,9 @@
     const CSSSelector* selector() const { return m_rule->selectorList().selectorAt(m_selectorIndex); }
     unsigned selectorIndex() const { return m_selectorIndex; }
 
+    bool isLastInArray() const { return m_isLastInArray; }
+    void setLastInArray(bool flag) { m_isLastInArray = flag; }
+
     bool hasFastCheckableSelector() const { return m_hasFastCheckableSelector; }
     bool hasMultipartSelector() const { return m_hasMultipartSelector; }
     bool hasRightmostSelectorMatchingHTMLBasedOnRuleHash() const { return m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash; }
@@ -68,15 +71,13 @@
     unsigned linkMatchType() const { return m_linkMatchType; }
     bool hasDocumentSecurityOrigin() const { return m_hasDocumentSecurityOrigin; }
     PropertyWhitelistType propertyWhitelistType(bool isMatchingUARules = false) const { return isMatchingUARules ? PropertyWhitelistNone : static_cast<PropertyWhitelistType>(m_propertyWhitelistType); }
-    // Try to balance between memory usage (there can be lots of RuleData objects) and good filtering performance.
-    static const unsigned maximumIdentifierCount = 4;
-    const unsigned* descendantSelectorIdentifierHashes() const { return m_descendantSelectorIdentifierHashes; }
 
     void reportMemoryUsage(MemoryObjectInfo*) const;
 
 private:
     StyleRule* m_rule;
-    unsigned m_selectorIndex : 13;
+    unsigned m_selectorIndex : 12;
+    unsigned m_isLastInArray : 1; // We store an array of RuleData objects in a primitive array.
     // This number was picked fairly arbitrarily. We can probably lower it if we need to.
     // Some simple testing showed <100,000 RuleData's on large sites.
     unsigned m_position : 18;
@@ -88,15 +89,12 @@
     unsigned m_linkMatchType : 2; //  SelectorChecker::LinkMatchMask
     unsigned m_hasDocumentSecurityOrigin : 1;
     unsigned m_propertyWhitelistType : 2;
-    // Use plain array instead of a Vector to minimize memory overhead.
-    unsigned m_descendantSelectorIdentifierHashes[maximumIdentifierCount];
 };
     
 struct SameSizeAsRuleData {
     void* a;
     unsigned b;
     unsigned c;
-    unsigned d[4];
 };
 
 COMPILE_ASSERT(sizeof(RuleData) == sizeof(SameSizeAsRuleData), RuleData_should_stay_small);
@@ -106,52 +104,33 @@
 public:
     static PassOwnPtr<RuleSet> create() { return adoptPtr(new RuleSet); }
 
-    typedef HashMap<AtomicStringImpl*, OwnPtr<Vector<RuleData> > > AtomRuleMap;
-
     void addRulesFromSheet(StyleSheetContents*, const MediaQueryEvaluator&, StyleResolver* = 0, const ContainerNode* = 0);
-
     void addStyleRule(StyleRule*, AddRuleFlags);
     void addRule(StyleRule*, unsigned selectorIndex, AddRuleFlags);
-    void addPageRule(StyleRulePage*);
-    void addToRuleSet(AtomicStringImpl* key, AtomRuleMap&, const RuleData&);
-    void addRegionRule(StyleRuleRegion*, bool hasDocumentSecurityOrigin);
-    void shrinkToFit();
-    void disableAutoShrinkToFit() { m_autoShrinkToFitEnabled = false; }
 
     const RuleFeatureSet& features() const { return m_features; }
 
-    const Vector<RuleData>* idRules(AtomicStringImpl* key) const { return m_idRules.get(key); }
-    const Vector<RuleData>* classRules(AtomicStringImpl* key) const { return m_classRules.get(key); }
-    const Vector<RuleData>* tagRules(AtomicStringImpl* key) const { return m_tagRules.get(key); }
-    const Vector<RuleData>* shadowPseudoElementRules(AtomicStringImpl* key) const { return m_shadowPseudoElementRules.get(key); }
-    const Vector<RuleData>* linkPseudoClassRules() const { return &m_linkPseudoClassRules; }
-    const Vector<RuleData>* cuePseudoRules() const { return &m_cuePseudoRules; }
-    const Vector<RuleData>* focusPseudoClassRules() const { return &m_focusPseudoClassRules; }
-    const Vector<RuleData>* universalRules() const { return &m_universalRules; }
-    const Vector<StyleRulePage*>& pageRules() const { return m_pageRules; }
+    const RuleData* idRules(AtomicStringImpl* key) const { ASSERT(!m_pendingRules); return m_idRules.get(key); }
+    const RuleData* classRules(AtomicStringImpl* key) const { ASSERT(!m_pendingRules); return m_classRules.get(key); }
+    const RuleData* tagRules(AtomicStringImpl* key) const { ASSERT(!m_pendingRules); return m_tagRules.get(key); }
+    const RuleData* shadowPseudoElementRules(AtomicStringImpl* key) const { ASSERT(!m_pendingRules); return m_shadowPseudoElementRules.get(key); }
+    const Vector<RuleData>* linkPseudoClassRules() const { ASSERT(!m_pendingRules); return &m_linkPseudoClassRules; }
+    const Vector<RuleData>* cuePseudoRules() const { ASSERT(!m_pendingRules); return &m_cuePseudoRules; }
+    const Vector<RuleData>* focusPseudoClassRules() const { ASSERT(!m_pendingRules); return &m_focusPseudoClassRules; }
+    const Vector<RuleData>* universalRules() const { ASSERT(!m_pendingRules); return &m_universalRules; }
+    const Vector<StyleRulePage*>& pageRules() const { ASSERT(!m_pendingRules); return m_pageRules; }
+
+    unsigned ruleCount() const { return m_ruleCount; }
+
+    void compactRulesIfNeeded()
+    {
+        if (!m_pendingRules)
+            return;
+        compactRules();
+    }
 
     void reportMemoryUsage(MemoryObjectInfo*) const;
 
-private:
-    void addChildRules(const Vector<RefPtr<StyleRuleBase> >&, const MediaQueryEvaluator& medium, StyleResolver*, const ContainerNode* scope, bool hasDocumentSecurityOrigin, AddRuleFlags);
-    bool findBestRuleSetAndAdd(const CSSSelector*, RuleData&);
-
-public:
-    RuleSet();
-
-    AtomRuleMap m_idRules;
-    AtomRuleMap m_classRules;
-    AtomRuleMap m_tagRules;
-    AtomRuleMap m_shadowPseudoElementRules;
-    Vector<RuleData> m_linkPseudoClassRules;
-    Vector<RuleData> m_cuePseudoRules;
-    Vector<RuleData> m_focusPseudoClassRules;
-    Vector<RuleData> m_universalRules;
-    Vector<StyleRulePage*> m_pageRules;
-    unsigned m_ruleCount;
-    bool m_autoShrinkToFitEnabled;
-    RuleFeatureSet m_features;
-
     struct RuleSetSelectorPair {
         RuleSetSelectorPair(const CSSSelector* selector, PassOwnPtr<RuleSet> ruleSet) : selector(selector), ruleSet(ruleSet) { }
         RuleSetSelectorPair(const RuleSetSelectorPair& rs) : selector(rs.selector), ruleSet(const_cast<RuleSetSelectorPair*>(&rs)->ruleSet.release()) { }
@@ -162,13 +141,54 @@
     };
 
     Vector<RuleSetSelectorPair> m_regionSelectorsAndRuleSets;
-};
 
-inline RuleSet::RuleSet()
-    : m_ruleCount(0)
-    , m_autoShrinkToFitEnabled(true)
-{
-}
+private:
+    typedef HashMap<AtomicStringImpl*, OwnPtr<LinkedStack<RuleData> > > PendingRuleMap;
+    typedef HashMap<AtomicStringImpl*, OwnPtr<RuleData> > CompactRuleMap;
+
+    RuleSet()
+        : m_ruleCount(0)
+    {
+    }
+
+    void addToRuleSet(AtomicStringImpl* key, PendingRuleMap&, const RuleData&);
+    void addPageRule(StyleRulePage*);
+    void addRegionRule(StyleRuleRegion*, bool hasDocumentSecurityOrigin);
+
+    void addChildRules(const Vector<RefPtr<StyleRuleBase> >&, const MediaQueryEvaluator& medium, StyleResolver*, const ContainerNode* scope, bool hasDocumentSecurityOrigin, AddRuleFlags);
+    bool findBestRuleSetAndAdd(const CSSSelector*, RuleData&);
+
+    void compactRules();
+    static void compactPendingRules(PendingRuleMap&, CompactRuleMap&);
+
+    struct PendingRuleMaps {
+        PendingRuleMap idRules;
+        PendingRuleMap classRules;
+        PendingRuleMap tagRules;
+        PendingRuleMap shadowPseudoElementRules;
+    };
+
+    PendingRuleMaps* ensurePendingRules()
+    {
+        if (!m_pendingRules)
+            m_pendingRules = adoptPtr(new PendingRuleMaps);
+        return m_pendingRules.get();
+    }
+
+    CompactRuleMap m_idRules;
+    CompactRuleMap m_classRules;
+    CompactRuleMap m_tagRules;
+    CompactRuleMap m_shadowPseudoElementRules;
+    Vector<RuleData> m_linkPseudoClassRules;
+    Vector<RuleData> m_cuePseudoRules;
+    Vector<RuleData> m_focusPseudoClassRules;
+    Vector<RuleData> m_universalRules;
+    RuleFeatureSet m_features;
+    Vector<StyleRulePage*> m_pageRules;
+
+    unsigned m_ruleCount;
+    OwnPtr<PendingRuleMaps> m_pendingRules;
+};
 
 } // namespace WebCore
 
diff --git a/Source/core/css/SVGCSSStyleSelector.cpp b/Source/core/css/SVGCSSStyleSelector.cpp
index 912ddd9..3fb1bc7 100644
--- a/Source/core/css/SVGCSSStyleSelector.cpp
+++ b/Source/core/css/SVGCSSStyleSelector.cpp
@@ -30,7 +30,6 @@
 
 #include "core/css/resolver/StyleResolver.h"
 
-#include <stdlib.h>
 #include "CSSPropertyNames.h"
 #include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/css/CSSValueList.h"
@@ -40,7 +39,7 @@
 #include "core/svg/SVGColor.h"
 #include "core/svg/SVGPaint.h"
 #include "core/svg/SVGURIReference.h"
-#include <wtf/MathExtras.h>
+#include "wtf/MathExtras.h"
 
 #define HANDLE_INHERIT(prop, Prop) \
 if (isInherit) \
@@ -566,7 +565,7 @@
             int blur = item->blur ? item->blur->computeLength<int>(state.style(), state.rootElementStyle()) : 0;
             Color color;
             if (item->color)
-                color = colorFromPrimitiveValue(item->color.get());
+                color = resolveColorFromPrimitiveValue(item->color.get());
 
             // -webkit-svg-shadow does should not have a spread or style
             ASSERT(!item->spread);
diff --git a/Source/core/css/SelectorChecker.cpp b/Source/core/css/SelectorChecker.cpp
index fb1a811..56757a9 100644
--- a/Source/core/css/SelectorChecker.cpp
+++ b/Source/core/css/SelectorChecker.cpp
@@ -33,9 +33,9 @@
 #include "core/css/CSSSelectorList.h"
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/dom/Document.h"
+#include "core/dom/Element.h"
 #include "core/dom/FullscreenController.h"
 #include "core/dom/NodeRenderStyle.h"
-#include "core/dom/StyledElement.h"
 #include "core/dom/Text.h"
 #include "core/dom/shadow/InsertionPoint.h"
 #include "core/dom/shadow/ShadowRoot.h"
@@ -340,7 +340,7 @@
         return SelectorChecker::tagMatches(element, selector->tagQName());
 
     if (selector->m_match == CSSSelector::Class)
-        return element->hasClass() && static_cast<StyledElement*>(element)->classNames().contains(selector->value());
+        return element->hasClass() && element->classNames().contains(selector->value());
 
     if (selector->m_match == CSSSelector::Id)
         return element->hasID() && element->idForStyleResolution() == selector->value();
@@ -688,7 +688,7 @@
             // element is an element in the document, the 'full-screen' pseudoclass applies to
             // that element. Also, an <iframe>, <object> or <embed> element whose child browsing
             // context's Document is in the fullscreen state has the 'full-screen' pseudoclass applied.
-            if (element->isFrameElementBase() && static_cast<HTMLFrameElementBase*>(element)->containsFullScreenElement())
+            if (element->isFrameElementBase() && element->containsFullScreenElement())
                 return true;
             if (FullscreenController* fullscreen = FullscreenController::fromIfExists(element->document())) {
                 if (!fullscreen->webkitIsFullScreen())
@@ -696,13 +696,6 @@
                 return element == fullscreen->webkitCurrentFullScreenElement();
             }
             return false;
-        case CSSSelector::PseudoAnimatingFullScreenTransition:
-            if (FullscreenController* fullscreen = FullscreenController::fromIfExists(element->document())) {
-                if (!fullscreen->isAnimatingFullScreen())
-                    return false;
-                return element == fullscreen->webkitCurrentFullScreenElement();
-            }
-            return false;
         case CSSSelector::PseudoFullScreenAncestor:
             return element->containsFullScreenElement();
         case CSSSelector::PseudoFullScreenDocument:
diff --git a/Source/core/css/SelectorChecker.h b/Source/core/css/SelectorChecker.h
index 2b192e7..c1f7fd1 100644
--- a/Source/core/css/SelectorChecker.h
+++ b/Source/core/css/SelectorChecker.h
@@ -29,10 +29,7 @@
 #define SelectorChecker_h
 
 #include "core/css/CSSSelector.h"
-#include "core/dom/SpaceSplitString.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include <wtf/HashSet.h>
-#include <wtf/Vector.h>
 
 namespace WebCore {
 
diff --git a/Source/core/css/SelectorCheckerFastPath.cpp b/Source/core/css/SelectorCheckerFastPath.cpp
index daf7449..7c8fecb 100644
--- a/Source/core/css/SelectorCheckerFastPath.cpp
+++ b/Source/core/css/SelectorCheckerFastPath.cpp
@@ -30,7 +30,7 @@
 #include "core/css/SelectorCheckerFastPath.h"
 
 #include "HTMLNames.h"
-#include "core/dom/StyledElement.h"
+#include "core/dom/Element.h"
 #include "core/html/HTMLDocument.h"
 
 namespace WebCore {
@@ -75,7 +75,7 @@
 
 inline bool checkClassValue(const Element* element, const CSSSelector* selector)
 {
-    return element->hasClass() && static_cast<const StyledElement*>(element)->classNames().contains(selector->value().impl());
+    return element->hasClass() && element->classNames().contains(selector->value().impl());
 }
 
 inline bool checkIDValue(const Element* element, const CSSSelector* selector)
diff --git a/Source/core/css/SelectorFilter.cpp b/Source/core/css/SelectorFilter.cpp
index 632a7ec..239bc45 100644
--- a/Source/core/css/SelectorFilter.cpp
+++ b/Source/core/css/SelectorFilter.cpp
@@ -30,7 +30,7 @@
 #include "core/css/SelectorFilter.h"
 
 #include "core/css/CSSSelector.h"
-#include "core/dom/StyledElement.h"
+#include "core/dom/Element.h"
 
 namespace WebCore {
 
@@ -42,9 +42,8 @@
     identifierHashes.append(element->localName().impl()->existingHash() * TagNameSalt);
     if (element->hasID())
         identifierHashes.append(element->idForStyleResolution().impl()->existingHash() * IdAttributeSalt);
-    const StyledElement* styledElement = element->isStyledElement() ? static_cast<const StyledElement*>(element) : 0;
-    if (styledElement && styledElement->hasClass()) {
-        const SpaceSplitString& classNames = styledElement->classNames();
+    if (element->isStyledElement() && element->hasClass()) {
+        const SpaceSplitString& classNames = element->classNames();
         size_t count = classNames.size();
         for (size_t i = 0; i < count; ++i)
             identifierHashes.append(classNames[i].impl()->existingHash() * ClassAttributeSalt);
@@ -110,30 +109,36 @@
     pushParentStackFrame(parent);
 }
 
-static inline void collectDescendantSelectorIdentifierHashes(const CSSSelector* selector, unsigned*& hash)
+static unsigned selectorIdentifierHash(const CSSSelector* selector)
 {
     switch (selector->m_match) {
     case CSSSelector::Id:
         if (!selector->value().isEmpty())
-            (*hash++) = selector->value().impl()->existingHash() * IdAttributeSalt;
+            return selector->value().impl()->existingHash() * IdAttributeSalt;
         break;
     case CSSSelector::Class:
         if (!selector->value().isEmpty())
-            (*hash++) = selector->value().impl()->existingHash() * ClassAttributeSalt;
+            return selector->value().impl()->existingHash() * ClassAttributeSalt;
         break;
     case CSSSelector::Tag:
         if (selector->tagQName().localName() != starAtom)
-            (*hash++) = selector->tagQName().localName().impl()->existingHash() * TagNameSalt;
+            return selector->tagQName().localName().impl()->existingHash() * TagNameSalt;
         break;
     default:
         break;
     }
+    return 0;
 }
 
-void SelectorFilter::collectIdentifierHashes(const CSSSelector* selector, unsigned* identifierHashes, unsigned maximumIdentifierCount)
+bool SelectorFilter::fastRejectSelector(const CSSSelector* selector) const
 {
-    unsigned* hash = identifierHashes;
-    unsigned* end = identifierHashes + maximumIdentifierCount;
+    ASSERT(m_ancestorIdentifierFilter);
+
+    // FIXME: Tune this parameter. This parameter was originally selected when
+    // we materialized the selector identifier hashes in RuleData objects,
+    // which meant that increasing increased memory usage.
+    size_t remainingHashesToCheck = 4;
+
     CSSSelector::Relation relation = selector->relation();
     bool relationIsForShadowDistributed = selector->relationIsForShadowDistributed();
 
@@ -143,8 +148,14 @@
         // Only collect identifiers that match ancestors.
         switch (relation) {
         case CSSSelector::SubSelector:
-            if (!skipOverSubselectors)
-                collectDescendantSelectorIdentifierHashes(selector, hash);
+            if (!skipOverSubselectors) {
+                if (unsigned hash = selectorIdentifierHash(selector)) {
+                    if (!m_ancestorIdentifierFilter->mayContain(hash))
+                        return true;
+                    if (!--remainingHashesToCheck)
+                        return false;
+                }
+            }
             break;
         case CSSSelector::DirectAdjacent:
         case CSSSelector::IndirectAdjacent:
@@ -158,15 +169,20 @@
                 break;
             }
             skipOverSubselectors = false;
-            collectDescendantSelectorIdentifierHashes(selector, hash);
+            if (unsigned hash = selectorIdentifierHash(selector)) {
+                if (!m_ancestorIdentifierFilter->mayContain(hash))
+                    return true;
+                if (!--remainingHashesToCheck)
+                    return false;
+            }
             break;
         }
-        if (hash == end)
-            return;
+
         relation = selector->relation();
         relationIsForShadowDistributed = selector->relationIsForShadowDistributed();
     }
-    *hash = 0;
+
+    return false;
 }
 
 }
diff --git a/Source/core/css/SelectorFilter.h b/Source/core/css/SelectorFilter.h
index 4025ca3..2e44252 100644
--- a/Source/core/css/SelectorFilter.h
+++ b/Source/core/css/SelectorFilter.h
@@ -48,9 +48,7 @@
     bool parentStackIsEmpty() const { return m_parentStack.isEmpty(); }
     bool parentStackIsConsistent(const ContainerNode* parentNode) const { return !m_parentStack.isEmpty() && m_parentStack.last().element == parentNode; }
 
-    template <unsigned maximumIdentifierCount>
-    inline bool fastRejectSelector(const unsigned* identifierHashes) const;
-    static void collectIdentifierHashes(const CSSSelector*, unsigned* identifierHashes, unsigned maximumIdentifierCount);
+    bool fastRejectSelector(const CSSSelector*) const;
 
 private:
     struct ParentStackFrame {
@@ -66,17 +64,6 @@
     OwnPtr<BloomFilter<bloomFilterKeyBits> > m_ancestorIdentifierFilter;
 };
 
-template <unsigned maximumIdentifierCount>
-inline bool SelectorFilter::fastRejectSelector(const unsigned* identifierHashes) const
-{
-    ASSERT(m_ancestorIdentifierFilter);
-    for (unsigned n = 0; n < maximumIdentifierCount && identifierHashes[n]; ++n) {
-        if (!m_ancestorIdentifierFilter->mayContain(identifierHashes[n]))
-            return true;
-    }
-    return false;
-}
-
 }
 
 #endif
diff --git a/Source/core/css/StyleInvalidationAnalysis.cpp b/Source/core/css/StyleInvalidationAnalysis.cpp
index b0ef035..47ce49a 100644
--- a/Source/core/css/StyleInvalidationAnalysis.cpp
+++ b/Source/core/css/StyleInvalidationAnalysis.cpp
@@ -119,7 +119,7 @@
     }
     if (styleSheetContents->hasSingleOwnerNode()) {
         Node* ownerNode = styleSheetContents->singleOwnerNode();
-        if (ownerNode && isHTMLStyleElement(ownerNode) && toHTMLStyleElement(ownerNode)->isRegisteredAsScoped()) {
+        if (ownerNode && ownerNode->hasTagName(HTMLNames::styleTag) && toHTMLStyleElement(ownerNode)->isRegisteredAsScoped()) {
             m_scopingNodes.append(determineScopingNodeForStyleScoped(toHTMLStyleElement(ownerNode), styleSheetContents));
             return;
         }
diff --git a/Source/core/css/StyleInvalidationAnalysis.h b/Source/core/css/StyleInvalidationAnalysis.h
index 5e2c4b9..18dad9f 100644
--- a/Source/core/css/StyleInvalidationAnalysis.h
+++ b/Source/core/css/StyleInvalidationAnalysis.h
@@ -26,10 +26,9 @@
 #ifndef StyleInvalidationAnalysis_h
 #define StyleInvalidationAnalysis_h
 
-#include <wtf/HashSet.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/Vector.h>
-#include <wtf/text/AtomicStringImpl.h>
+#include "wtf/HashSet.h"
+#include "wtf/Vector.h"
+#include "wtf/text/AtomicStringImpl.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/StylePropertySerializer.cpp b/Source/core/css/StylePropertySerializer.cpp
index c132da4..3e2135c 100644
--- a/Source/core/css/StylePropertySerializer.cpp
+++ b/Source/core/css/StylePropertySerializer.cpp
@@ -86,6 +86,10 @@
         case CSSPropertyBackgroundRepeatY:
             repeatYPropertyIndex = n;
             continue;
+        case CSSPropertyContent:
+            if (property.value()->isValueList())
+                value = toCSSValueList(property.value())->customCssText(AlwaysQuoteCSSString);
+            break;
         case CSSPropertyBorderTopWidth:
         case CSSPropertyBorderRightWidth:
         case CSSPropertyBorderBottomWidth:
@@ -170,14 +174,14 @@
         case CSSPropertyWebkitAnimationFillMode:
             shorthandPropertyID = CSSPropertyWebkitAnimation;
             break;
-        case CSSPropertyWebkitFlexDirection:
-        case CSSPropertyWebkitFlexWrap:
-            shorthandPropertyID = CSSPropertyWebkitFlexFlow;
+        case CSSPropertyFlexDirection:
+        case CSSPropertyFlexWrap:
+            shorthandPropertyID = CSSPropertyFlexFlow;
             break;
-        case CSSPropertyWebkitFlexBasis:
-        case CSSPropertyWebkitFlexGrow:
-        case CSSPropertyWebkitFlexShrink:
-            shorthandPropertyID = CSSPropertyWebkitFlex;
+        case CSSPropertyFlexBasis:
+        case CSSPropertyFlexGrow:
+        case CSSPropertyFlexShrink:
+            shorthandPropertyID = CSSPropertyFlex;
             break;
         case CSSPropertyWebkitMaskPositionX:
         case CSSPropertyWebkitMaskPositionY:
@@ -215,8 +219,10 @@
         }
 
         if (!value.isNull()) {
-            propertyID = shorthandPropertyID;
-            shorthandPropertyUsed.set(shortPropertyIndex);
+            if (shorthandPropertyID) {
+                propertyID = shorthandPropertyID;
+                shorthandPropertyUsed.set(shortPropertyIndex);
+            }
         } else
             value = property.value()->cssText();
 
@@ -336,10 +342,10 @@
         return getShorthandValue(webkitColumnRuleShorthand());
     case CSSPropertyWebkitColumns:
         return getShorthandValue(webkitColumnsShorthand());
-    case CSSPropertyWebkitFlex:
-        return getShorthandValue(webkitFlexShorthand());
-    case CSSPropertyWebkitFlexFlow:
-        return getShorthandValue(webkitFlexFlowShorthand());
+    case CSSPropertyFlex:
+        return getShorthandValue(flexShorthand());
+    case CSSPropertyFlexFlow:
+        return getShorthandValue(flexFlowShorthand());
     case CSSPropertyGridColumn:
         return getShorthandValue(gridColumnShorthand());
     case CSSPropertyGridRow:
diff --git a/Source/core/css/StylePropertySerializer.h b/Source/core/css/StylePropertySerializer.h
index e15d1a2..55d1027 100644
--- a/Source/core/css/StylePropertySerializer.h
+++ b/Source/core/css/StylePropertySerializer.h
@@ -23,11 +23,8 @@
 #ifndef StylePropertySerializer_h
 #define StylePropertySerializer_h
 
-#include "core/css/CSSValue.h"
 #include "core/css/CSSValueList.h"
 #include "core/css/StylePropertySet.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
 
 namespace WebCore {
 
diff --git a/Source/core/css/StylePropertySet.cpp b/Source/core/css/StylePropertySet.cpp
index 352e0ee..8146755 100644
--- a/Source/core/css/StylePropertySet.cpp
+++ b/Source/core/css/StylePropertySet.cpp
@@ -30,14 +30,12 @@
 #include "core/css/StylePropertyShorthand.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/page/RuntimeCSSEnabled.h"
-#include <wtf/BitArray.h>
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/MemoryInstrumentationVector.h"
+#include "wtf/text/StringBuilder.h"
 
 #ifndef NDEBUG
+#include "wtf/text/CString.h"
 #include <stdio.h>
-#include <wtf/ASCIICType.h>
-#include <wtf/text/CString.h>
 #endif
 
 using namespace std;
@@ -535,7 +533,7 @@
     return cssomWrapper;
 }
 
-CSSStyleDeclaration* MutableStylePropertySet::ensureInlineCSSStyleDeclaration(StyledElement* parentElement)
+CSSStyleDeclaration* MutableStylePropertySet::ensureInlineCSSStyleDeclaration(Element* parentElement)
 {
     if (m_ownsCSSOMWrapper) {
         ASSERT(propertySetCSSOMWrapperMap().get(this)->parentElement() == parentElement);
@@ -594,7 +592,7 @@
         ASSERT(propertyValue()->isVariableValue());
         if (!propertyValue()->isVariableValue())
             return emptyString(); // Should not happen, but if it does, avoid a bad cast.
-        return "-webkit-var-" + static_cast<const CSSVariableValue*>(propertyValue())->name();
+        return "var-" + static_cast<const CSSVariableValue*>(propertyValue())->name();
     }
     return getPropertyNameString(id());
 }
diff --git a/Source/core/css/StylePropertySet.h b/Source/core/css/StylePropertySet.h
index 7d40b49..3fed430 100644
--- a/Source/core/css/StylePropertySet.h
+++ b/Source/core/css/StylePropertySet.h
@@ -33,11 +33,11 @@
 
 class CSSRule;
 class CSSStyleDeclaration;
+class Element;
 class ImmutableStylePropertySet;
 class KURL;
 class MutableStylePropertySet;
 class PropertySetCSSStyleDeclaration;
-class StyledElement;
 class StylePropertyShorthand;
 class StyleSheetContents;
 
@@ -211,7 +211,7 @@
     void parseDeclaration(const String& styleDeclaration, StyleSheetContents* contextStyleSheet);
 
     CSSStyleDeclaration* ensureCSSStyleDeclaration();
-    CSSStyleDeclaration* ensureInlineCSSStyleDeclaration(StyledElement* parentElement);
+    CSSStyleDeclaration* ensureInlineCSSStyleDeclaration(Element* parentElement);
 
     Vector<CSSProperty, 4> m_propertyVector;
 
diff --git a/Source/core/css/StylePropertyShorthand.cpp b/Source/core/css/StylePropertyShorthand.cpp
index 8d0de73..6e6512f 100644
--- a/Source/core/css/StylePropertyShorthand.cpp
+++ b/Source/core/css/StylePropertyShorthand.cpp
@@ -369,18 +369,18 @@
     return webkitColumnRuleLonghands;
 }
 
-const StylePropertyShorthand& webkitFlexFlowShorthand()
+const StylePropertyShorthand& flexFlowShorthand()
 {
-    static const CSSPropertyID flexFlowProperties[] = { CSSPropertyWebkitFlexDirection, CSSPropertyWebkitFlexWrap };
-    DEFINE_STATIC_LOCAL(StylePropertyShorthand, webkitFlexFlowLonghands, (CSSPropertyWebkitFlexFlow, flexFlowProperties, WTF_ARRAY_LENGTH(flexFlowProperties)));
-    return webkitFlexFlowLonghands;
+    static const CSSPropertyID flexFlowProperties[] = { CSSPropertyFlexDirection, CSSPropertyFlexWrap };
+    DEFINE_STATIC_LOCAL(StylePropertyShorthand, flexFlowLonghands, (CSSPropertyFlexFlow, flexFlowProperties, WTF_ARRAY_LENGTH(flexFlowProperties)));
+    return flexFlowLonghands;
 }
 
-const StylePropertyShorthand& webkitFlexShorthand()
+const StylePropertyShorthand& flexShorthand()
 {
-    static const CSSPropertyID flexProperties[] = { CSSPropertyWebkitFlexGrow, CSSPropertyWebkitFlexShrink, CSSPropertyWebkitFlexBasis };
-    DEFINE_STATIC_LOCAL(StylePropertyShorthand, webkitFlexLonghands, (CSSPropertyWebkitFlex, flexProperties, WTF_ARRAY_LENGTH(flexProperties)));
-    return webkitFlexLonghands;
+    static const CSSPropertyID flexProperties[] = { CSSPropertyFlexGrow, CSSPropertyFlexShrink, CSSPropertyFlexBasis };
+    DEFINE_STATIC_LOCAL(StylePropertyShorthand, flexLonghands, (CSSPropertyFlex, flexProperties, WTF_ARRAY_LENGTH(flexProperties)));
+    return flexLonghands;
 }
 
 const StylePropertyShorthand& webkitMarginCollapseShorthand()
@@ -393,8 +393,8 @@
 const StylePropertyShorthand& gridColumnShorthand()
 {
     static const CSSPropertyID gridColumnProperties[] = {
-        CSSPropertyGridStart,
-        CSSPropertyGridEnd
+        CSSPropertyGridColumnStart,
+        CSSPropertyGridColumnEnd
     };
     DEFINE_STATIC_LOCAL(StylePropertyShorthand, gridColumnLonghands, (CSSPropertyGridColumn, gridColumnProperties, WTF_ARRAY_LENGTH(gridColumnProperties)));
     return gridColumnLonghands;
@@ -403,8 +403,8 @@
 const StylePropertyShorthand& gridRowShorthand()
 {
     static const CSSPropertyID gridRowProperties[] = {
-        CSSPropertyGridBefore,
-        CSSPropertyGridAfter
+        CSSPropertyGridRowStart,
+        CSSPropertyGridRowEnd
     };
     DEFINE_STATIC_LOCAL(StylePropertyShorthand, gridRowLonghands, (CSSPropertyGridRow, gridRowProperties, WTF_ARRAY_LENGTH(gridRowProperties)));
     return gridRowLonghands;
@@ -413,10 +413,10 @@
 const StylePropertyShorthand& gridAreaShorthand()
 {
     static const CSSPropertyID gridAreaProperties[] = {
-        CSSPropertyGridStart,
-        CSSPropertyGridBefore,
-        CSSPropertyGridEnd,
-        CSSPropertyGridAfter
+        CSSPropertyGridColumnStart,
+        CSSPropertyGridRowStart,
+        CSSPropertyGridColumnEnd,
+        CSSPropertyGridRowEnd
     };
     DEFINE_STATIC_LOCAL(StylePropertyShorthand, gridAreaLonghands, (CSSPropertyGridArea, gridAreaProperties, WTF_ARRAY_LENGTH(gridAreaProperties)));
     return gridAreaLonghands;
@@ -587,10 +587,10 @@
         return webkitColumnsShorthand();
     case CSSPropertyWebkitColumnRule:
         return webkitColumnRuleShorthand();
-    case CSSPropertyWebkitFlex:
-        return webkitFlexShorthand();
-    case CSSPropertyWebkitFlexFlow:
-        return webkitFlexFlowShorthand();
+    case CSSPropertyFlex:
+        return flexShorthand();
+    case CSSPropertyFlexFlow:
+        return flexFlowShorthand();
     case CSSPropertyGridColumn:
         return gridColumnShorthand();
     case CSSPropertyGridRow:
@@ -853,27 +853,27 @@
         map.set(CSSPropertyWebkitColumnRuleColor, columnRule);
 
         Vector<StylePropertyShorthand, 1> flex;
-        flex.uncheckedAppend(webkitFlexShorthand());
-        map.set(CSSPropertyWebkitFlexGrow, flex);
-        map.set(CSSPropertyWebkitFlexShrink, flex);
-        map.set(CSSPropertyWebkitFlexBasis, flex);
+        flex.uncheckedAppend(flexShorthand());
+        map.set(CSSPropertyFlexGrow, flex);
+        map.set(CSSPropertyFlexShrink, flex);
+        map.set(CSSPropertyFlexBasis, flex);
 
         Vector<StylePropertyShorthand, 1> flexFlow;
-        flexFlow.uncheckedAppend(webkitFlexFlowShorthand());
-        map.set(CSSPropertyWebkitFlexDirection, flexFlow);
-        map.set(CSSPropertyWebkitFlexWrap, flexFlow);
+        flexFlow.uncheckedAppend(flexFlowShorthand());
+        map.set(CSSPropertyFlexDirection, flexFlow);
+        map.set(CSSPropertyFlexWrap, flexFlow);
 
         Vector<StylePropertyShorthand, 2> grid;
         grid.uncheckedAppend(gridAreaShorthand());
         grid.uncheckedAppend(gridColumnShorthand());
-        map.set(CSSPropertyGridStart, grid);
-        map.set(CSSPropertyGridEnd, grid);
+        map.set(CSSPropertyGridColumnStart, grid);
+        map.set(CSSPropertyGridColumnEnd, grid);
 
         Vector<StylePropertyShorthand, 2> gridAfter;
         gridAfter.uncheckedAppend(gridAreaShorthand());
         gridAfter.uncheckedAppend(gridRowShorthand());
-        map.set(CSSPropertyGridBefore, gridAfter);
-        map.set(CSSPropertyGridAfter, gridAfter);
+        map.set(CSSPropertyGridRowStart, gridAfter);
+        map.set(CSSPropertyGridRowEnd, gridAfter);
 
         Vector<StylePropertyShorthand, 1> marginCollapse;
         marginCollapse.uncheckedAppend(webkitMarginCollapseShorthand());
diff --git a/Source/core/css/StylePropertyShorthand.h b/Source/core/css/StylePropertyShorthand.h
index 6992e89..d3f3b3f 100644
--- a/Source/core/css/StylePropertyShorthand.h
+++ b/Source/core/css/StylePropertyShorthand.h
@@ -96,8 +96,8 @@
 const StylePropertyShorthand& webkitBorderStartShorthand();
 const StylePropertyShorthand& webkitColumnsShorthand();
 const StylePropertyShorthand& webkitColumnRuleShorthand();
-const StylePropertyShorthand& webkitFlexFlowShorthand();
-const StylePropertyShorthand& webkitFlexShorthand();
+const StylePropertyShorthand& flexFlowShorthand();
+const StylePropertyShorthand& flexShorthand();
 const StylePropertyShorthand& gridColumnShorthand();
 const StylePropertyShorthand& gridRowShorthand();
 const StylePropertyShorthand& gridAreaShorthand();
diff --git a/Source/core/css/StyleRule.cpp b/Source/core/css/StyleRule.cpp
index e547872..3b16271 100644
--- a/Source/core/css/StyleRule.cpp
+++ b/Source/core/css/StyleRule.cpp
@@ -23,24 +23,20 @@
 #include "core/css/StyleRule.h"
 
 #include "RuntimeEnabledFeatures.h"
-#include "core/css/CSSCharsetRule.h"
 #include "core/css/CSSFilterRule.h"
 #include "core/css/CSSFontFaceRule.h"
 #include "core/css/CSSHostRule.h"
 #include "core/css/CSSImportRule.h"
-#include "core/css/CSSKeyframeRule.h"
 #include "core/css/CSSKeyframesRule.h"
 #include "core/css/CSSMediaRule.h"
 #include "core/css/CSSPageRule.h"
 #include "core/css/CSSRegionRule.h"
 #include "core/css/CSSStyleRule.h"
 #include "core/css/CSSSupportsRule.h"
-#include "core/css/CSSUnknownRule.h"
 #include "core/css/CSSViewportRule.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleRuleImport.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include "wtf/MemoryInstrumentationVector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/StyleRuleImport.cpp b/Source/core/css/StyleRuleImport.cpp
index 8f77583..d3808d3 100644
--- a/Source/core/css/StyleRuleImport.cpp
+++ b/Source/core/css/StyleRuleImport.cpp
@@ -22,7 +22,6 @@
 #include "config.h"
 #include "core/css/StyleRuleImport.h"
 
-#include <wtf/StdLibExtras.h>
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/Document.h"
 #include "core/loader/cache/CachedCSSStyleSheet.h"
diff --git a/Source/core/css/StyleSheetList.cpp b/Source/core/css/StyleSheetList.cpp
index 226206e..bd00038 100644
--- a/Source/core/css/StyleSheetList.cpp
+++ b/Source/core/css/StyleSheetList.cpp
@@ -74,9 +74,10 @@
     // ### Bad implementation because returns a single element (are IDs always unique?)
     // and doesn't look for name attribute.
     // But unicity of stylesheet ids is good practice anyway ;)
+    // FIXME: We should figure out if we should change this or fix the spec.
     Element* element = m_document->getElementById(name);
     if (element && element->hasTagName(styleTag))
-        return static_cast<HTMLStyleElement*>(element);
+        return toHTMLStyleElement(element);
     return 0;
 }
 
diff --git a/Source/core/css/html.css b/Source/core/css/html.css
index 5b97e32..057d693 100644
--- a/Source/core/css/html.css
+++ b/Source/core/css/html.css
@@ -447,8 +447,7 @@
     display: block;
     -webkit-flex: none;
     -webkit-user-modify: read-only !important;
-    -webkit-align-self: flex-start;
-    margin: auto 0;
+    -webkit-margin-start: 1px;
 }
 
 input[type="search"]::-webkit-search-decoration {
diff --git a/Source/core/css/resolver/ElementStyleResources.cpp b/Source/core/css/resolver/ElementStyleResources.cpp
new file mode 100644
index 0000000..6efe8e0
--- /dev/null
+++ b/Source/core/css/resolver/ElementStyleResources.cpp
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "config.h"
+#include "core/css/resolver/ElementStyleResources.h"
+
+#include "core/platform/graphics/filters/FilterOperation.h"
+
+namespace WebCore {
+
+ElementStyleResources::ElementStyleResources()
+    : m_hasPendingShaders(false)
+    , m_deviceScaleFactor(1)
+{
+}
+
+void ElementStyleResources::addPendingImageProperty(const CSSPropertyID& property, CSSValue* value)
+{
+    m_pendingImageProperties.set(property, value);
+}
+
+void ElementStyleResources::addPendingSVGDocument(FilterOperation* filterOperation, CSSSVGDocumentValue* cssSVGDocumentValue)
+{
+    m_pendingSVGDocuments.set(filterOperation, cssSVGDocumentValue);
+}
+
+void ElementStyleResources::clear()
+{
+    m_pendingImageProperties.clear();
+    m_pendingSVGDocuments.clear();
+    m_hasPendingShaders = false;
+    m_deviceScaleFactor = 1;
+}
+
+}
diff --git a/Source/core/css/resolver/ElementStyleResources.h b/Source/core/css/resolver/ElementStyleResources.h
new file mode 100644
index 0000000..94c1599
--- /dev/null
+++ b/Source/core/css/resolver/ElementStyleResources.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef ElementStyleResources_h
+#define ElementStyleResources_h
+
+#include "CSSPropertyNames.h"
+#include "core/css/CSSSVGDocumentValue.h"
+#include "core/css/CSSValue.h"
+#include "wtf/HashMap.h"
+
+namespace WebCore {
+
+class FilterOperation;
+
+typedef HashMap<FilterOperation*, RefPtr<CSSSVGDocumentValue> > PendingSVGDocumentMap;
+typedef HashMap<CSSPropertyID, RefPtr<CSSValue> > PendingImagePropertyMap;
+
+// Holds information about resources, requested by stylesheets.
+// Lifetime: per-element style resolve.
+// FIXME: At least for the moment, the lifetime actually matches that of StyleResolverState,
+// but all data is cleared for each element resolve. We must investigate performance
+// implications of matching effective and intended lifetime.
+class ElementStyleResources {
+WTF_MAKE_NONCOPYABLE(ElementStyleResources);
+public:
+    ElementStyleResources();
+
+    const PendingImagePropertyMap& pendingImageProperties() const { return m_pendingImageProperties; }
+    const PendingSVGDocumentMap& pendingSVGDocuments() const { return m_pendingSVGDocuments; }
+
+    void setHasPendingShaders(bool hasPendingShaders) { m_hasPendingShaders = hasPendingShaders; }
+    bool hasPendingShaders() const { return m_hasPendingShaders; }
+
+    float deviceScaleFactor() const { return m_deviceScaleFactor; }
+    void setDeviceScaleFactor(float deviceScaleFactor) { m_deviceScaleFactor = deviceScaleFactor; }
+
+    void addPendingImageProperty(const CSSPropertyID&, CSSValue*);
+    void addPendingSVGDocument(FilterOperation*, CSSSVGDocumentValue*);
+
+    void clear();
+
+private:
+    PendingImagePropertyMap m_pendingImageProperties;
+    PendingSVGDocumentMap m_pendingSVGDocuments;
+    bool m_hasPendingShaders;
+    float m_deviceScaleFactor;
+};
+
+} // namespace WebCore
+
+#endif // ElementStyleResources_h
diff --git a/Source/core/css/resolver/FilterOperationResolver.cpp b/Source/core/css/resolver/FilterOperationResolver.cpp
index d2c8e45..bde228b 100644
--- a/Source/core/css/resolver/FilterOperationResolver.cpp
+++ b/Source/core/css/resolver/FilterOperationResolver.cpp
@@ -99,7 +99,7 @@
 {
     StyleShader* shader = value->cachedOrPendingShader();
     if (shader && shader->isPendingShader())
-        state.setHasPendingShaders(true);
+        state.elementStyleResources().setHasPendingShaders(true);
     return shader;
 }
 
@@ -415,7 +415,7 @@
             RefPtr<ReferenceFilterOperation> operation = ReferenceFilterOperation::create(svgDocumentValue->url(), url.fragmentIdentifier(), operationType);
             if (SVGURIReference::isExternalURIReference(svgDocumentValue->url(), state.document())) {
                 if (!svgDocumentValue->loadRequested())
-                    state.pendingSVGDocuments().set(operation.get(), svgDocumentValue);
+                    state.elementStyleResources().addPendingSVGDocument(operation.get(), svgDocumentValue);
                 else if (svgDocumentValue->cachedSVGDocument())
                     operation->setCachedSVGDocumentReference(adoptPtr(new CachedSVGDocumentReference(svgDocumentValue->cachedSVGDocument())));
             }
@@ -497,7 +497,7 @@
             int blur = item->blur ? item->blur->computeLength<int>(style, rootStyle, zoomFactor) : 0;
             Color color;
             if (item->color)
-                color = state.colorFromPrimitiveValue(item->color.get());
+                color = state.resolveColorFromPrimitiveValue(item->color.get());
 
             operations.operations().append(DropShadowFilterOperation::create(location, blur, color.isValid() ? color : Color::transparent, operationType));
             break;
diff --git a/Source/core/css/resolver/FilterOperationResolver.h b/Source/core/css/resolver/FilterOperationResolver.h
index 3009735..cd4d817 100644
--- a/Source/core/css/resolver/FilterOperationResolver.h
+++ b/Source/core/css/resolver/FilterOperationResolver.h
@@ -22,8 +22,6 @@
 #ifndef FilterOperationResolver_h
 #define FilterOperationResolver_h
 
-#include "CSSPropertyNames.h"
-#include "core/css/CSSValueList.h"
 #include "core/css/resolver/StyleResolverState.h"
 #include "core/platform/graphics/filters/FilterOperations.h"
 
diff --git a/Source/core/css/resolver/ScopedStyleResolver.cpp b/Source/core/css/resolver/ScopedStyleResolver.cpp
index ef99e87..35a4110 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.cpp
+++ b/Source/core/css/resolver/ScopedStyleResolver.cpp
@@ -41,7 +41,6 @@
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLStyleElement.h"
 #include "wtf/MemoryInstrumentationHashMap.h"
-#include "wtf/MemoryInstrumentationHashSet.h"
 
 namespace WebCore {
 
@@ -84,23 +83,35 @@
     ASSERT(target);
     ASSERT(target->scopingNode());
 
+    const ContainerNode* scopingNode = target->scopingNode();
+
     // Since StyleResolver creates RuleSets according to styles' document
     // order, a parent of the given ScopedRuleData has been already
     // prepared.
-    const ContainerNode* e = target->scopingNode()->parentOrShadowHostNode();
-    for (; e; e = e->parentOrShadowHostNode()) {
-        if (ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(e)) {
+    for (const ContainerNode* node = scopingNode->parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode()) {
+        if (ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(node)) {
             target->setParent(scopedResolver);
             break;
         }
-        if (e->isDocumentNode()) {
+        if (node->isDocumentNode()) {
             bool dummy;
-            ScopedStyleResolver* scopedResolver = addScopedStyleResolver(e, dummy);
+            ScopedStyleResolver* scopedResolver = addScopedStyleResolver(node, dummy);
             target->setParent(scopedResolver);
             setupScopedStylesTree(scopedResolver);
             break;
         }
     }
+
+    if (m_buildInDocumentOrder)
+        return;
+
+    // Reparent all nodes whose scoping node is contained by target's one.
+    for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it) {
+        if (it->value == target)
+            continue;
+        if (it->value->parent() == target->parent() && scopingNode->containsIncludingShadowDOM(it->key))
+            it->value->setParent(target);
+    }
 }
 
 void ScopedStyleTree::clear()
@@ -163,6 +174,31 @@
         it->value->collectFeaturesTo(features);
 }
 
+inline void ScopedStyleTree::reparentNodes(const ScopedStyleResolver* oldParent, ScopedStyleResolver* newParent)
+{
+    // FIXME: this takes O(N) (N = number of all scoping nodes).
+    for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it) {
+        if (it->value->parent() == oldParent)
+            it->value->setParent(newParent);
+    }
+}
+
+void ScopedStyleTree::remove(const ContainerNode* scopingNode)
+{
+    if (!scopingNode || scopingNode->isDocumentNode())
+        return;
+
+    ScopedStyleResolver* resolverRemoved = scopedStyleResolverFor(scopingNode);
+    if (!resolverRemoved)
+        return;
+
+    reparentNodes(resolverRemoved, resolverRemoved->parent());
+    if (m_cache.scopedResolver == resolverRemoved)
+        m_cache.clear();
+
+    m_authorStyles.remove(scopingNode);
+}
+
 void ScopedStyleTree::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
 {
     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
@@ -177,10 +213,10 @@
     if (!document)
         return 0;
     Node* ownerNode = sheet->ownerNode();
-    if (!ownerNode || !ownerNode->isHTMLElement() || !ownerNode->hasTagName(HTMLNames::styleTag))
+    if (!ownerNode || !ownerNode->hasTagName(HTMLNames::styleTag))
         return 0;
 
-    HTMLStyleElement* styleElement = static_cast<HTMLStyleElement*>(ownerNode);
+    HTMLStyleElement* styleElement = toHTMLStyleElement(ownerNode);
     if (!styleElement->scoped())
         return styleElement->isInShadowTree() ? styleElement->containingShadowRoot() : 0;
 
@@ -242,8 +278,11 @@
 void ScopedStyleResolver::resetAuthorStyle()
 {
     m_authorStyle = RuleSet::create();
-    m_authorStyle->disableAutoShrinkToFit();
-    m_atHostRules.clear();
+}
+
+void ScopedStyleResolver::resetAtHostRules(const ShadowRoot* shadowRoot)
+{
+    m_atHostRules.remove(shadowRoot);
 }
 
 bool ScopedStyleResolver::checkRegionStyle(Element* regionElement)
diff --git a/Source/core/css/resolver/ScopedStyleResolver.h b/Source/core/css/resolver/ScopedStyleResolver.h
index 3c2582f..0ed95d7 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.h
+++ b/Source/core/css/resolver/ScopedStyleResolver.h
@@ -27,27 +27,8 @@
 #ifndef ScopedStyleResolver_h
 #define ScopedStyleResolver_h
 
-#include "core/css/CSSKeyframeRule.h"
-#include "core/css/CSSKeyframesRule.h"
-#include "core/css/CSSRuleList.h"
-#include "core/css/CSSSVGDocumentValue.h"
-#include "core/css/CSSToStyleMap.h"
-#include "core/css/CSSValueList.h"
-#include "core/css/DocumentRuleSets.h"
-#include "core/css/InspectorCSSOMWrappers.h"
-#include "core/css/MediaQueryExp.h"
-#include "core/css/RuleFeature.h"
 #include "core/css/RuleSet.h"
-#include "core/css/SelectorChecker.h"
-#include "core/css/SelectorFilter.h"
 #include "core/css/SiblingTraversalStrategies.h"
-#include "core/css/resolver/ViewportStyleResolver.h"
-#include "core/platform/LinkHash.h"
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
-#include "core/rendering/style/RenderStyle.h"
-#include "core/rendering/style/StyleInheritedData.h"
-#include "wtf/Assertions.h"
 #include "wtf/Forward.h"
 #include "wtf/HashMap.h"
 #include "wtf/OwnPtr.h"
@@ -71,13 +52,14 @@
 
     static const ContainerNode* scopingNodeFor(const CSSStyleSheet*);
 
-    // methods for building tree.
     const ContainerNode* scopingNode() const { return m_scopingNode; }
     const TreeScope* treeScope() const { return m_scopingNode->treeScope(); }
     void prepareEmptyRuleSet() { m_authorStyle = RuleSet::create(); }
     void setParent(ScopedStyleResolver* newParent) { m_parent = newParent; }
     ScopedStyleResolver* parent() { return m_parent; }
 
+    bool hasOnlyEmptyRuleSets() const { return !m_authorStyle->ruleCount() && m_atHostRules.isEmpty(); }
+
 public:
     bool checkRegionStyle(Element*);
 
@@ -85,10 +67,11 @@
     void matchAuthorRules(ElementRuleCollector&, bool includeEmptyRules, bool applyAuthorStyles);
     void matchPageRules(PageRuleCollector&);
     void addRulesFromSheet(StyleSheetContents*, const MediaQueryEvaluator&, StyleResolver*);
-    void postAddRulesFromSheet() { m_authorStyle->shrinkToFit(); }
     void addHostRule(StyleRuleHost*, bool hasDocumentSecurityOrigin, const ContainerNode* scopingNode);
     void collectFeaturesTo(RuleFeatureSet&);
     void resetAuthorStyle();
+    void resetAtHostRules(const ShadowRoot*);
+
     void reportMemoryUsage(MemoryObjectInfo*) const;
 
 private:
@@ -108,7 +91,7 @@
 class ScopedStyleTree {
     WTF_MAKE_NONCOPYABLE(ScopedStyleTree); WTF_MAKE_FAST_ALLOCATED;
 public:
-    ScopedStyleTree() : m_scopedResolverForDocument(0) { }
+    ScopedStyleTree() : m_scopedResolverForDocument(0), m_buildInDocumentOrder(true) { }
 
     ScopedStyleResolver* ensureScopedStyleResolver(const ContainerNode* scopingNode);
     ScopedStyleResolver* scopedStyleResolverFor(const ContainerNode* scopingNode);
@@ -122,10 +105,14 @@
     void resolveScopedStyles(const Element*, Vector<ScopedStyleResolver*, 8>&);
     ScopedStyleResolver* scopedResolverFor(const Element*);
 
+    void remove(const ContainerNode* scopingNode);
+
     void pushStyleCache(const ContainerNode* scopingNode, const ContainerNode* parent);
     void popStyleCache(const ContainerNode* scopingNode);
 
     void collectFeaturesTo(RuleFeatureSet& features);
+    void setBuildInDocumentOrder(bool enabled) { m_buildInDocumentOrder = enabled; }
+    bool buildInDocumentOrder() const { return m_buildInDocumentOrder; }
 
     void reportMemoryUsage(MemoryObjectInfo*) const;
 private:
@@ -135,9 +122,12 @@
     void resolveStyleCache(const ContainerNode* scopingNode);
     ScopedStyleResolver* enclosingScopedStyleResolverFor(const ContainerNode* scopingNode);
 
+    void reparentNodes(const ScopedStyleResolver* oldParent, ScopedStyleResolver* newParent);
+
 private:
     HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> > m_authorStyles;
     ScopedStyleResolver* m_scopedResolverForDocument;
+    bool m_buildInDocumentOrder;
 
     struct ScopedStyleCache {
         ScopedStyleResolver* scopedResolver;
diff --git a/Source/core/css/resolver/StyleResolver.cpp b/Source/core/css/resolver/StyleResolver.cpp
index 87e23ed..d06cf9b 100644
--- a/Source/core/css/resolver/StyleResolver.cpp
+++ b/Source/core/css/resolver/StyleResolver.cpp
@@ -30,36 +30,27 @@
 #include "core/css/resolver/StyleResolver.h"
 
 #include "CSSPropertyNames.h"
-#include "FontFamilyNames.h"
 #include "HTMLNames.h"
-#include "MathMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
-#include "UserAgentStyleSheets.h"
 #include "XMLNames.h"
 #include "core/animation/AnimatableValue.h"
 #include "core/animation/Animation.h"
-#include "core/css/CSSBorderImage.h"
 #include "core/css/CSSCalculationValue.h"
 #include "core/css/CSSCursorImageValue.h"
 #include "core/css/CSSDefaultStyleSheets.h"
-#include "core/css/CSSFontFaceRule.h"
 #include "core/css/CSSFontSelector.h"
 #include "core/css/CSSImageSetValue.h"
 #include "core/css/CSSKeyframeRule.h"
 #include "core/css/CSSKeyframesRule.h"
 #include "core/css/CSSLineBoxContainValue.h"
-#include "core/css/CSSPageRule.h"
 #include "core/css/CSSParser.h"
 #include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/css/CSSReflectValue.h"
 #include "core/css/CSSSVGDocumentValue.h"
 #include "core/css/CSSSelector.h"
 #include "core/css/CSSSelectorList.h"
-#include "core/css/CSSShaderValue.h"
 #include "core/css/CSSStyleRule.h"
-#include "core/css/CSSSupportsRule.h"
-#include "core/css/CSSTimingFunctionValue.h"
 #include "core/css/CSSValueList.h"
 #include "core/css/CSSVariableValue.h"
 #include "core/css/Counter.h"
@@ -68,66 +59,39 @@
 #include "core/css/FontFeatureValue.h"
 #include "core/css/FontSize.h"
 #include "core/css/FontValue.h"
-#include "core/css/MediaList.h"
 #include "core/css/MediaQueryEvaluator.h"
 #include "core/css/PageRuleCollector.h"
 #include "core/css/Pair.h"
-#include "core/css/Rect.h"
 #include "core/css/RuleSet.h"
-#include "core/css/SelectorCheckerFastPath.h"
 #include "core/css/ShadowValue.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StylePropertyShorthand.h"
-#include "core/css/StyleRule.h"
-#include "core/css/StyleRuleImport.h"
 #include "core/css/StyleSheetContents.h"
-#include "core/css/StyleSheetList.h"
+#include "core/css/resolver/ElementStyleResources.h"
 #include "core/css/resolver/FilterOperationResolver.h"
 #include "core/css/resolver/StyleBuilder.h"
 #include "core/css/resolver/TransformBuilder.h"
 #include "core/css/resolver/ViewportStyleResolver.h"
-#include "core/dom/Attribute.h"
-#include "core/dom/ContextFeatures.h"
 #include "core/dom/DocumentStyleSheetCollection.h"
 #include "core/dom/FullscreenController.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeRenderingContext.h"
 #include "core/dom/Text.h"
-#include "core/dom/VisitedLinkState.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/InsertionPoint.h"
 #include "core/dom/shadow/ShadowRoot.h"
-#include "core/editing/FrameSelection.h"
-#include "core/html/HTMLDocument.h"
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/HTMLOptionElement.h"
-#include "core/html/HTMLProgressElement.h"
-#include "core/html/HTMLStyleElement.h"
-#include "core/html/HTMLTextAreaElement.h"
 #include "core/html/track/WebVTTElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/cache/CachedDocument.h"
-#include "core/loader/cache/CachedImage.h"
 #include "core/loader/cache/CachedSVGDocumentReference.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/platform/CalculationValue.h"
 #include "core/platform/LinkHash.h"
-#include "core/platform/graphics/filters/custom/CustomFilterArrayParameter.h"
 #include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
-#include "core/platform/graphics/filters/custom/CustomFilterNumberParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "core/platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
-#include "core/platform/graphics/filters/custom/CustomFilterTransformParameter.h"
 #include "core/platform/text/LocaleToScriptMapping.h"
-#include "core/rendering/RenderRegion.h"
-#include "core/rendering/RenderScrollbar.h"
-#include "core/rendering/RenderScrollbarTheme.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/style/ContentData.h"
@@ -139,21 +103,15 @@
 #include "core/rendering/style/ShadowData.h"
 #include "core/rendering/style/StyleCachedImage.h"
 #include "core/rendering/style/StyleCachedImageSet.h"
-#include "core/rendering/style/StyleCachedShader.h"
-#include "core/rendering/style/StyleCustomFilterProgram.h"
 #include "core/rendering/style/StyleCustomFilterProgramCache.h"
 #include "core/rendering/style/StyleGeneratedImage.h"
 #include "core/rendering/style/StylePendingImage.h"
 #include "core/rendering/style/StylePendingShader.h"
 #include "core/rendering/style/StyleShader.h"
-#include "core/svg/SVGDocument.h"
 #include "core/svg/SVGDocumentExtensions.h"
 #include "core/svg/SVGElement.h"
 #include "core/svg/SVGFontFaceElement.h"
-#include "core/svg/SVGURIReference.h"
-#include "weborigin/SecurityOrigin.h"
 #include "wtf/MemoryInstrumentationHashMap.h"
-#include "wtf/MemoryInstrumentationHashSet.h"
 #include "wtf/MemoryInstrumentationVector.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/Vector.h"
@@ -223,6 +181,7 @@
     , m_viewportStyleResolver(ViewportStyleResolver::create(document))
     , m_styleBuilder(DeprecatedStyleBuilder::sharedStyleBuilder())
     , m_styleMap(this)
+    , m_styleResourceLoader(document->cachedResourceLoader())
 {
     Element* root = document->documentElement();
 
@@ -260,6 +219,7 @@
     }
 #endif
 
+    // FIXME: Stylesheet candidate nodes are sorted in document order, but scoping nodes are not sorted.
     appendAuthorStyleSheets(0, styleSheetCollection->activeAuthorStyleSheets());
 }
 
@@ -267,7 +227,6 @@
 {
     // This handles sheets added to the end of the stylesheet list only. In other cases the style resolver
     // needs to be reconstructed. To handle insertions too the rule order numbers would need to be updated.
-    ScopedStyleResolver* lastUpdatedResolver = 0;
     unsigned size = styleSheets.size();
     for (unsigned i = firstNew; i < size; ++i) {
         CSSStyleSheet* cssSheet = styleSheets[i].get();
@@ -280,14 +239,8 @@
         ASSERT(resolver);
         resolver->addRulesFromSheet(sheet, *m_medium, this);
         m_inspectorCSSOMWrappers.collectFromStyleSheetIfNeeded(cssSheet);
-
-        if (lastUpdatedResolver && lastUpdatedResolver != resolver)
-            lastUpdatedResolver->postAddRulesFromSheet();
-        lastUpdatedResolver = resolver;
     }
 
-    if (lastUpdatedResolver)
-        lastUpdatedResolver->postAddRulesFromSheet();
     collectFeatures();
 
     if (document()->renderer() && document()->renderer()->style())
@@ -302,6 +255,41 @@
     m_styleTree.clear();
 }
 
+void StyleResolver::resetAuthorStyle(const ContainerNode* scopingNode)
+{
+    m_styleTree.clear();
+    ScopedStyleResolver* resolver = scopingNode ? m_styleTree.scopedStyleResolverFor(scopingNode) : m_styleTree.scopedStyleResolverForDocument();
+    if (!resolver)
+        return;
+
+    m_ruleSets.shadowDistributedRules().reset(scopingNode);
+
+    resolver->resetAuthorStyle();
+
+    if (!scopingNode || !resolver->hasOnlyEmptyRuleSets())
+        return;
+
+    m_styleTree.remove(scopingNode);
+}
+
+void StyleResolver::resetAtHostRules(const ContainerNode* scopingNode)
+{
+    ASSERT(scopingNode);
+    ASSERT(scopingNode->isShadowRoot());
+
+    const ShadowRoot* shadowRoot = toShadowRoot(scopingNode);
+    const ContainerNode* shadowHost = shadowRoot->shadowHost();
+    ScopedStyleResolver* resolver = m_styleTree.scopedStyleResolverFor(shadowHost);
+    if (!resolver)
+        return;
+
+    resolver->resetAtHostRules(shadowRoot);
+    if (!resolver->hasOnlyEmptyRuleSets())
+        return;
+
+    m_styleTree.remove(shadowHost);
+}
+
 static PassOwnPtr<RuleSet> makeRuleSet(const Vector<RuleFeature>& rules)
 {
     size_t size = rules.size();
@@ -310,7 +298,6 @@
     OwnPtr<RuleSet> ruleSet = RuleSet::create();
     for (size_t i = 0; i < size; ++i)
         ruleSet->addRule(rules[i].rule, rules[i].selectorIndex, rules[i].hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState);
-    ruleSet->shrinkToFit();
     return ruleSet.release();
 }
 
@@ -561,17 +548,6 @@
         collector.matchedResult().isCacheable = false;
 }
 
-inline void StyleResolver::initElement(Element* e)
-{
-    if (m_state.element() != e) {
-        m_state.initElement(e);
-        if (e && e == e->document()->documentElement()) {
-            e->document()->setDirectionSetOnDocumentElement(false);
-            e->document()->setWritingModeSetOnDocumentElement(false);
-        }
-    }
-}
-
 static const unsigned cStyleSearchThreshold = 10;
 static const unsigned cStyleSearchLevelThreshold = 10;
 
@@ -590,18 +566,17 @@
         return 0;
     if (parent->hasScopedHTMLStyleChild())
         return 0;
-    StyledElement* p = static_cast<StyledElement*>(parent);
-    if (p->inlineStyle())
+    if (parent->inlineStyle())
         return 0;
-    if (p->isSVGElement() && toSVGElement(p)->animatedSMILStyleProperties())
+    if (parent->isSVGElement() && toSVGElement(parent)->animatedSMILStyleProperties())
         return 0;
-    if (p->hasID() && m_features.idsInRules.contains(p->idForStyleResolution().impl()))
+    if (parent->hasID() && m_features.idsInRules.contains(parent->idForStyleResolution().impl()))
         return 0;
 
-    RenderStyle* parentStyle = p->renderStyle();
+    RenderStyle* parentStyle = parent->renderStyle();
     unsigned subcount = 0;
-    Node* thisCousin = p;
-    Node* currentNode = p->previousSibling();
+    Node* thisCousin = parent;
+    Node* currentNode = parent->previousSibling();
 
     // Reserve the tries for this level. This effectively makes sure that the algorithm
     // will never go deeper than cStyleSearchLevelThreshold levels into recursion.
@@ -637,7 +612,7 @@
     return collector.hasAnyMatchingRules(ruleSet);
 }
 
-bool StyleResolver::canShareStyleWithControl(StyledElement* element) const
+bool StyleResolver::canShareStyleWithControl(Element* element) const
 {
     const StyleResolverState& state = m_state;
 
@@ -693,7 +668,7 @@
     return element->isHTMLElement() && toHTMLElement(element)->hasDirectionAuto();
 }
 
-bool StyleResolver::sharingCandidateHasIdenticalStyleAffectingAttributes(StyledElement* sharingCandidate) const
+bool StyleResolver::sharingCandidateHasIdenticalStyleAffectingAttributes(Element* sharingCandidate) const
 {
     const StyleResolverState& state = m_state;
     if (state.element()->elementData() == sharingCandidate->elementData())
@@ -729,7 +704,7 @@
     return true;
 }
 
-bool StyleResolver::canShareStyleWithElement(StyledElement* element) const
+bool StyleResolver::canShareStyleWithElement(Element* element) const
 {
     RenderStyle* style = element->renderStyle();
     const StyleResolverState& state = m_state;
@@ -816,17 +791,17 @@
     return true;
 }
 
-inline StyledElement* StyleResolver::findSiblingForStyleSharing(Node* node, unsigned& count) const
+inline Element* StyleResolver::findSiblingForStyleSharing(Node* node, unsigned& count) const
 {
     for (; node; node = node->previousSibling()) {
         if (!node->isStyledElement())
             continue;
-        if (canShareStyleWithElement(static_cast<StyledElement*>(node)))
+        if (canShareStyleWithElement(toElement(node)))
             break;
         if (count++ == cStyleSearchThreshold)
             return 0;
     }
-    return static_cast<StyledElement*>(node);
+    return toElement(node);
 }
 
 RenderStyle* StyleResolver::locateSharedStyle()
@@ -866,7 +841,7 @@
     // Check previous siblings and their cousins.
     unsigned count = 0;
     unsigned visitedNodeCount = 0;
-    StyledElement* shareElement = 0;
+    Element* shareElement = 0;
     Node* cousinList = state.styledElement()->previousSibling();
     while (cousinList) {
         shareElement = findSiblingForStyleSharing(cousinList, count);
@@ -1098,7 +1073,6 @@
     }
 
     StyleResolverState& state = m_state;
-    initElement(element);
     state.initForStyleResolve(document(), element, defaultParent, regionForStyling);
     if (sharingBehavior == AllowStyleSharing && !state.distributedToInsertionPoint()) {
         RenderStyle* sharedStyle = locateSharedStyle();
@@ -1199,7 +1173,7 @@
     updateFont();
 
     // Start loading resources referenced by this style.
-    loadPendingResources();
+    m_styleResourceLoader.loadPendingResources(m_state.style(), m_state.elementStyleResources());
 
     // Add all the animating properties to the keyframe.
     if (const StylePropertySet* styleDeclaration = keyframe->properties()) {
@@ -1238,7 +1212,6 @@
     const Vector<RefPtr<StyleKeyframe> >& keyframes = keyframesRule->keyframes();
     for (unsigned i = 0; i < keyframes.size(); ++i) {
         // Apply the declaration to the style. This is a simplified version of the logic in styleForElement
-        initElement(e);
         m_state.initForStyleResolve(document(), e);
 
         const StyleKeyframe* keyframe = keyframes[i].get();
@@ -1289,8 +1262,6 @@
 
     StyleResolverState& state = m_state;
 
-    initElement(e);
-
     state.initForStyleResolve(document(), e, parentStyle);
 
     if (m_state.parentStyle()) {
@@ -1325,7 +1296,7 @@
     adjustRenderStyle(state.style(), m_state.parentStyle(), 0);
 
     // Start loading resources referenced by this style.
-    loadPendingResources();
+    m_styleResourceLoader.loadPendingResources(m_state.style(), m_state.elementStyleResources());
 
     document()->didAccessStyleResolver();
 
@@ -1365,7 +1336,7 @@
     applyMatchedProperties<LowPriorityProperties>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
 
     // Start loading resources referenced by this style.
-    loadPendingResources();
+    m_styleResourceLoader.loadPendingResources(m_state.style(), m_state.elementStyleResources());
 
     document()->didAccessStyleResolver();
 
@@ -1713,14 +1684,14 @@
 void StyleResolver::adjustGridItemPosition(RenderStyle* style) const
 {
     // If opposing grid-placement properties both specify a grid span, they both compute to ‘auto’.
-    if (style->gridStart().isSpan() && style->gridEnd().isSpan()) {
-        style->setGridStart(GridPosition());
-        style->setGridEnd(GridPosition());
+    if (style->gridColumnStart().isSpan() && style->gridColumnEnd().isSpan()) {
+        style->setGridColumnStart(GridPosition());
+        style->setGridColumnEnd(GridPosition());
     }
 
-    if (style->gridBefore().isSpan() && style->gridAfter().isSpan()) {
-        style->setGridBefore(GridPosition());
-        style->setGridAfter(GridPosition());
+    if (style->gridRowStart().isSpan() && style->gridRowEnd().isSpan()) {
+        style->setGridRowStart(GridPosition());
+        style->setGridRowEnd(GridPosition());
     }
 }
 
@@ -1784,7 +1755,6 @@
     if (!e || !e->document()->haveStylesheetsLoaded())
         return 0;
 
-    initElement(e);
     m_state.initForStyleResolve(document(), e, 0);
 
     ElementRuleCollector collector(this, m_state);
@@ -2189,12 +2159,14 @@
     applyMatchedProperties<LowPriorityProperties>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
 
     // Start loading resources referenced by this style.
-    loadPendingResources();
+    m_styleResourceLoader.loadPendingResources(m_state.style(), m_state.elementStyleResources());
 
     ASSERT(!state.fontDirty());
 
     if (cacheItem || !cacheHash)
         return;
+    if (!state.isMatchedPropertiesCacheable())
+        return;
     if (!isCacheableInMatchedPropertiesCache(state.element(), state.style(), state.parentStyle()))
         return;
     addToMatchedPropertiesCache(state.style(), state.parentStyle(), cacheHash, matchResult);
@@ -2202,7 +2174,6 @@
 
 void StyleResolver::applyPropertyToStyle(CSSPropertyID id, CSSValue* value, RenderStyle* style)
 {
-    initElement(0);
     m_state.initForStyleResolve(document(), 0, style);
     m_state.setStyle(style);
     applyPropertyToCurrentStyle(id, value);
@@ -2214,27 +2185,19 @@
         applyProperty(id, value);
 }
 
-// SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
-// of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
-// multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
-// Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
-// need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
-// width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
-// if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
-// properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
 bool StyleResolver::useSVGZoomRules()
 {
-    return m_state.element() && m_state.element()->isSVGElement();
+    return m_state.useSVGZoomRules();
 }
 
 static bool createGridTrackBreadth(CSSPrimitiveValue* primitiveValue, const StyleResolverState& state, GridLength& workingLength)
 {
-    if (primitiveValue->getValueID() == CSSValueWebkitMinContent) {
+    if (primitiveValue->getValueID() == CSSValueMinContent) {
         workingLength = Length(MinContent);
         return true;
     }
 
-    if (primitiveValue->getValueID() == CSSValueWebkitMaxContent) {
+    if (primitiveValue->getValueID() == CSSValueMaxContent) {
         workingLength = Length(MaxContent);
         return true;
     }
@@ -2311,9 +2274,9 @@
         trackSizes.append(trackSize);
     }
 
-    if (trackSizes.isEmpty())
-        return false;
-
+    // The parser should have rejected any <track-list> without any <track-size> as
+    // this is not conformant to the syntax.
+    ASSERT(!trackSizes.isEmpty());
     return true;
 }
 
@@ -2491,7 +2454,7 @@
                 CSSValue* item = i.value();
                 if (item->isImageGeneratorValue()) {
                     if (item->isGradientValue())
-                        state.style()->setContent(StyleGeneratedImage::create(static_cast<CSSGradientValue*>(item)->gradientWithStylesResolved(this).get()), didSet);
+                        state.style()->setContent(StyleGeneratedImage::create(static_cast<CSSGradientValue*>(item)->gradientWithStylesResolved(m_state).get()), didSet);
                     else
                         state.style()->setContent(StyleGeneratedImage::create(static_cast<CSSImageGeneratorValue*>(item)), didSet);
                     didSet = true;
@@ -2624,7 +2587,7 @@
                 fontDescription.setUsePrinterFont(document()->printing());
 
                 // Handle the zoom factor.
-                fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(document(), state.style(), fontDescription.isAbsoluteSize(), fontDescription.specifiedSize(), useSVGZoomRules()));
+                fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(document(), state.style(), fontDescription.isAbsoluteSize(), fontDescription.specifiedSize(), m_state.useSVGZoomRules()));
                 setFontDescription(fontDescription);
             }
         } else if (value->isFontValue()) {
@@ -2676,8 +2639,8 @@
     case CSSPropertyWebkitBorderRadius:
     case CSSPropertyWebkitColumns:
     case CSSPropertyWebkitColumnRule:
-    case CSSPropertyWebkitFlex:
-    case CSSPropertyWebkitFlexFlow:
+    case CSSPropertyFlex:
+    case CSSPropertyFlexFlow:
     case CSSPropertyGridColumn:
     case CSSPropertyGridRow:
     case CSSPropertyGridArea:
@@ -2721,7 +2684,7 @@
             ShadowStyle shadowStyle = item->style && item->style->getValueID() == CSSValueInset ? Inset : Normal;
             Color color;
             if (item->color)
-                color = m_state.colorFromPrimitiveValue(item->color.get());
+                color = m_state.resolveColorFromPrimitiveValue(item->color.get());
             else if (state.style())
                 color = state.style()->color();
 
@@ -2838,7 +2801,7 @@
         if (!primitiveValue)
             break;
 
-        Color col = m_state.colorFromPrimitiveValue(primitiveValue);
+        Color col = m_state.resolveColorFromPrimitiveValue(primitiveValue);
         state.style()->setTapHighlightColor(col);
         return;
     }
@@ -2964,7 +2927,7 @@
     case CSSPropertyWebkitFilter: {
         HANDLE_INHERIT_AND_INITIAL(filter, Filter);
         FilterOperations operations;
-        if (FilterOperationResolver::createFilterOperations(value, state.style(), state.rootElementStyle(), operations, m_customFilterProgramCache.get(), m_state))
+        if (FilterOperationResolver::createFilterOperations(value, state.style(), state.rootElementStyle(), operations, m_styleResourceLoader.customFilterProgramCache(), m_state))
             state.style()->setFilter(operations);
         return;
     }
@@ -2984,14 +2947,14 @@
         state.style()->setGridAutoRows(trackSize);
         return;
     }
-    case CSSPropertyGridColumns: {
+    case CSSPropertyGridDefinitionColumns: {
         if (isInherit) {
-            m_state.style()->setGridColumns(m_state.parentStyle()->gridColumns());
+            m_state.style()->setGridDefinitionColumns(m_state.parentStyle()->gridDefinitionColumns());
             m_state.style()->setNamedGridColumnLines(m_state.parentStyle()->namedGridColumnLines());
             return;
         }
         if (isInitial) {
-            m_state.style()->setGridColumns(RenderStyle::initialGridColumns());
+            m_state.style()->setGridDefinitionColumns(RenderStyle::initialGridDefinitionColumns());
             m_state.style()->setNamedGridColumnLines(RenderStyle::initialNamedGridColumnLines());
             return;
         }
@@ -3000,18 +2963,18 @@
         NamedGridLinesMap namedGridLines;
         if (!createGridTrackList(value, trackSizes, namedGridLines, state))
             return;
-        state.style()->setGridColumns(trackSizes);
+        state.style()->setGridDefinitionColumns(trackSizes);
         state.style()->setNamedGridColumnLines(namedGridLines);
         return;
     }
-    case CSSPropertyGridRows: {
+    case CSSPropertyGridDefinitionRows: {
         if (isInherit) {
-            m_state.style()->setGridRows(m_state.parentStyle()->gridRows());
+            m_state.style()->setGridDefinitionRows(m_state.parentStyle()->gridDefinitionRows());
             m_state.style()->setNamedGridRowLines(m_state.parentStyle()->namedGridRowLines());
             return;
         }
         if (isInitial) {
-            m_state.style()->setGridRows(RenderStyle::initialGridRows());
+            m_state.style()->setGridDefinitionRows(RenderStyle::initialGridDefinitionRows());
             m_state.style()->setNamedGridRowLines(RenderStyle::initialNamedGridRowLines());
             return;
         }
@@ -3020,42 +2983,42 @@
         NamedGridLinesMap namedGridLines;
         if (!createGridTrackList(value, trackSizes, namedGridLines, state))
             return;
-        state.style()->setGridRows(trackSizes);
+        state.style()->setGridDefinitionRows(trackSizes);
         state.style()->setNamedGridRowLines(namedGridLines);
         return;
     }
 
-    case CSSPropertyGridStart: {
-        HANDLE_INHERIT_AND_INITIAL(gridStart, GridStart);
+    case CSSPropertyGridColumnStart: {
+        HANDLE_INHERIT_AND_INITIAL(gridColumnStart, GridColumnStart);
         GridPosition startPosition;
         if (!createGridPosition(value, startPosition))
             return;
-        state.style()->setGridStart(startPosition);
+        state.style()->setGridColumnStart(startPosition);
         return;
     }
-    case CSSPropertyGridEnd: {
-        HANDLE_INHERIT_AND_INITIAL(gridEnd, GridEnd);
+    case CSSPropertyGridColumnEnd: {
+        HANDLE_INHERIT_AND_INITIAL(gridColumnEnd, GridColumnEnd);
         GridPosition endPosition;
         if (!createGridPosition(value, endPosition))
             return;
-        state.style()->setGridEnd(endPosition);
+        state.style()->setGridColumnEnd(endPosition);
         return;
     }
 
-    case CSSPropertyGridBefore: {
-        HANDLE_INHERIT_AND_INITIAL(gridBefore, GridBefore);
+    case CSSPropertyGridRowStart: {
+        HANDLE_INHERIT_AND_INITIAL(gridRowStart, GridRowStart);
         GridPosition beforePosition;
         if (!createGridPosition(value, beforePosition))
             return;
-        state.style()->setGridBefore(beforePosition);
+        state.style()->setGridRowStart(beforePosition);
         return;
     }
-    case CSSPropertyGridAfter: {
-        HANDLE_INHERIT_AND_INITIAL(gridAfter, GridAfter);
+    case CSSPropertyGridRowEnd: {
+        HANDLE_INHERIT_AND_INITIAL(gridRowEnd, GridRowEnd);
         GridPosition afterPosition;
         if (!createGridPosition(value, afterPosition))
             return;
-        state.style()->setGridAfter(afterPosition);
+        state.style()->setGridRowEnd(afterPosition);
         return;
     }
 
@@ -3212,16 +3175,16 @@
     case CSSPropertyWebkitColumnRuleWidth:
     case CSSPropertyWebkitColumnSpan:
     case CSSPropertyWebkitColumnWidth:
-    case CSSPropertyWebkitAlignContent:
-    case CSSPropertyWebkitAlignItems:
-    case CSSPropertyWebkitAlignSelf:
-    case CSSPropertyWebkitFlexBasis:
-    case CSSPropertyWebkitFlexDirection:
-    case CSSPropertyWebkitFlexGrow:
-    case CSSPropertyWebkitFlexShrink:
-    case CSSPropertyWebkitFlexWrap:
-    case CSSPropertyWebkitJustifyContent:
-    case CSSPropertyWebkitOrder:
+    case CSSPropertyAlignContent:
+    case CSSPropertyAlignItems:
+    case CSSPropertyAlignSelf:
+    case CSSPropertyFlexBasis:
+    case CSSPropertyFlexDirection:
+    case CSSPropertyFlexGrow:
+    case CSSPropertyFlexShrink:
+    case CSSPropertyFlexWrap:
+    case CSSPropertyJustifyContent:
+    case CSSPropertyOrder:
     case CSSPropertyWebkitFlowFrom:
     case CSSPropertyWebkitFlowInto:
     case CSSPropertyWebkitFontKerning:
@@ -3325,7 +3288,7 @@
 
     if (value->isImageGeneratorValue()) {
         if (value->isGradientValue())
-            return generatedOrPendingFromValue(property, static_cast<CSSGradientValue*>(value)->gradientWithStylesResolved(this).get());
+            return generatedOrPendingFromValue(property, static_cast<CSSGradientValue*>(value)->gradientWithStylesResolved(m_state).get());
         return generatedOrPendingFromValue(property, static_cast<CSSImageGeneratorValue*>(value));
     }
 
@@ -3342,14 +3305,14 @@
 {
     RefPtr<StyleImage> image = value->cachedOrPendingImage();
     if (image && image->isPendingImage())
-        m_state.pendingImageProperties().set(property, value);
+        m_state.elementStyleResources().addPendingImageProperty(property, value);
     return image.release();
 }
 
 PassRefPtr<StyleImage> StyleResolver::generatedOrPendingFromValue(CSSPropertyID property, CSSImageGeneratorValue* value)
 {
     if (value->isPending()) {
-        m_state.pendingImageProperties().set(property, value);
+        m_state.elementStyleResources().addPendingImageProperty(property, value);
         return StylePendingImage::create(value);
     }
     return StyleGeneratedImage::create(value);
@@ -3357,17 +3320,17 @@
 
 PassRefPtr<StyleImage> StyleResolver::setOrPendingFromValue(CSSPropertyID property, CSSImageSetValue* value)
 {
-    RefPtr<StyleImage> image = value->cachedOrPendingImageSet(document());
+    RefPtr<StyleImage> image = value->cachedOrPendingImageSet(m_state.elementStyleResources().deviceScaleFactor());
     if (image && image->isPendingImage())
-        m_state.pendingImageProperties().set(property, value);
+        m_state.elementStyleResources().addPendingImageProperty(property, value);
     return image.release();
 }
 
 PassRefPtr<StyleImage> StyleResolver::cursorOrPendingFromValue(CSSPropertyID property, CSSCursorImageValue* value)
 {
-    RefPtr<StyleImage> image = value->cachedOrPendingImage(document());
+    RefPtr<StyleImage> image = value->cachedOrPendingImage(m_state.elementStyleResources().deviceScaleFactor());
     if (image && image->isPendingImage())
-        m_state.pendingImageProperties().set(property, value);
+        m_state.elementStyleResources().addPendingImageProperty(property, value);
     return image.release();
 }
 
@@ -3441,21 +3404,7 @@
 void StyleResolver::setFontSize(FontDescription& fontDescription, float size)
 {
     fontDescription.setSpecifiedSize(size);
-    fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(document(), m_state.style(), fontDescription.isAbsoluteSize(), size, useSVGZoomRules()));
-}
-
-bool StyleResolver::colorFromPrimitiveValueIsDerivedFromElement(CSSPrimitiveValue* value)
-{
-    int ident = value->getValueID();
-    switch (ident) {
-    case CSSValueWebkitText:
-    case CSSValueWebkitLink:
-    case CSSValueWebkitActivelink:
-    case CSSValueCurrentcolor:
-        return true;
-    default:
-        return false;
-    }
+    fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(document(), m_state.style(), fontDescription.isAbsoluteSize(), size, m_state.useSVGZoomRules()));
 }
 
 void StyleResolver::addViewportDependentMediaQueryResult(const MediaQueryExp* expr, bool result)
@@ -3473,203 +3422,6 @@
     return false;
 }
 
-void StyleResolver::loadPendingSVGDocuments()
-{
-    StyleResolverState& state = m_state;
-    if (!state.style()->hasFilter() || state.pendingSVGDocuments().isEmpty())
-        return;
-
-    CachedResourceLoader* cachedResourceLoader = state.document()->cachedResourceLoader();
-    Vector<RefPtr<FilterOperation> >& filterOperations = state.style()->mutableFilter().operations();
-    for (unsigned i = 0; i < filterOperations.size(); ++i) {
-        RefPtr<FilterOperation> filterOperation = filterOperations.at(i);
-        if (filterOperation->getOperationType() == FilterOperation::REFERENCE) {
-            ReferenceFilterOperation* referenceFilter = static_cast<ReferenceFilterOperation*>(filterOperation.get());
-
-            CSSSVGDocumentValue* value = state.pendingSVGDocuments().get(referenceFilter);
-            if (!value)
-                continue;
-            CachedDocument* cachedDocument = value->load(cachedResourceLoader);
-            if (!cachedDocument)
-                continue;
-
-            // Stash the CachedDocument on the reference filter.
-            referenceFilter->setCachedSVGDocumentReference(adoptPtr(new CachedSVGDocumentReference(cachedDocument)));
-        }
-    }
-    state.pendingSVGDocuments().clear();
-}
-
-void StyleResolver::loadPendingShaders()
-{
-    if (!m_state.style()->hasFilter() || !m_state.hasPendingShaders())
-        return;
-
-    CachedResourceLoader* cachedResourceLoader = m_state.document()->cachedResourceLoader();
-
-    Vector<RefPtr<FilterOperation> >& filterOperations = m_state.style()->mutableFilter().operations();
-    for (unsigned i = 0; i < filterOperations.size(); ++i) {
-        RefPtr<FilterOperation> filterOperation = filterOperations.at(i);
-        if (filterOperation->getOperationType() == FilterOperation::CUSTOM) {
-            CustomFilterOperation* customFilter = static_cast<CustomFilterOperation*>(filterOperation.get());
-            ASSERT(customFilter->program());
-            StyleCustomFilterProgram* program = static_cast<StyleCustomFilterProgram*>(customFilter->program());
-            // Note that the StylePendingShaders could be already resolved to StyleCachedShaders. That's because the rule was matched before.
-            // However, the StyleCustomFilterProgram that was initially created could have been removed from the cache in the meanwhile,
-            // meaning that we get a new StyleCustomFilterProgram here that is not yet in the cache, but already has loaded StyleShaders.
-            if (!program->hasPendingShaders() && program->inCache())
-                continue;
-            if (!m_customFilterProgramCache)
-                m_customFilterProgramCache = adoptPtr(new StyleCustomFilterProgramCache());
-            RefPtr<StyleCustomFilterProgram> styleProgram = m_customFilterProgramCache->lookup(program);
-            if (styleProgram.get())
-                customFilter->setProgram(styleProgram.release());
-            else {
-                if (program->vertexShader() && program->vertexShader()->isPendingShader()) {
-                    CSSShaderValue* shaderValue = static_cast<StylePendingShader*>(program->vertexShader())->cssShaderValue();
-                    program->setVertexShader(shaderValue->cachedShader(cachedResourceLoader));
-                }
-                if (program->fragmentShader() && program->fragmentShader()->isPendingShader()) {
-                    CSSShaderValue* shaderValue = static_cast<StylePendingShader*>(program->fragmentShader())->cssShaderValue();
-                    program->setFragmentShader(shaderValue->cachedShader(cachedResourceLoader));
-                }
-                m_customFilterProgramCache->add(program);
-            }
-        }
-    }
-    m_state.setHasPendingShaders(false);
-}
-
-PassRefPtr<StyleImage> StyleResolver::loadPendingImage(StylePendingImage* pendingImage)
-{
-    CachedResourceLoader* cachedResourceLoader = m_state.document()->cachedResourceLoader();
-
-    if (pendingImage->cssImageValue()) {
-        CSSImageValue* imageValue = pendingImage->cssImageValue();
-        return imageValue->cachedImage(cachedResourceLoader);
-    }
-
-    if (pendingImage->cssImageGeneratorValue()) {
-        CSSImageGeneratorValue* imageGeneratorValue = pendingImage->cssImageGeneratorValue();
-        imageGeneratorValue->loadSubimages(cachedResourceLoader);
-        return StyleGeneratedImage::create(imageGeneratorValue);
-    }
-
-    if (pendingImage->cssCursorImageValue()) {
-        CSSCursorImageValue* cursorImageValue = pendingImage->cssCursorImageValue();
-        return cursorImageValue->cachedImage(cachedResourceLoader);
-    }
-
-    if (pendingImage->cssImageSetValue()) {
-        CSSImageSetValue* imageSetValue = pendingImage->cssImageSetValue();
-        return imageSetValue->cachedImageSet(cachedResourceLoader);
-    }
-
-    return 0;
-}
-
-void StyleResolver::loadPendingImages()
-{
-    if (m_state.pendingImageProperties().isEmpty())
-        return;
-
-    PendingImagePropertyMap::const_iterator::Keys end = m_state.pendingImageProperties().end().keys();
-    for (PendingImagePropertyMap::const_iterator::Keys it = m_state.pendingImageProperties().begin().keys(); it != end; ++it) {
-        CSSPropertyID currentProperty = *it;
-
-        switch (currentProperty) {
-        case CSSPropertyBackgroundImage: {
-            for (FillLayer* backgroundLayer = m_state.style()->accessBackgroundLayers(); backgroundLayer; backgroundLayer = backgroundLayer->next()) {
-                if (backgroundLayer->image() && backgroundLayer->image()->isPendingImage())
-                    backgroundLayer->setImage(loadPendingImage(static_cast<StylePendingImage*>(backgroundLayer->image())));
-            }
-            break;
-        }
-        case CSSPropertyContent: {
-            for (ContentData* contentData = const_cast<ContentData*>(m_state.style()->contentData()); contentData; contentData = contentData->next()) {
-                if (contentData->isImage()) {
-                    StyleImage* image = static_cast<ImageContentData*>(contentData)->image();
-                    if (image->isPendingImage()) {
-                        RefPtr<StyleImage> loadedImage = loadPendingImage(static_cast<StylePendingImage*>(image));
-                        if (loadedImage)
-                            static_cast<ImageContentData*>(contentData)->setImage(loadedImage.release());
-                    }
-                }
-            }
-            break;
-        }
-        case CSSPropertyCursor: {
-            if (CursorList* cursorList = m_state.style()->cursors()) {
-                for (size_t i = 0; i < cursorList->size(); ++i) {
-                    CursorData& currentCursor = cursorList->at(i);
-                    if (StyleImage* image = currentCursor.image()) {
-                        if (image->isPendingImage())
-                            currentCursor.setImage(loadPendingImage(static_cast<StylePendingImage*>(image)));
-                    }
-                }
-            }
-            break;
-        }
-        case CSSPropertyListStyleImage: {
-            if (m_state.style()->listStyleImage() && m_state.style()->listStyleImage()->isPendingImage())
-                m_state.style()->setListStyleImage(loadPendingImage(static_cast<StylePendingImage*>(m_state.style()->listStyleImage())));
-            break;
-        }
-        case CSSPropertyBorderImageSource: {
-            if (m_state.style()->borderImageSource() && m_state.style()->borderImageSource()->isPendingImage())
-                m_state.style()->setBorderImageSource(loadPendingImage(static_cast<StylePendingImage*>(m_state.style()->borderImageSource())));
-            break;
-        }
-        case CSSPropertyWebkitBoxReflect: {
-            if (StyleReflection* reflection = m_state.style()->boxReflect()) {
-                const NinePieceImage& maskImage = reflection->mask();
-                if (maskImage.image() && maskImage.image()->isPendingImage()) {
-                    RefPtr<StyleImage> loadedImage = loadPendingImage(static_cast<StylePendingImage*>(maskImage.image()));
-                    reflection->setMask(NinePieceImage(loadedImage.release(), maskImage.imageSlices(), maskImage.fill(), maskImage.borderSlices(), maskImage.outset(), maskImage.horizontalRule(), maskImage.verticalRule()));
-                }
-            }
-            break;
-        }
-        case CSSPropertyWebkitMaskBoxImageSource: {
-            if (m_state.style()->maskBoxImageSource() && m_state.style()->maskBoxImageSource()->isPendingImage())
-                m_state.style()->setMaskBoxImageSource(loadPendingImage(static_cast<StylePendingImage*>(m_state.style()->maskBoxImageSource())));
-            break;
-        }
-        case CSSPropertyWebkitMaskImage: {
-            for (FillLayer* maskLayer = m_state.style()->accessMaskLayers(); maskLayer; maskLayer = maskLayer->next()) {
-                if (maskLayer->image() && maskLayer->image()->isPendingImage())
-                    maskLayer->setImage(loadPendingImage(static_cast<StylePendingImage*>(maskLayer->image())));
-            }
-            break;
-        }
-        case CSSPropertyWebkitShapeInside:
-            if (m_state.style()->shapeInside() && m_state.style()->shapeInside()->image() && m_state.style()->shapeInside()->image()->isPendingImage())
-                m_state.style()->shapeInside()->setImage(loadPendingImage(static_cast<StylePendingImage*>(m_state.style()->shapeInside()->image())));
-            break;
-        case CSSPropertyWebkitShapeOutside:
-            if (m_state.style()->shapeOutside() && m_state.style()->shapeOutside()->image() && m_state.style()->shapeOutside()->image()->isPendingImage())
-                m_state.style()->shapeOutside()->setImage(loadPendingImage(static_cast<StylePendingImage*>(m_state.style()->shapeOutside()->image())));
-            break;
-        default:
-            ASSERT_NOT_REACHED();
-        }
-    }
-
-    m_state.pendingImageProperties().clear();
-}
-
-void StyleResolver::loadPendingResources()
-{
-    // Start loading images referenced by this style.
-    loadPendingImages();
-
-    // Start loading the shaders referenced by this style.
-    loadPendingShaders();
-
-    // Start loading the SVG Documents referenced by this style.
-    loadPendingSVGDocuments();
-}
-
 inline StyleResolver::MatchedProperties::MatchedProperties()
     : possiblyPaddedMember(0)
 {
diff --git a/Source/core/css/resolver/StyleResolver.h b/Source/core/css/resolver/StyleResolver.h
index a8013e7..ff1a28b 100644
--- a/Source/core/css/resolver/StyleResolver.h
+++ b/Source/core/css/resolver/StyleResolver.h
@@ -24,9 +24,7 @@
 
 #include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSRuleList.h"
-#include "core/css/CSSSVGDocumentValue.h"
 #include "core/css/CSSToStyleMap.h"
-#include "core/css/CSSValueList.h"
 #include "core/css/DocumentRuleSets.h"
 #include "core/css/InspectorCSSOMWrappers.h"
 #include "core/css/MediaQueryExp.h"
@@ -38,17 +36,13 @@
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/css/resolver/ScopedStyleResolver.h"
 #include "core/css/resolver/StyleResolverState.h"
+#include "core/css/resolver/StyleResourceLoader.h"
 #include "core/css/resolver/ViewportStyleResolver.h"
-#include "core/platform/LinkHash.h"
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
 #include "core/rendering/style/RenderStyle.h"
 #include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
-#include "wtf/text/AtomicStringHash.h"
-#include "wtf/text/StringHash.h"
 
 namespace WebCore {
 
@@ -79,7 +73,6 @@
 class RuleData;
 class RuleSet;
 class Settings;
-class StyleCustomFilterProgramCache;
 class StyleImage;
 class StyleKeyframe;
 class StylePendingImage;
@@ -92,7 +85,6 @@
 class StyleShader;
 class StyleSheet;
 class StyleSheetList;
-class StyledElement;
 
 class MediaQueryResult {
     WTF_MAKE_NONCOPYABLE(MediaQueryResult); WTF_MAKE_FAST_ALLOCATED;
@@ -128,12 +120,19 @@
     MatchRequest(RuleSet* ruleSet, bool includeEmptyRules = false, const ContainerNode* scope = 0)
         : ruleSet(ruleSet)
         , includeEmptyRules(includeEmptyRules)
-        , scope(scope) { }
+        , scope(scope)
+    {
+        // Now that we're about to read from the RuleSet, we're done adding more
+        // rules to the set and we should make sure it's compacted.
+        ruleSet->compactRulesIfNeeded();
+    }
+
     const RuleSet* ruleSet;
     const bool includeEmptyRules;
     const ContainerNode* scope;
 };
 
+
 // This class selects a RenderStyle for a given element based on a collection of stylesheets.
 class StyleResolver {
     WTF_MAKE_NONCOPYABLE(StyleResolver); WTF_MAKE_FAST_ALLOCATED;
@@ -160,9 +159,9 @@
 
     static PassRefPtr<RenderStyle> styleForDocument(Document*, CSSFontSelector* = 0);
 
-    Color colorFromPrimitiveValue(CSSPrimitiveValue* value, bool forVisitedLink = false) const
+    Color resolveColorFromPrimitiveValue(CSSPrimitiveValue* value, bool forVisitedLink = false)
     {
-        return m_state.colorFromPrimitiveValue(value, forVisitedLink);
+        return m_state.resolveColorFromPrimitiveValue(value, forVisitedLink);
     }
     RenderStyle* style() const { return m_state.style(); }
     RenderStyle* parentStyle() const { return m_state.parentStyle(); }
@@ -174,24 +173,29 @@
     // FIXME: It could be better to call m_ruleSets.appendAuthorStyleSheets() directly after we factor StyleRsolver further.
     // https://bugs.webkit.org/show_bug.cgi?id=108890
     void appendAuthorStyleSheets(unsigned firstNew, const Vector<RefPtr<CSSStyleSheet> >&);
+    // FIXME: resetAuthorStyle() will be removed when rulesets are reset in a per-scoping node manner.
     void resetAuthorStyle();
+    void resetAuthorStyle(const ContainerNode*);
+    void resetAtHostRules(const ContainerNode*);
 
     DocumentRuleSets& ruleSets() { return m_ruleSets; }
     const DocumentRuleSets& ruleSets() const { return m_ruleSets; }
     SelectorFilter& selectorFilter() { return m_selectorFilter; }
 
+    void setBuildScopedStyleTreeInDocumentOrder(bool enabled) { m_styleTree.setBuildInDocumentOrder(enabled); }
+    bool buildScopedStyleTreeInDocumentOrder() const { return m_styleTree.buildInDocumentOrder(); }
+
     ScopedStyleResolver* ensureScopedStyleResolver(const ContainerNode* scope)
     {
         return m_styleTree.ensureScopedStyleResolver(scope ? scope : document());
     }
 
 private:
-    void initElement(Element*);
     RenderStyle* locateSharedStyle();
     bool styleSharingCandidateMatchesRuleSet(RuleSet*);
     Node* locateCousinList(Element* parent, unsigned& visitedNodeCount) const;
-    StyledElement* findSiblingForStyleSharing(Node*, unsigned& count) const;
-    bool canShareStyleWithElement(StyledElement*) const;
+    Element* findSiblingForStyleSharing(Node*, unsigned& count) const;
+    bool canShareStyleWithElement(Element*) const;
 
     PassRefPtr<RenderStyle> styleForKeyframe(const RenderStyle*, const StyleKeyframe*, KeyframeValue&);
 
@@ -220,8 +224,6 @@
 public:
     bool useSVGZoomRules();
 
-    static bool colorFromPrimitiveValueIsDerivedFromElement(CSSPrimitiveValue*);
-
     bool hasSelectorForId(const AtomicString&) const;
     bool hasSelectorForClass(const AtomicString&) const;
     bool hasSelectorForAttribute(const AtomicString&) const;
@@ -243,11 +245,6 @@
 
     void invalidateMatchedPropertiesCache();
 
-    void loadPendingShaders();
-    void loadPendingSVGDocuments();
-
-    void loadPendingResources();
-
     struct RuleRange {
         RuleRange(int& firstRuleIndex, int& lastRuleIndex): firstRuleIndex(firstRuleIndex), lastRuleIndex(lastRuleIndex) { }
         int& firstRuleIndex;
@@ -375,15 +372,12 @@
     void cacheBorderAndBackground();
 
 private:
-    bool canShareStyleWithControl(StyledElement*) const;
+    bool canShareStyleWithControl(Element*) const;
 
     void applyProperty(CSSPropertyID, CSSValue*);
 
     void applySVGProperty(CSSPropertyID, CSSValue*);
 
-    PassRefPtr<StyleImage> loadPendingImage(StylePendingImage*);
-    void loadPendingImages();
-
     struct MatchedPropertiesCacheItem {
         void reportMemoryUsage(MemoryObjectInfo*) const;
         Vector<MatchedProperties> matchedProperties;
@@ -399,7 +393,7 @@
     void sweepMatchedPropertiesCache(Timer<StyleResolver>*);
 
     bool classNamesAffectedByRules(const SpaceSplitString&) const;
-    bool sharingCandidateHasIdenticalStyleAffectingAttributes(StyledElement*) const;
+    bool sharingCandidateHasIdenticalStyleAffectingAttributes(Element*) const;
 
     unsigned m_matchedPropertiesCacheAdditionsSinceLastSweep;
 
@@ -432,8 +426,7 @@
     InspectorCSSOMWrappers m_inspectorCSSOMWrappers;
 
     StyleResolverState m_state;
-
-    OwnPtr<StyleCustomFilterProgramCache> m_customFilterProgramCache;
+    StyleResourceLoader m_styleResourceLoader;
 
     friend class DeprecatedStyleBuilder;
     friend bool operator==(const MatchedProperties&, const MatchedProperties&);
diff --git a/Source/core/css/resolver/StyleResolverState.cpp b/Source/core/css/resolver/StyleResolverState.cpp
index ecdf471..a355f8e 100644
--- a/Source/core/css/resolver/StyleResolverState.cpp
+++ b/Source/core/css/resolver/StyleResolverState.cpp
@@ -22,12 +22,12 @@
 #include "config.h"
 #include "core/css/resolver/StyleResolverState.h"
 
-#include "core/css/CSSPrimitiveValueMappings.h"
+#include "core/dom/Element.h"
 #include "core/dom/Node.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeRenderingContext.h"
-#include "core/dom/StyledElement.h"
 #include "core/dom/VisitedLinkState.h"
+#include "core/page/Page.h"
 #include "core/rendering/RenderTheme.h"
 
 namespace WebCore {
@@ -49,20 +49,29 @@
     m_parentStyle = 0;
     m_parentNode = 0;
     m_regionForStyling = 0;
-    m_pendingImageProperties.clear();
-    m_hasPendingShaders = false;
-    m_pendingSVGDocuments.clear();
+    m_elementStyleResources.clear();
 }
 
-void StyleResolverState::initElement(Element* e)
+void StyleResolverState::initElement(Element* element)
 {
-    m_element = e;
-    m_styledElement = e && e->isStyledElement() ? static_cast<StyledElement*>(e) : 0;
-    m_elementLinkState = e ? e->document()->visitedLinkState()->determineLinkState(e) : NotInsideLink;
+    if (m_element == element)
+        return;
+
+    m_element = element;
+    m_styledElement = element && element->isStyledElement() ? element : 0;
+    m_elementLinkState = element ? element->document()->visitedLinkState()->determineLinkState(element) : NotInsideLink;
+
+    if (!element || element != element->document()->documentElement())
+        return;
+
+    element->document()->setDirectionSetOnDocumentElement(false);
+    element->document()->setWritingModeSetOnDocumentElement(false);
 }
 
 void StyleResolverState::initForStyleResolve(Document* document, Element* e, RenderStyle* parentStyle, RenderRegion* regionForStyling)
 {
+    initElement(e);
+
     m_regionForStyling = regionForStyling;
 
     if (e) {
@@ -83,8 +92,11 @@
     m_rootElementStyle = docElement && e != docElement ? docElement->renderStyle() : docStyle;
 
     m_style = 0;
-    m_pendingImageProperties.clear();
+    m_elementStyleResources.clear();
     m_fontDirty = false;
+
+    if (Page* page = document->page())
+        m_elementStyleResources.setDeviceScaleFactor(page->deviceScaleFactor());
 }
 
 
@@ -125,7 +137,7 @@
     return RenderTheme::defaultTheme()->systemColor(cssValueId);
 }
 
-Color StyleResolverState::colorFromPrimitiveValue(CSSPrimitiveValue* value, bool forVisitedLink) const
+Color StyleResolverState::resolveColorFromPrimitiveValue(CSSPrimitiveValue* value, bool forVisitedLink)
 {
     if (value->isRGBColor())
         return Color(value->getRGBA32Value());
@@ -143,11 +155,11 @@
     case CSSValueWebkitFocusRingColor:
         return RenderTheme::focusRingColor();
     case CSSValueCurrentcolor:
+        m_isMatchedPropertiesCacheable = false;
         return style()->color();
     default:
         return colorForCSSValue(valueID);
     }
 }
 
-
 } // namespace WebCore
diff --git a/Source/core/css/resolver/StyleResolverState.h b/Source/core/css/resolver/StyleResolverState.h
index 4084290..c181b57 100644
--- a/Source/core/css/resolver/StyleResolverState.h
+++ b/Source/core/css/resolver/StyleResolverState.h
@@ -25,10 +25,9 @@
 #include "CSSPropertyNames.h"
 
 #include "core/css/CSSSVGDocumentValue.h"
-#include "core/css/CSSValueList.h"
+#include "core/css/resolver/ElementStyleResources.h"
 #include "core/dom/Element.h"
 #include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/filters/FilterOperations.h"
 #include "core/rendering/style/BorderData.h"
 #include "core/rendering/style/FillLayer.h"
 #include "core/rendering/style/RenderStyle.h"
@@ -40,10 +39,6 @@
 class FillLayer;
 class FontDescription;
 class RenderRegion;
-class StyledElement;
-
-typedef HashMap<CSSPropertyID, RefPtr<CSSValue> > PendingImagePropertyMap;
-typedef HashMap<FilterOperation*, RefPtr<CSSSVGDocumentValue> > PendingSVGDocumentMap;
 
 class StyleResolverState {
 WTF_MAKE_NONCOPYABLE(StyleResolverState);
@@ -60,22 +55,22 @@
     , m_elementAffectedByClassRules(false)
     , m_applyPropertyToRegularStyle(true)
     , m_applyPropertyToVisitedLinkStyle(false)
-    , m_hasPendingShaders(false)
+    , m_isMatchedPropertiesCacheable(true)
     , m_lineHeightValue(0)
     , m_fontDirty(false)
     , m_hasUAAppearance(false)
     , m_backgroundData(BackgroundFillLayer) { }
 
-    public:
-    void initElement(Element*);
+public:
     void initForStyleResolve(Document*, Element*, RenderStyle* parentStyle = 0, RenderRegion* regionForStyling = 0);
     void clear();
 
-    Color colorFromPrimitiveValue(CSSPrimitiveValue*, bool forVisitedLink = false) const;
+    // This method might change an internal state, i.e. m_isMatchedPropertiesCachable.
+    Color resolveColorFromPrimitiveValue(CSSPrimitiveValue*, bool forVisitedLink = false);
 
     Document* document() const { return m_element->document(); }
     Element* element() const { return m_element; }
-    StyledElement* styledElement() const { return m_styledElement; }
+    Element* styledElement() const { return m_styledElement; }
     void setStyle(PassRefPtr<RenderStyle> style) { m_style = style; }
     RenderStyle* style() const { return m_style.get(); }
     PassRefPtr<RenderStyle> takeStyle() { return m_style.release(); }
@@ -95,10 +90,7 @@
     void setApplyPropertyToVisitedLinkStyle(bool isApply) { m_applyPropertyToVisitedLinkStyle = isApply; }
     bool applyPropertyToRegularStyle() const { return m_applyPropertyToRegularStyle; }
     bool applyPropertyToVisitedLinkStyle() const { return m_applyPropertyToVisitedLinkStyle; }
-    PendingImagePropertyMap& pendingImageProperties() { return m_pendingImageProperties; }
-    PendingSVGDocumentMap& pendingSVGDocuments() { return m_pendingSVGDocuments; }
-    void setHasPendingShaders(bool hasPendingShaders) { m_hasPendingShaders = hasPendingShaders; }
-    bool hasPendingShaders() const { return m_hasPendingShaders; }
+    bool isMatchedPropertiesCacheable() const { return m_isMatchedPropertiesCacheable; }
 
     void setLineHeightValue(CSSValue* value) { m_lineHeightValue = value; }
     CSSValue* lineHeightValue() { return m_lineHeightValue; }
@@ -110,6 +102,7 @@
     BorderData borderData() const { return m_borderData; }
     FillLayer backgroundData() const { return m_backgroundData; }
     Color backgroundColor() const { return m_backgroundColor; }
+    ElementStyleResources& elementStyleResources() { return m_elementStyleResources; }
 
     const FontDescription& fontDescription() { return m_style->fontDescription(); }
     const FontDescription& parentFontDescription() { return m_parentStyle->fontDescription(); }
@@ -119,12 +112,22 @@
     void setWritingMode(WritingMode writingMode) { m_fontDirty |= m_style->setWritingMode(writingMode); }
     void setTextOrientation(TextOrientation textOrientation) { m_fontDirty |= m_style->setTextOrientation(textOrientation); }
 
+    // SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
+    // of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
+    // multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
+    // Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
+    // need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
+    // width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
+    // if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
+    // properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
     bool useSVGZoomRules() const { return m_element && m_element->isSVGElement(); }
 
 private:
+    void initElement(Element*);
+
     Element* m_element;
     RefPtr<RenderStyle> m_style;
-    StyledElement* m_styledElement;
+    Element* m_styledElement;
     ContainerNode* m_parentNode;
     RefPtr<RenderStyle> m_parentStyle;
     RenderStyle* m_rootElementStyle;
@@ -140,10 +143,8 @@
 
     bool m_applyPropertyToRegularStyle;
     bool m_applyPropertyToVisitedLinkStyle;
+    bool m_isMatchedPropertiesCacheable;
 
-    PendingImagePropertyMap m_pendingImageProperties;
-    bool m_hasPendingShaders;
-    PendingSVGDocumentMap m_pendingSVGDocuments;
     CSSValue* m_lineHeightValue;
     bool m_fontDirty;
 
@@ -151,6 +152,7 @@
     BorderData m_borderData;
     FillLayer m_backgroundData;
     Color m_backgroundColor;
+    ElementStyleResources m_elementStyleResources;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/resolver/StyleResourceLoader.cpp b/Source/core/css/resolver/StyleResourceLoader.cpp
new file mode 100644
index 0000000..dabbbbc
--- /dev/null
+++ b/Source/core/css/resolver/StyleResourceLoader.cpp
@@ -0,0 +1,259 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "config.h"
+#include "core/css/resolver/StyleResourceLoader.h"
+
+#include "CSSPropertyNames.h"
+#include "core/css/CSSCursorImageValue.h"
+#include "core/css/CSSImageValue.h"
+#include "core/css/CSSSVGDocumentValue.h"
+#include "core/css/CSSShaderValue.h"
+#include "core/css/resolver/ElementStyleResources.h"
+#include "core/loader/cache/CachedResourceLoader.h"
+#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
+#include "core/rendering/style/ContentData.h"
+#include "core/rendering/style/CursorList.h"
+#include "core/rendering/style/FillLayer.h"
+#include "core/rendering/style/RenderStyle.h"
+#include "core/rendering/style/StyleCachedImage.h"
+#include "core/rendering/style/StyleCachedImageSet.h"
+#include "core/rendering/style/StyleCachedShader.h"
+#include "core/rendering/style/StyleCustomFilterProgram.h"
+#include "core/rendering/style/StyleCustomFilterProgramCache.h"
+#include "core/rendering/style/StyleGeneratedImage.h"
+#include "core/rendering/style/StylePendingImage.h"
+#include "core/rendering/style/StylePendingShader.h"
+
+namespace WebCore {
+
+StyleResourceLoader::StyleResourceLoader(CachedResourceLoader* cachedResourceLoader)
+    : m_cachedResourceLoader(cachedResourceLoader)
+    , m_customFilterProgramCache(StyleCustomFilterProgramCache::create())
+{
+}
+
+void StyleResourceLoader::loadPendingSVGDocuments(RenderStyle* renderStyle, const ElementStyleResources& elementStyleResources)
+{
+    if (!renderStyle->hasFilter() || elementStyleResources.pendingSVGDocuments().isEmpty())
+        return;
+
+    Vector<RefPtr<FilterOperation> >& filterOperations = renderStyle->mutableFilter().operations();
+    for (unsigned i = 0; i < filterOperations.size(); ++i) {
+        RefPtr<FilterOperation> filterOperation = filterOperations.at(i);
+        if (filterOperation->getOperationType() == FilterOperation::REFERENCE) {
+            ReferenceFilterOperation* referenceFilter = static_cast<ReferenceFilterOperation*>(filterOperation.get());
+
+            CSSSVGDocumentValue* value = elementStyleResources.pendingSVGDocuments().get(referenceFilter);
+            if (!value)
+                continue;
+            CachedDocument* cachedDocument = value->load(m_cachedResourceLoader);
+            if (!cachedDocument)
+                continue;
+
+            // Stash the CachedDocument on the reference filter.
+            referenceFilter->setCachedSVGDocumentReference(adoptPtr(new CachedSVGDocumentReference(cachedDocument)));
+        }
+    }
+}
+
+PassRefPtr<StyleImage> StyleResourceLoader::loadPendingImage(StylePendingImage* pendingImage, float deviceScaleFactor)
+{
+    if (pendingImage->cssImageValue()) {
+        CSSImageValue* imageValue = pendingImage->cssImageValue();
+        return imageValue->cachedImage(m_cachedResourceLoader);
+    }
+
+    if (pendingImage->cssImageGeneratorValue()) {
+        CSSImageGeneratorValue* imageGeneratorValue = pendingImage->cssImageGeneratorValue();
+        imageGeneratorValue->loadSubimages(m_cachedResourceLoader);
+        return StyleGeneratedImage::create(imageGeneratorValue);
+    }
+
+    if (pendingImage->cssCursorImageValue()) {
+        CSSCursorImageValue* cursorImageValue = pendingImage->cssCursorImageValue();
+        return cursorImageValue->cachedImage(m_cachedResourceLoader, deviceScaleFactor);
+    }
+
+    if (pendingImage->cssImageSetValue()) {
+        CSSImageSetValue* imageSetValue = pendingImage->cssImageSetValue();
+        return imageSetValue->cachedImageSet(m_cachedResourceLoader, deviceScaleFactor);
+    }
+
+    return 0;
+}
+
+void StyleResourceLoader::loadPendingShapeImage(RenderStyle* renderStyle, ShapeValue* shapeValue)
+{
+    if (!shapeValue)
+        return;
+
+    StyleImage* image = shapeValue->image();
+    if (!image || !image->isPendingImage())
+        return;
+
+    StylePendingImage* pendingImage = static_cast<StylePendingImage*>(image);
+    CSSImageValue* cssImageValue =  pendingImage->cssImageValue();
+
+    ResourceLoaderOptions options = CachedResourceLoader::defaultCachedResourceOptions();
+    options.requestOriginPolicy = RestrictToSameOrigin;
+
+    shapeValue->setImage(cssImageValue->cachedImage(m_cachedResourceLoader, options));
+}
+
+void StyleResourceLoader::loadPendingImages(RenderStyle* style, const ElementStyleResources& elementStyleResources)
+{
+    if (elementStyleResources.pendingImageProperties().isEmpty())
+        return;
+
+    PendingImagePropertyMap::const_iterator::Keys end = elementStyleResources.pendingImageProperties().end().keys();
+    for (PendingImagePropertyMap::const_iterator::Keys it = elementStyleResources.pendingImageProperties().begin().keys(); it != end; ++it) {
+        CSSPropertyID currentProperty = *it;
+
+        switch (currentProperty) {
+        case CSSPropertyBackgroundImage: {
+            for (FillLayer* backgroundLayer = style->accessBackgroundLayers(); backgroundLayer; backgroundLayer = backgroundLayer->next()) {
+                if (backgroundLayer->image() && backgroundLayer->image()->isPendingImage())
+                    backgroundLayer->setImage(loadPendingImage(static_cast<StylePendingImage*>(backgroundLayer->image()), elementStyleResources.deviceScaleFactor()));
+            }
+            break;
+        }
+        case CSSPropertyContent: {
+            for (ContentData* contentData = const_cast<ContentData*>(style->contentData()); contentData; contentData = contentData->next()) {
+                if (contentData->isImage()) {
+                    StyleImage* image = static_cast<ImageContentData*>(contentData)->image();
+                    if (image->isPendingImage()) {
+                        RefPtr<StyleImage> loadedImage = loadPendingImage(static_cast<StylePendingImage*>(image), elementStyleResources.deviceScaleFactor());
+                        if (loadedImage)
+                            static_cast<ImageContentData*>(contentData)->setImage(loadedImage.release());
+                    }
+                }
+            }
+            break;
+        }
+        case CSSPropertyCursor: {
+            if (CursorList* cursorList = style->cursors()) {
+                for (size_t i = 0; i < cursorList->size(); ++i) {
+                    CursorData& currentCursor = cursorList->at(i);
+                    if (StyleImage* image = currentCursor.image()) {
+                        if (image->isPendingImage())
+                            currentCursor.setImage(loadPendingImage(static_cast<StylePendingImage*>(image), elementStyleResources.deviceScaleFactor()));
+                    }
+                }
+            }
+            break;
+        }
+        case CSSPropertyListStyleImage: {
+            if (style->listStyleImage() && style->listStyleImage()->isPendingImage())
+                style->setListStyleImage(loadPendingImage(static_cast<StylePendingImage*>(style->listStyleImage()), elementStyleResources.deviceScaleFactor()));
+            break;
+        }
+        case CSSPropertyBorderImageSource: {
+            if (style->borderImageSource() && style->borderImageSource()->isPendingImage())
+                style->setBorderImageSource(loadPendingImage(static_cast<StylePendingImage*>(style->borderImageSource()), elementStyleResources.deviceScaleFactor()));
+            break;
+        }
+        case CSSPropertyWebkitBoxReflect: {
+            if (StyleReflection* reflection = style->boxReflect()) {
+                const NinePieceImage& maskImage = reflection->mask();
+                if (maskImage.image() && maskImage.image()->isPendingImage()) {
+                    RefPtr<StyleImage> loadedImage = loadPendingImage(static_cast<StylePendingImage*>(maskImage.image()), elementStyleResources.deviceScaleFactor());
+                    reflection->setMask(NinePieceImage(loadedImage.release(), maskImage.imageSlices(), maskImage.fill(), maskImage.borderSlices(), maskImage.outset(), maskImage.horizontalRule(), maskImage.verticalRule()));
+                }
+            }
+            break;
+        }
+        case CSSPropertyWebkitMaskBoxImageSource: {
+            if (style->maskBoxImageSource() && style->maskBoxImageSource()->isPendingImage())
+                style->setMaskBoxImageSource(loadPendingImage(static_cast<StylePendingImage*>(style->maskBoxImageSource()), elementStyleResources.deviceScaleFactor()));
+            break;
+        }
+        case CSSPropertyWebkitMaskImage: {
+            for (FillLayer* maskLayer = style->accessMaskLayers(); maskLayer; maskLayer = maskLayer->next()) {
+                if (maskLayer->image() && maskLayer->image()->isPendingImage())
+                    maskLayer->setImage(loadPendingImage(static_cast<StylePendingImage*>(maskLayer->image()), elementStyleResources.deviceScaleFactor()));
+            }
+            break;
+        }
+        case CSSPropertyWebkitShapeInside:
+            loadPendingShapeImage(style, style->shapeInside());
+            break;
+        case CSSPropertyWebkitShapeOutside:
+            loadPendingShapeImage(style, style->shapeOutside());
+            break;
+        default:
+            ASSERT_NOT_REACHED();
+        }
+    }
+}
+
+void StyleResourceLoader::loadPendingShaders(RenderStyle* style, const ElementStyleResources& elementStyleResources)
+{
+    if (!style->hasFilter() || !elementStyleResources.hasPendingShaders())
+        return;
+
+    Vector<RefPtr<FilterOperation> >& filterOperations = style->mutableFilter().operations();
+    for (unsigned i = 0; i < filterOperations.size(); ++i) {
+        RefPtr<FilterOperation> filterOperation = filterOperations.at(i);
+        if (filterOperation->getOperationType() == FilterOperation::CUSTOM) {
+            CustomFilterOperation* customFilter = static_cast<CustomFilterOperation*>(filterOperation.get());
+            ASSERT(customFilter->program());
+            StyleCustomFilterProgram* program = static_cast<StyleCustomFilterProgram*>(customFilter->program());
+            // Note that the StylePendingShaders could be already resolved to StyleCachedShaders. That's because the rule was matched before.
+            // However, the StyleCustomFilterProgram that was initially created could have been removed from the cache in the meanwhile,
+            // meaning that we get a new StyleCustomFilterProgram here that is not yet in the cache, but already has loaded StyleShaders.
+            if (!program->hasPendingShaders() && program->inCache())
+                continue;
+            RefPtr<StyleCustomFilterProgram> styleProgram = m_customFilterProgramCache->lookup(program);
+            if (styleProgram.get()) {
+                customFilter->setProgram(styleProgram.release());
+            } else {
+                if (program->vertexShader() && program->vertexShader()->isPendingShader()) {
+                    CSSShaderValue* shaderValue = static_cast<StylePendingShader*>(program->vertexShader())->cssShaderValue();
+                    program->setVertexShader(shaderValue->cachedShader(m_cachedResourceLoader));
+                }
+                if (program->fragmentShader() && program->fragmentShader()->isPendingShader()) {
+                    CSSShaderValue* shaderValue = static_cast<StylePendingShader*>(program->fragmentShader())->cssShaderValue();
+                    program->setFragmentShader(shaderValue->cachedShader(m_cachedResourceLoader));
+                }
+                m_customFilterProgramCache->add(program);
+            }
+        }
+    }
+}
+
+void StyleResourceLoader::loadPendingResources(RenderStyle* renderStyle, ElementStyleResources& elementStyleResources)
+{
+    // Start loading images referenced by this style.
+    loadPendingImages(renderStyle, elementStyleResources);
+
+    // Start loading the shaders referenced by this style.
+    loadPendingShaders(renderStyle, elementStyleResources);
+
+    // Start loading the SVG Documents referenced by this style.
+    loadPendingSVGDocuments(renderStyle, elementStyleResources);
+
+    // FIXME: Investigate if this clearing is necessary.
+    elementStyleResources.clear();
+}
+
+}
diff --git a/Source/core/css/resolver/StyleResourceLoader.h b/Source/core/css/resolver/StyleResourceLoader.h
new file mode 100644
index 0000000..0bf75d0
--- /dev/null
+++ b/Source/core/css/resolver/StyleResourceLoader.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef StyleResourceLoader_h
+#define StyleResourceLoader_h
+
+#include "wtf/OwnPtr.h"
+#include "wtf/PassRefPtr.h"
+
+namespace WebCore {
+
+class ElementStyleResources;
+class CachedResourceLoader;
+class RenderStyle;
+class ShapeValue;
+class StyleImage;
+class StylePendingImage;
+class StyleCustomFilterProgramCache;
+
+// Manages loading of resources, requested by the stylesheets.
+// Expects the same lifetime as StyleResolver, because:
+// 1) it expects CachedResourceLoader to never change, and
+// 2) it also holds the StyleCustomFilterProgramCache.
+class StyleResourceLoader {
+WTF_MAKE_NONCOPYABLE(StyleResourceLoader);
+public:
+    explicit StyleResourceLoader(CachedResourceLoader*);
+
+    void loadPendingResources(RenderStyle*, ElementStyleResources&);
+    StyleCustomFilterProgramCache* customFilterProgramCache() const { return m_customFilterProgramCache.get(); }
+
+private:
+    void loadPendingSVGDocuments(RenderStyle*, const ElementStyleResources&);
+    void loadPendingShaders(RenderStyle*, const ElementStyleResources&);
+
+    PassRefPtr<StyleImage> loadPendingImage(StylePendingImage*, float deviceScaleFactor);
+    void loadPendingImages(RenderStyle*, const ElementStyleResources&);
+    void loadPendingShapeImage(RenderStyle*, ShapeValue*);
+
+    OwnPtr<StyleCustomFilterProgramCache> m_customFilterProgramCache;
+    CachedResourceLoader* m_cachedResourceLoader;
+};
+
+} // namespace WebCore
+
+#endif // StyleResourceLoader_h
diff --git a/Source/core/css/resolver/ViewportStyleResolver.cpp b/Source/core/css/resolver/ViewportStyleResolver.cpp
index 7d2fce1..cc22bcf 100644
--- a/Source/core/css/resolver/ViewportStyleResolver.cpp
+++ b/Source/core/css/resolver/ViewportStyleResolver.cpp
@@ -36,8 +36,6 @@
 #include "core/dom/Document.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/ViewportArguments.h"
-#include "core/page/Page.h"
-#include "core/rendering/RenderView.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/resolver/ViewportStyleResolver.h b/Source/core/css/resolver/ViewportStyleResolver.h
index 6699561..a523bc5 100644
--- a/Source/core/css/resolver/ViewportStyleResolver.h
+++ b/Source/core/css/resolver/ViewportStyleResolver.h
@@ -31,7 +31,6 @@
 #define ViewportStyleResolver_h
 
 #include "CSSPropertyNames.h"
-#include "core/platform/graphics/FloatSize.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
 
diff --git a/Source/core/css/themeWin.css b/Source/core/css/themeWin.css
index 1bb96fa..b7a6f0b 100644
--- a/Source/core/css/themeWin.css
+++ b/Source/core/css/themeWin.css
@@ -120,6 +120,10 @@
     font: inherit !important;
 }
 
+select:disabled option:checked, option:disabled:checked {
+    color: #d2d2d2
+}
+
 textarea {
   font-family: monospace;
 }