Backed out 2 changesets (bug 1035091)
authorWes Kocher <wkocher@mozilla.com>
Thu, 03 Sep 2015 11:41:39 -0700
changeset 260657 3602ae56a243
parent 260656 74fbd245369c
child 260695 1eb12ed3b236
push id29319
push userkwierso@gmail.com
push dateThu, 03 Sep 2015 18:41:53 +0000
treeherdermozilla-central@3602ae56a243 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
bugs1035091
milestone43.0a1
backs out1fc07bdd9aa8
f6e98029d1cb
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Backed out 2 changesets (bug 1035091) a=backout Backed out changeset 1fc07bdd9aa8 (bug 1035091) Backed out changeset f6e98029d1cb (bug 1035091)
dom/base/nsDocument.cpp
dom/base/nsTreeSanitizer.cpp
dom/locales/en-US/chrome/layout/css.properties
dom/svg/SVGDocument.cpp
editor/libeditor/nsHTMLEditor.cpp
editor/libeditor/tests/test_bug520189.html
layout/base/nsStyleSheetService.cpp
layout/reftests/scoped-style/reftest.list
layout/reftests/scoped-style/scoped-style-document-ref.html
layout/reftests/scoped-style/scoped-style-document.html
layout/reftests/w3c-css/submitted/conditional3/css-supports-027.xht
layout/reftests/w3c-css/submitted/conditional3/css-supports-028.xht
layout/reftests/w3c-css/submitted/conditional3/reftest.list
layout/style/CSSStyleSheet.cpp
layout/style/Loader.cpp
layout/style/Loader.h
layout/style/crashtests/473720-1.html
layout/style/crashtests/495269-2.html
layout/style/crashtests/crashtests.list
layout/style/crashtests/long-url-list-stack-overflow.html
layout/style/nsCSSParser.cpp
layout/style/nsCSSParser.h
layout/style/nsLayoutStylesheetCache.cpp
layout/style/nsLayoutStylesheetCache.h
layout/style/test/chrome/chrome.ini
layout/style/test/chrome/moz_document_condition_text.css
layout/style/test/chrome/moz_document_nesting.css
layout/style/test/chrome/moz_document_serialization.css
layout/style/test/chrome/test_moz_document_condition_text.html
layout/style/test/chrome/test_moz_document_crashes.html
layout/style/test/chrome/test_moz_document_matching.html
layout/style/test/chrome/test_moz_document_nesting.html
layout/style/test/chrome/test_moz_document_rules.html
layout/style/test/chrome/test_moz_document_serialization.html
layout/style/test/chrome/test_moz_document_usability.html
layout/style/test/mochitest.ini
layout/style/test/test_bug511909.html
layout/style/test/test_condition_text.html
layout/style/test/test_css_eof_handling.html
layout/style/test/test_rule_insertion.html
layout/style/test/test_rule_serialization.html
--- a/dom/base/nsDocument.cpp
+++ b/dom/base/nsDocument.cpp
@@ -4404,49 +4404,30 @@ FindSheet(const nsCOMArray<nsIStyleSheet
     if (uri && NS_SUCCEEDED(uri->Equals(aSheetURI, &bEqual)) && bEqual)
       return i;
   }
 
   return -1;
 }
 
 nsresult
-nsDocument::LoadAdditionalStyleSheet(additionalSheetType aType,
-                                     nsIURI* aSheetURI)
+nsDocument::LoadAdditionalStyleSheet(additionalSheetType aType, nsIURI* aSheetURI)
 {
   NS_PRECONDITION(aSheetURI, "null arg");
 
   // Checking if we have loaded this one already.
   if (FindSheet(mAdditionalSheets[aType], aSheetURI) >= 0)
     return NS_ERROR_INVALID_ARG;
 
   // Loading the sheet sync.
-  nsRefPtr<css::Loader> loader = new css::Loader();
-
-  css::SheetParsingMode parsingMode;
-  switch (aType) {
-    case nsIDocument::eAgentSheet:
-      parsingMode = css::eAgentSheetFeatures;
-      break;
-
-    case nsIDocument::eUserSheet:
-      parsingMode = css::eUserSheetFeatures;
-      break;
-
-    case nsIDocument::eAuthorSheet:
-      parsingMode = css::eAuthorSheetFeatures;
-      break;
-
-    default:
-      MOZ_CRASH("impossible value for aType");
-  }
+  nsRefPtr<mozilla::css::Loader> loader = new mozilla::css::Loader();
 
   nsRefPtr<CSSStyleSheet> sheet;
-  nsresult rv = loader->LoadSheetSync(aSheetURI, parsingMode, true,
-                                      getter_AddRefs(sheet));
+  nsresult rv = loader->LoadSheetSync(aSheetURI, aType == eAgentSheet,
+    true, getter_AddRefs(sheet));
   NS_ENSURE_SUCCESS(rv, rv);
 
   sheet->SetOwningDocument(this);
   MOZ_ASSERT(sheet->IsApplicable());
 
   return AddAdditionalStyleSheet(aType, sheet);
 }
 
@@ -9949,20 +9930,17 @@ nsDocument::PreloadStyle(nsIURI* uri, co
                          Element::StringToCORSMode(aCrossOriginAttr),
                          aReferrerPolicy, aIntegrity);
 }
 
 nsresult
 nsDocument::LoadChromeSheetSync(nsIURI* uri, bool isAgentSheet,
                                 CSSStyleSheet** sheet)
 {
-  css::SheetParsingMode mode =
-    isAgentSheet ? css::eAgentSheetFeatures
-                 : css::eAuthorSheetFeatures;
-  return CSSLoader()->LoadSheetSync(uri, mode, isAgentSheet, sheet);
+  return CSSLoader()->LoadSheetSync(uri, isAgentSheet, isAgentSheet, sheet);
 }
 
 class nsDelayedEventDispatcher : public nsRunnable
 {
 public:
   explicit nsDelayedEventDispatcher(nsTArray<nsCOMPtr<nsIDocument>>& aDocuments)
   {
     mDocuments.SwapElements(aDocuments);
--- a/dom/base/nsTreeSanitizer.cpp
+++ b/dom/base/nsTreeSanitizer.cpp
@@ -1098,18 +1098,17 @@ nsTreeSanitizer::SanitizeStyleSheet(cons
   bool didSanitize = false;
   // Create a sheet to hold the parsed CSS
   nsRefPtr<CSSStyleSheet> sheet = new CSSStyleSheet(CORS_NONE, aDocument->GetReferrerPolicy());
   sheet->SetURIs(aDocument->GetDocumentURI(), nullptr, aBaseURI);
   sheet->SetPrincipal(aDocument->NodePrincipal());
   // Create the CSS parser, and parse the CSS text.
   nsCSSParser parser(nullptr, sheet);
   rv = parser.ParseSheet(aOriginal, aDocument->GetDocumentURI(), aBaseURI,
-                         aDocument->NodePrincipal(), 0,
-                         mozilla::css::eAuthorSheetFeatures);
+                         aDocument->NodePrincipal(), 0, false);
   NS_ENSURE_SUCCESS(rv, true);
   // Mark the sheet as complete.
   MOZ_ASSERT(!sheet->IsModified(),
              "should not get marked modified during parsing");
   sheet->SetComplete();
   // Loop through all the rules found in the CSS text
   int32_t ruleCount = sheet->StyleRuleCount();
   for (int32_t i = 0; i < ruleCount; ++i) {
--- a/dom/locales/en-US/chrome/layout/css.properties
+++ b/dom/locales/en-US/chrome/layout/css.properties
@@ -164,9 +164,8 @@ PEValueWithVariablesParsingError=Error i
 PEValueWithVariablesFallbackInherit=Falling back to 'inherit'.
 PEValueWithVariablesFallbackInitial=Falling back to 'initial'.
 PEInvalidVariableReference=Property contained reference to invalid variable.
 PEInvalidVariableTokenFallback=Found invalid token '%1$S' at top level of variable reference fallback.
 PEExpectedVariableNameEOF=identifier for variable name
 PEExpectedVariableName=Expected identifier for variable name but found '%1$S'.
 PEExpectedVariableFallback=Expected variable reference fallback after ','.
 PEExpectedVariableCommaOrCloseParen=Expected ',' or ')' after variable name in variable reference but found '%1$S'.
-PEMozDocumentRuleNotAllowed=@-moz-document rules may only be used in user style sheets.
--- a/dom/svg/SVGDocument.cpp
+++ b/dom/svg/SVGDocument.cpp
@@ -143,19 +143,17 @@ SVGDocument::EnsureNonSVGUserAgentStyleS
                                    getter_Copies(spec));
 
           mozilla::css::Loader* cssLoader = CSSLoader();
           if (cssLoader->GetEnabled()) {
             nsCOMPtr<nsIURI> uri;
             NS_NewURI(getter_AddRefs(uri), spec);
             if (uri) {
               nsRefPtr<CSSStyleSheet> cssSheet;
-              cssLoader->LoadSheetSync(uri,
-                                       mozilla::css::eAgentSheetFeatures,
-                                       true, getter_AddRefs(cssSheet));
+              cssLoader->LoadSheetSync(uri, true, true, getter_AddRefs(cssSheet));
               if (cssSheet) {
                 EnsureOnDemandBuiltInUASheet(cssSheet);
               }
             }
           }
         }
       }
     }
--- a/editor/libeditor/nsHTMLEditor.cpp
+++ b/editor/libeditor/nsHTMLEditor.cpp
@@ -2835,18 +2835,17 @@ nsHTMLEditor::AddOverrideStyleSheet(cons
   NS_ENSURE_SUCCESS(rv, rv);
 
   // We MUST ONLY load synchronous local files (no @import)
   // XXXbz Except this will actually try to load remote files
   // synchronously, of course..
   nsRefPtr<CSSStyleSheet> sheet;
   // Editor override style sheets may want to style Gecko anonymous boxes
   rv = ps->GetDocument()->CSSLoader()->
-    LoadSheetSync(uaURI, mozilla::css::eAgentSheetFeatures, true,
-                  getter_AddRefs(sheet));
+    LoadSheetSync(uaURI, true, true, getter_AddRefs(sheet));
 
   // Synchronous loads should ALWAYS return completed
   NS_ENSURE_TRUE(sheet, NS_ERROR_NULL_POINTER);
 
   // Add the override style sheet
   // (This checks if already exists)
   ps->AddOverrideStyleSheet(sheet);
 
--- a/editor/libeditor/tests/test_bug520189.html
+++ b/editor/libeditor/tests/test_bug520189.html
@@ -1,15 +1,15 @@
 <!DOCTYPE HTML>
 <html>
 <!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=520189
+https://bugzilla.mozilla.org/show_bug.cgi?id=520182
 -->
 <head>
-  <title>Test for Bug 520189</title>
+  <title>Test for Bug 520182</title>
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
   <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>  
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=520182">Mozilla Bug 520182</a>
 <p id="display"></p>
 <div id="content">
@@ -74,17 +74,17 @@ https://bugzilla.mozilla.org/show_bug.cg
   <div id="xxx" contenteditable="true"></div>
   <iframe id="xxxx" src="about:blank"></iframe>
   <div id="yyy" contenteditable="true"></div>
   <iframe id="yyyy" src="about:blank"></iframe>
 </div>
 <pre id="test">
 <script type="application/javascript">
 
-/** Test for Bug 520189 **/
+/** Test for Bug 520182 **/
 
 const dataPayload = "foo<iframe src=\"data:text/html,bar\"></iframe>baz";
 const jsPayload = "foo<iframe src=\"javascript:void('bar');\"></iframe>baz";
 const httpPayload = "foo<iframe src=\"http://mochi.test:8888/\"></iframe>baz";
 const scriptPayload ="foo<script>document.write(\"<iframe></iframe>\");</sc" + "ript>baz";
 const scriptExternalPayload = "foo<script src=\"data:text/javascript,document.write('<iframe></iframe>');\"></sc" + "ript>baz";
 const validStyle1Payload = "foo<style>#bar{color:red;}</style>baz";
 const validStyle2Payload = "foo<span style=\"color:red\">bar</span>baz";
@@ -416,31 +416,23 @@ var tests = [
     rootElement() { return document.getElementById("rr"); },
     checkResult(html) { isnot(html.indexOf("bar"), -1, "Should have retained the _bar attribute"); },
   },
   {
     id: "ss",
     isIFrame: true,
     payload: invalidStyle8Payload,
     rootElement() { return document.getElementById("ss").contentDocument.documentElement; },
-    // The sanitizer currently doesn't discard unrecognized rules when
-    // that would make the sheet completely empty (see bug 1177546).
-    // This is harmless, since @-moz-document is inoperative in author
-    // style sheets (see bug 1035091).
-    checkResult(html) { todo_is(html.indexOf("@-moz-document"), -1, "Should not have retained the @-moz-document rule"); },
+    checkResult(html) { is(html.indexOf("@-moz-document"), -1, "Should not have retained the @-moz-document rule"); },
   },
   {
     id: "tt",
     payload: invalidStyle8Payload,
     rootElement() { return document.getElementById("tt"); },
-    // The sanitizer currently doesn't discard unrecognized rules when
-    // that would make the sheet completely empty (see bug 1177546).
-    // This is harmless, since @-moz-document is inoperative in author
-    // style sheets (see bug 1035091).
-    checkResult(html) { todo_is(html.indexOf("@-moz-document"), -1, "Should not have retained the @-moz-document rule"); },
+    checkResult(html) { is(html.indexOf("@-moz-document"), -1, "Should not have retained the @-moz-document rule"); },
   },
   {
     id: "uu",
     isIFrame: true,
     payload: invalidStyle9Payload,
     rootElement() { return document.getElementById("uu").contentDocument.documentElement; },
     checkResult(html) { is(html.indexOf("@-moz-keyframes"), -1, "Should not have retained the @-moz-keyframes rule"); },
   },
--- a/layout/base/nsStyleSheetService.cpp
+++ b/layout/base/nsStyleSheetService.cpp
@@ -175,42 +175,27 @@ nsStyleSheetService::LoadAndRegisterShee
   }
   return rv;
 }
 
 nsresult
 nsStyleSheetService::LoadAndRegisterSheetInternal(nsIURI *aSheetURI,
                                                   uint32_t aSheetType)
 {
+  NS_ENSURE_ARG(aSheetType == AGENT_SHEET ||
+                aSheetType == USER_SHEET ||
+                aSheetType == AUTHOR_SHEET);
   NS_ENSURE_ARG_POINTER(aSheetURI);
 
-  css::SheetParsingMode parsingMode;
-  switch (aSheetType) {
-    case AGENT_SHEET:
-      parsingMode = css::eAgentSheetFeatures;
-      break;
-
-    case USER_SHEET:
-      parsingMode = css::eUserSheetFeatures;
-      break;
-
-    case AUTHOR_SHEET:
-      parsingMode = css::eAuthorSheetFeatures;
-      break;
-
-    default:
-      NS_WARNING("invalid sheet type argument");
-      return NS_ERROR_INVALID_ARG;
-  }
-
   nsRefPtr<css::Loader> loader = new css::Loader();
 
   nsRefPtr<CSSStyleSheet> sheet;
-  nsresult rv = loader->LoadSheetSync(aSheetURI, parsingMode, true,
-                                      getter_AddRefs(sheet));
+  // Allow UA sheets, but not user sheets, to use unsafe rules
+  nsresult rv = loader->LoadSheetSync(aSheetURI, aSheetType == AGENT_SHEET,
+                                      true, getter_AddRefs(sheet));
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!mSheets[aSheetType].AppendObject(sheet)) {
     rv = NS_ERROR_OUT_OF_MEMORY;
   }
 
   return rv;
 }
@@ -229,42 +214,28 @@ nsStyleSheetService::SheetRegistered(nsI
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsStyleSheetService::PreloadSheet(nsIURI *aSheetURI, uint32_t aSheetType,
                                   nsIDOMStyleSheet **aSheet)
 {
-  NS_PRECONDITION(aSheet, "Null out param");
+  NS_ENSURE_ARG(aSheetType == AGENT_SHEET ||
+                aSheetType == USER_SHEET ||
+                aSheetType == AUTHOR_SHEET);
   NS_ENSURE_ARG_POINTER(aSheetURI);
-  css::SheetParsingMode parsingMode;
-  switch (aSheetType) {
-    case AGENT_SHEET:
-      parsingMode = css::eAgentSheetFeatures;
-      break;
-
-    case USER_SHEET:
-      parsingMode = css::eUserSheetFeatures;
-      break;
-
-    case AUTHOR_SHEET:
-      parsingMode = css::eAuthorSheetFeatures;
-      break;
-
-    default:
-      NS_WARNING("invalid sheet type argument");
-      return NS_ERROR_INVALID_ARG;
-  }
+  NS_PRECONDITION(aSheet, "Null out param");
 
   nsRefPtr<css::Loader> loader = new css::Loader();
 
+  // Allow UA sheets, but not user sheets, to use unsafe rules
   nsRefPtr<CSSStyleSheet> sheet;
-  nsresult rv = loader->LoadSheetSync(aSheetURI, parsingMode, true,
-                                      getter_AddRefs(sheet));
+  nsresult rv = loader->LoadSheetSync(aSheetURI, aSheetType == AGENT_SHEET,
+                                      true, getter_AddRefs(sheet));
   NS_ENSURE_SUCCESS(rv, rv);
   sheet.forget(aSheet);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsStyleSheetService::UnregisterSheet(nsIURI *aSheetURI, uint32_t aSheetType)
 {
--- a/layout/reftests/scoped-style/reftest.list
+++ b/layout/reftests/scoped-style/reftest.list
@@ -43,14 +43,15 @@
 == scoped-style-dynamic-012.svg scoped-style-dynamic-012-ref.svg
 == scoped-style-dynamic-013.svg scoped-style-dynamic-013-ref.svg
 == scoped-style-dynamic-014.svg scoped-style-dynamic-014-ref.svg
 == scoped-style-dynamic-015.svg scoped-style-dynamic-015-ref.svg
 == scoped-style-import.html scoped-style-import-ref.html
 == scoped-style-media.html scoped-style-media-ref.html
 == scoped-style-namespace.html scoped-style-namespace-ref.html
 == scoped-style-charset.html scoped-style-charset-ref.html
+== scoped-style-document.html scoped-style-document-ref.html
 HTTP(..) == scoped-style-font-face.html scoped-style-font-face-ref.html
 == scoped-style-keyframes.html scoped-style-keyframes-ref.html
 == scoped-style-supports.html scoped-style-supports-ref.html
 pref(layout.css.scope-pseudo.enabled,true) == scoped-style-pseudo-001.html scoped-style-pseudo-001-ref.html
 pref(layout.css.scope-pseudo.enabled,true) == scoped-style-pseudo-002.html scoped-style-pseudo-002-ref.html
 pref(layout.css.scope-pseudo.enabled,true) == scoped-style-pseudo-003.html scoped-style-pseudo-003-ref.html
new file mode 100644
--- /dev/null
+++ b/layout/reftests/scoped-style/scoped-style-document-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE html>
+<body>
+  <p>First</p>
+  <p style="color: blue">Second</p>
+  <p>Third</p>
+</body>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/scoped-style/scoped-style-document.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<body>
+  <p>First</p>
+  <p>
+    <style scoped>
+      @-moz-document regexp("^.*scoped-style-document\\.html$") {
+        p { color: blue }
+      }
+    </style>
+    Second
+  </p>
+  <p>Third</p>
+</body>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/w3c-css/submitted/conditional3/css-supports-027.xht
@@ -0,0 +1,21 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+  <title>CSS Test: A nested @supports rule with valid syntax and a passing condition must apply rules inside it</title>
+  <link rel="author" title="Cameron McCormack" href="mailto:cam@mcc.id.au" />
+  <link rel="help" href="http://www.w3.org/TR/css3-conditional/#at-supports" />
+  <link rel="help" href="http://www.w3.org/TR/css3-conditional/#at-document" />
+  <meta name="flags" content="" />
+  <meta name="assert" content="An outer @document rule with an inner @supports rule must apply the rules inside the @supports only if both the @supports and @document conditions pass."/>
+  <link rel="match" href="support/pass.xht" />
+  <style type="text/css"><![CDATA[
+    @-moz-document url-prefix("") {
+      @supports (color: green) {
+        html { background-color: green }
+      }
+    }
+  ]]></style>
+ </head>
+ <body>
+ </body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/w3c-css/submitted/conditional3/css-supports-028.xht
@@ -0,0 +1,20 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+  <title>CSS Test: A nested @supports rule with valid syntax and a passing condition must apply rules inside it</title>
+  <link rel="author" title="Cameron McCormack" href="mailto:cam@mcc.id.au" />
+  <link rel="help" href="http://www.w3.org/TR/css3-conditional/#at-supports" />
+  <meta name="flags" content="" />
+  <meta name="assert" content="An inner @document rule with an outer @supports rule must apply the rules inside the @document only if both the @supports and @document conditions pass."/>
+  <link rel="match" href="support/pass.xht" />
+  <style type="text/css"><![CDATA[
+    @supports (color: green) {
+      @-moz-document url-prefix("") {
+        html { background-color: green }
+      }
+    }
+  ]]></style>
+ </head>
+ <body>
+ </body>
+</html>
--- a/layout/reftests/w3c-css/submitted/conditional3/reftest.list
+++ b/layout/reftests/w3c-css/submitted/conditional3/reftest.list
@@ -19,16 +19,18 @@
 == css-supports-019.xht support/pass.xht
 == css-supports-020.xht support/pass.xht
 == css-supports-021.xht support/pass.xht
 == css-supports-022.xht support/pass.xht
 == css-supports-023.xht support/pass.xht
 == css-supports-024.xht support/pass.xht
 == css-supports-025.xht support/pass.xht
 == css-supports-026.xht support/pass.xht
+== css-supports-027.xht support/pass.xht
+== css-supports-028.xht support/pass.xht
 == css-supports-029.xht support/pass.xht
 == css-supports-030.xht support/pass.xht
 == css-supports-031.xht support/pass.xht
 == css-supports-032.xht support/pass.xht
 == css-supports-033.xht support/pass.xht
 == css-supports-034.xht support/pass.xht
 == css-supports-035.xht support/pass.xht
 == css-supports-036.xht support/pass.xht
--- a/layout/style/CSSStyleSheet.cpp
+++ b/layout/style/CSSStyleSheet.cpp
@@ -2304,24 +2304,21 @@ CSSStyleSheet::ParseSheet(const nsAStrin
     NS_ASSERTION(child->mParent == this, "Child sheet is not parented to this!");
     child->mParent = nullptr;
     child->mDocument = nullptr;
   }
   mInner->mFirstChild = nullptr;
   mInner->mNameSpaceMap = nullptr;
 
   // allow unsafe rules if the style sheet's principal is the system principal
-  css::SheetParsingMode parsingMode =
-    nsContentUtils::IsSystemPrincipal(mInner->mPrincipal)
-      ? css::eAgentSheetFeatures
-      : css::eAuthorSheetFeatures;
+  bool allowUnsafeRules = nsContentUtils::IsSystemPrincipal(mInner->mPrincipal);
 
   nsCSSParser parser(loader, this);
   nsresult rv = parser.ParseSheet(aInput, mInner->mSheetURI, mInner->mBaseURI,
-                                  mInner->mPrincipal, 1, parsingMode);
+                                  mInner->mPrincipal, 1, allowUnsafeRules);
   DidDirty(); // we are always 'dirty' here since we always remove rules first
   NS_ENSURE_SUCCESS(rv, rv);
 
   // notify document of all new rules
   if (mDocument) {
     for (int32_t index = 0; index < mInner->mOrderedRules.Count(); ++index) {
       nsRefPtr<css::Rule> rule = mInner->mOrderedRules.ObjectAt(index);
       if (rule->GetType() == css::Rule::IMPORT_RULE &&
--- a/layout/style/Loader.cpp
+++ b/layout/style/Loader.cpp
@@ -99,22 +99,16 @@ using namespace mozilla::dom;
 
 namespace mozilla {
 namespace css {
 
 /*********************************************
  * Data needed to properly load a stylesheet *
  *********************************************/
 
-static_assert(eAuthorSheetFeatures == 0 &&
-              eUserSheetFeatures == 1 &&
-              eAgentSheetFeatures == 2,
-              "sheet parsing mode constants won't fit "
-              "in SheetLoadData::mParsingMode");
-
 class SheetLoadData final : public nsIRunnable,
                             public nsIUnicharStreamLoaderObserver,
                             public nsIThreadObserver
 {
 protected:
   virtual ~SheetLoadData(void);
 
 public:
@@ -138,17 +132,17 @@ public:
                 nsIPrincipal* aLoaderPrincipal,
                 nsINode* aRequestingNode);
 
   // Data for loading a non-document sheet
   SheetLoadData(Loader* aLoader,
                 nsIURI* aURI,
                 CSSStyleSheet* aSheet,
                 bool aSyncLoad,
-                SheetParsingMode aParsingMode,
+                bool aAllowUnsafeRules,
                 bool aUseSystemPrincipal,
                 const nsCString& aCharset,
                 nsICSSLoaderObserver* aObserver,
                 nsIPrincipal* aLoaderPrincipal,
                 nsINode* aRequestingNode);
 
   already_AddRefed<nsIURI> GetReferrerURI();
 
@@ -216,22 +210,19 @@ public:
   // are fired for any SheetLoadData that has a non-null
   // mOwningElement.
   bool                       mMustNotify : 1;
 
   // mWasAlternate is true if the sheet was an alternate when the load data was
   // created.
   bool                       mWasAlternate : 1;
 
-  // mParsingMode controls access to nonstandard style constructs that
-  // are not safe for use on the public Web but necessary in UA sheets
-  // and/or useful in user sheets.  The only values stored in this
-  // field are 0, 1, and 2; three bits are allocated to avoid issues
-  // should the enum type be signed.
-  SheetParsingMode           mParsingMode : 3;
+  // mAllowUnsafeRules is true if we should allow unsafe rules to be parsed
+  // in the loaded sheet.
+  bool                       mAllowUnsafeRules : 1;
 
   // mUseSystemPrincipal is true if the system principal should be used for
   // this sheet, no matter what the channel principal is.  Only true for sync
   // loads.
   bool                       mUseSystemPrincipal : 1;
 
   // If true, this SheetLoadData is being used as a way to handle
   // async observer notification for an already-complete sheet.
@@ -337,17 +328,17 @@ SheetLoadData::SheetLoadData(Loader* aLo
     mNext(nullptr),
     mPendingChildren(0),
     mSyncLoad(false),
     mIsNonDocumentSheet(false),
     mIsLoading(false),
     mIsCancelled(false),
     mMustNotify(false),
     mWasAlternate(aIsAlternate),
-    mParsingMode(eAuthorSheetFeatures),
+    mAllowUnsafeRules(false),
     mUseSystemPrincipal(false),
     mSheetAlreadyComplete(false),
     mOwningElement(aOwningElement),
     mObserver(aObserver),
     mLoaderPrincipal(aLoaderPrincipal),
     mRequestingNode(aRequestingNode)
 {
   NS_PRECONDITION(mLoader, "Must have a loader!");
@@ -368,42 +359,42 @@ SheetLoadData::SheetLoadData(Loader* aLo
     mParentData(aParentData),
     mPendingChildren(0),
     mSyncLoad(false),
     mIsNonDocumentSheet(false),
     mIsLoading(false),
     mIsCancelled(false),
     mMustNotify(false),
     mWasAlternate(false),
-    mParsingMode(eAuthorSheetFeatures),
+    mAllowUnsafeRules(false),
     mUseSystemPrincipal(false),
     mSheetAlreadyComplete(false),
     mOwningElement(nullptr),
     mObserver(aObserver),
     mLoaderPrincipal(aLoaderPrincipal),
     mRequestingNode(aRequestingNode)
 {
   NS_PRECONDITION(mLoader, "Must have a loader!");
   if (mParentData) {
     mSyncLoad = mParentData->mSyncLoad;
     mIsNonDocumentSheet = mParentData->mIsNonDocumentSheet;
-    mParsingMode = mParentData->mParsingMode;
+    mAllowUnsafeRules = mParentData->mAllowUnsafeRules;
     mUseSystemPrincipal = mParentData->mUseSystemPrincipal;
     ++(mParentData->mPendingChildren);
   }
 
   NS_POSTCONDITION(!mUseSystemPrincipal || mSyncLoad,
                    "Shouldn't use system principal for async loads");
 }
 
 SheetLoadData::SheetLoadData(Loader* aLoader,
                              nsIURI* aURI,
                              CSSStyleSheet* aSheet,
                              bool aSyncLoad,
-                             SheetParsingMode aParsingMode,
+                             bool aAllowUnsafeRules,
                              bool aUseSystemPrincipal,
                              const nsCString& aCharset,
                              nsICSSLoaderObserver* aObserver,
                              nsIPrincipal* aLoaderPrincipal,
                              nsINode* aRequestingNode)
   : mLoader(aLoader),
     mURI(aURI),
     mLineNumber(1),
@@ -411,30 +402,26 @@ SheetLoadData::SheetLoadData(Loader* aLo
     mNext(nullptr),
     mPendingChildren(0),
     mSyncLoad(aSyncLoad),
     mIsNonDocumentSheet(true),
     mIsLoading(false),
     mIsCancelled(false),
     mMustNotify(false),
     mWasAlternate(false),
-    mParsingMode(aParsingMode),
+    mAllowUnsafeRules(aAllowUnsafeRules),
     mUseSystemPrincipal(aUseSystemPrincipal),
     mSheetAlreadyComplete(false),
     mOwningElement(nullptr),
     mObserver(aObserver),
     mLoaderPrincipal(aLoaderPrincipal),
     mRequestingNode(aRequestingNode),
     mCharsetHint(aCharset)
 {
   NS_PRECONDITION(mLoader, "Must have a loader!");
-  NS_PRECONDITION(aParsingMode == eAuthorSheetFeatures ||
-                  aParsingMode == eUserSheetFeatures ||
-                  aParsingMode == eAgentSheetFeatures,
-                  "Unrecognized sheet parsing mode");
 
   NS_POSTCONDITION(!mUseSystemPrincipal || mSyncLoad,
                    "Shouldn't use system principal for async loads");
 }
 
 SheetLoadData::~SheetLoadData()
 {
   NS_IF_RELEASE(mNext);
@@ -1753,17 +1740,17 @@ Loader::ParseSheet(const nsAString& aInp
 
   // Push our load data on the stack so any kids can pick it up
   mParsingDatas.AppendElement(aLoadData);
   nsIURI* sheetURI = aLoadData->mSheet->GetSheetURI();
   nsIURI* baseURI = aLoadData->mSheet->GetBaseURI();
   nsresult rv = parser.ParseSheet(aInput, sheetURI, baseURI,
                                   aLoadData->mSheet->Principal(),
                                   aLoadData->mLineNumber,
-                                  aLoadData->mParsingMode);
+                                  aLoadData->mAllowUnsafeRules);
   mParsingDatas.RemoveElementAt(mParsingDatas.Length() - 1);
 
   if (NS_FAILED(rv)) {
     LOG_ERROR(("  Low-level error in parser!"));
     SheetComplete(aLoadData, rv);
     return rv;
   }
 
@@ -2261,60 +2248,59 @@ Loader::LoadChildSheet(CSSStyleSheet* aP
   // If syncLoad is true, |data| will be deleted by now.
   if (!syncLoad) {
     data->mMustNotify = true;
   }
   return rv;
 }
 
 nsresult
-Loader::LoadSheetSync(nsIURI* aURL,
-                      SheetParsingMode aParsingMode,
+Loader::LoadSheetSync(nsIURI* aURL, bool aAllowUnsafeRules,
                       bool aUseSystemPrincipal,
                       CSSStyleSheet** aSheet)
 {
   LOG(("css::Loader::LoadSheetSync"));
-  return InternalLoadNonDocumentSheet(aURL, aParsingMode,
+  return InternalLoadNonDocumentSheet(aURL, aAllowUnsafeRules,
                                       aUseSystemPrincipal, nullptr,
                                       EmptyCString(), aSheet, nullptr);
 }
 
 nsresult
 Loader::LoadSheet(nsIURI* aURL,
                   nsIPrincipal* aOriginPrincipal,
                   const nsCString& aCharset,
                   nsICSSLoaderObserver* aObserver,
                   CSSStyleSheet** aSheet)
 {
   LOG(("css::Loader::LoadSheet(aURL, aObserver, aSheet) api call"));
   NS_PRECONDITION(aSheet, "aSheet is null");
-  return InternalLoadNonDocumentSheet(aURL, eAuthorSheetFeatures, false,
+  return InternalLoadNonDocumentSheet(aURL, false, false,
                                       aOriginPrincipal, aCharset,
                                       aSheet, aObserver);
 }
 
 nsresult
 Loader::LoadSheet(nsIURI* aURL,
                   nsIPrincipal* aOriginPrincipal,
                   const nsCString& aCharset,
                   nsICSSLoaderObserver* aObserver,
                   CORSMode aCORSMode,
                   ReferrerPolicy aReferrerPolicy,
                   const nsAString& aIntegrity)
 {
   LOG(("css::Loader::LoadSheet(aURL, aObserver) api call"));
-  return InternalLoadNonDocumentSheet(aURL, eAuthorSheetFeatures, false,
+  return InternalLoadNonDocumentSheet(aURL, false, false,
                                       aOriginPrincipal, aCharset,
                                       nullptr, aObserver, aCORSMode,
                                       aReferrerPolicy, aIntegrity);
 }
 
 nsresult
 Loader::InternalLoadNonDocumentSheet(nsIURI* aURL,
-                                     SheetParsingMode aParsingMode,
+                                     bool aAllowUnsafeRules,
                                      bool aUseSystemPrincipal,
                                      nsIPrincipal* aOriginPrincipal,
                                      const nsCString& aCharset,
                                      CSSStyleSheet** aSheet,
                                      nsICSSLoaderObserver* aObserver,
                                      CORSMode aCORSMode,
                                      ReferrerPolicy aReferrerPolicy,
                                      const nsAString& aIntegrity)
@@ -2361,17 +2347,17 @@ Loader::InternalLoadNonDocumentSheet(nsI
     }
     if (aSheet) {
       sheet.swap(*aSheet);
     }
     return rv;
   }
 
   SheetLoadData* data =
-    new SheetLoadData(this, aURL, sheet, syncLoad, aParsingMode,
+    new SheetLoadData(this, aURL, sheet, syncLoad, aAllowUnsafeRules,
                       aUseSystemPrincipal, aCharset, aObserver,
                       aOriginPrincipal, mDocument);
 
   NS_ADDREF(data);
   rv = LoadSheet(data, state);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (aSheet) {
--- a/layout/style/Loader.h
+++ b/layout/style/Loader.h
@@ -137,43 +137,16 @@ class ImportRule;
 enum StyleSheetState {
   eSheetStateUnknown = 0,
   eSheetNeedsParser,
   eSheetPending,
   eSheetLoading,
   eSheetComplete
 };
 
-/**
- * Enum defining the mode in which a sheet is to be parsed.  This is
- * usually, but not always, the same as the cascade level at which the
- * sheet will apply (see nsStyleSet.h).  Most of the Loader APIs only
- * support loading of author sheets.
- *
- * Author sheets are the normal case: styles embedded in or linked
- * from HTML pages.  They are also the most restricted.
- *
- * User sheets can do anything author sheets can do, and also get
- * access to a few CSS extensions that are not yet suitable for
- * exposure on the public Web, but are very useful for expressing
- * user style overrides, such as @-moz-document rules.
- *
- * Agent sheets have access to all author- and user-sheet features
- * plus more extensions that are necessary for internal use but,
- * again, not yet suitable for exposure on the public Web.  Some of
- * these are outright unsafe to expose; in particular, incorrect
- * styling of anonymous box pseudo-elements can violate layout
- * invariants.
- */
-enum SheetParsingMode {
-  eAuthorSheetFeatures = 0,
-  eUserSheetFeatures,
-  eAgentSheetFeatures
-};
-
 class Loader final {
   typedef mozilla::net::ReferrerPolicy ReferrerPolicy;
 
 public:
   Loader();
   explicit Loader(nsIDocument*);
 
  private:
@@ -278,49 +251,51 @@ public:
   /**
    * Synchronously load and return the stylesheet at aURL.  Any child sheets
    * will also be loaded synchronously.  Note that synchronous loads over some
    * protocols may involve spinning up a new event loop, so use of this method
    * does NOT guarantee not receiving any events before the sheet loads.  This
    * method can be used to load sheets not associated with a document.
    *
    * @param aURL the URL of the sheet to load
-   * @param aParsingMode the mode in which to parse the sheet
-   *        (see comments at enum SheetParsingMode, above).
+   * @param aEnableUnsafeRules whether unsafe rules are enabled for this
+   * sheet load
+   * Unsafe rules are rules that can violate key Gecko invariants if misused.
+   * In particular, most anonymous box pseudoelements must be very carefully
+   * styled or we will have severe problems. Therefore unsafe rules should
+   * never be enabled for stylesheets controlled by untrusted sites; preferably
+   * unsafe rules should only be enabled for agent sheets.
    * @param aUseSystemPrincipal if true, give the resulting sheet the system
    * principal no matter where it's being loaded from.
    * @param [out] aSheet the loaded, complete sheet.
    *
    * NOTE: At the moment, this method assumes the sheet will be UTF-8, but
    * ideally it would allow arbitrary encodings.  Callers should NOT depend on
    * non-UTF8 sheets being treated as UTF-8 by this method.
    *
    * NOTE: A successful return from this method doesn't indicate anything about
    * whether the data could be parsed as CSS and doesn't indicate anything
    * about the status of child sheets of the returned sheet.
    */
-  nsresult LoadSheetSync(nsIURI* aURL,
-                         SheetParsingMode aParsingMode,
+  nsresult LoadSheetSync(nsIURI* aURL, bool aEnableUnsafeRules,
                          bool aUseSystemPrincipal,
                          CSSStyleSheet** aSheet);
 
   /**
-   * As above, but defaults aParsingMode to eAuthorSheetFeatures and
-   * aUseSystemPrincipal to false.
+   * As above, but aUseSystemPrincipal and aEnableUnsafeRules are assumed false.
    */
   nsresult LoadSheetSync(nsIURI* aURL, CSSStyleSheet** aSheet) {
-    return LoadSheetSync(aURL, eAuthorSheetFeatures, false, aSheet);
+    return LoadSheetSync(aURL, false, false, aSheet);
   }
 
   /**
    * Asynchronously load the stylesheet at aURL.  If a successful result is
    * returned, aObserver is guaranteed to be notified asynchronously once the
    * sheet is loaded and marked complete.  This method can be used to load
-   * sheets not associated with a document.  This method cannot be used to
-   * load user or agent sheets.
+   * sheets not associated with a document.
    *
    * @param aURL the URL of the sheet to load
    * @param aOriginPrincipal the principal to use for security checks.  This
    *                         can be null to indicate that these checks should
    *                         be skipped.
    * @param aCharset the encoding to use for converting the sheet data
    *        from bytes to Unicode.  May be empty to indicate that the
    *        charset of the CSSLoader's document should be used.  This
@@ -466,17 +441,17 @@ private:
                             nsIContent* aLinkingContent,
                             nsIDocument* aDocument);
 
   nsresult InsertChildSheet(CSSStyleSheet* aSheet,
                             CSSStyleSheet* aParentSheet,
                             ImportRule* aParentRule);
 
   nsresult InternalLoadNonDocumentSheet(nsIURI* aURL,
-                                        SheetParsingMode aParsingMode,
+                                        bool aAllowUnsafeRules,
                                         bool aUseSystemPrincipal,
                                         nsIPrincipal* aOriginPrincipal,
                                         const nsCString& aCharset,
                                         CSSStyleSheet** aSheet,
                                         nsICSSLoaderObserver* aObserver,
                                         CORSMode aCORSMode = CORS_NONE,
                                         ReferrerPolicy aReferrerPolicy = mozilla::net::RP_Default,
                                         const nsAString& aIntegrity = EmptyString());
--- a/layout/style/crashtests/473720-1.html
+++ b/layout/style/crashtests/473720-1.html
@@ -1,14 +1,15 @@
 <html><head><style>
 /* Recovery from an unparseable recognized @-rule is not the same thing
    as recovery from an unrecognized @-rule.  */
 
 @charset # { }
 @import # { }
 @namespace # { }
 @media # { }
+@-moz-document # { }
 @font-face # { }
 @page # { }
 @-non-mozilla # { }
 @nonstandard # { }
 
 </style></head></html>
new file mode 100644
--- /dev/null
+++ b/layout/style/crashtests/495269-2.html
@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<html>
+  <head>
+    <link rel="stylesheet" href="data:text/css,@-moz-document domain(example.com) {}';">
+    <link rel="stylesheet" href="data:text/css,@-moz-document domain(example.com) {}';">
+    <script>
+      // Force a unique inner for the second linked sheet
+      document.styleSheets[1].cssRules[0];
+    </script>
+  </head>
+</html>
+
--- a/layout/style/crashtests/crashtests.list
+++ b/layout/style/crashtests/crashtests.list
@@ -44,17 +44,19 @@ load 472237-1.html # will fail, test for
 HTTP(..) load 472237-1.html
 load 473720-1.html
 load 473892-1.html
 load 473914-1.html
 load 478321-1.xhtml
 load 512851-1.xhtml
 load 539613-1.xhtml
 load 588627-1.html
+skip load long-url-list-stack-overflow.html # skipped due to being slow (bug 477490)
 load 495269-1.html
+load 495269-2.html
 load 498036-1.html
 load 509155-1.html
 load 509156-1.html
 load 509569-1.html
 load 524252-1.html
 load font-face-truncated-src.html 
 load 536789-1.html
 load 565248-1.html
new file mode 100644
--- /dev/null
+++ b/layout/style/crashtests/long-url-list-stack-overflow.html
@@ -0,0 +1,23 @@
+<!DOCTYPE html>
+<html>
+<head>
+<style id="s"></style>
+<script type="text/javascript">
+
+// Duplicates the string 2^n times
+function exp(s, n)
+{
+  for (var i = 0; i < n; ++i)
+    s += s;
+  return s;
+}
+
+var stylesheet = "@-moz-document url(http://www.w3.org/)" + exp(", url-prefix(file:///)", 20) + " { }";
+document.getElementById("s").textContent = stylesheet;
+
+</script>
+</head>
+<body>
+<div></div>
+</body>
+</html>
--- a/layout/style/nsCSSParser.cpp
+++ b/layout/style/nsCSSParser.cpp
@@ -100,22 +100,16 @@ static void AssignRuleToPointer(css::Rul
 static void AppendRuleToSheet(css::Rule* aRule, void* aParser);
 
 struct CSSParserInputState {
   nsCSSScannerPosition mPosition;
   nsCSSToken mToken;
   bool mHavePushBack;
 };
 
-static_assert(eAuthorSheetFeatures == 0 &&
-              eUserSheetFeatures == 1 &&
-              eAgentSheetFeatures == 2,
-              "sheet parsing mode constants won't fit "
-              "in CSSParserImpl::mParsingMode");
-
 // Your basic top-down recursive descent style parser
 // The exposed methods and members of this class are precisely those
 // needed by nsCSSParser, far below.
 class CSSParserImpl {
 public:
   CSSParserImpl();
   ~CSSParserImpl();
 
@@ -130,17 +124,17 @@ public:
   // Clears everything set by the above Set*() functions.
   void Reset();
 
   nsresult ParseSheet(const nsAString& aInput,
                       nsIURI*          aSheetURI,
                       nsIURI*          aBaseURI,
                       nsIPrincipal*    aSheetPrincipal,
                       uint32_t         aLineNumber,
-                      SheetParsingMode aParsingMode);
+                      bool             aAllowUnsafeRules);
 
   nsresult ParseStyleAttribute(const nsAString&  aAttributeValue,
                                nsIURI*           aDocURL,
                                nsIURI*           aBaseURL,
                                nsIPrincipal*     aNodePrincipal,
                                css::StyleRule**  aResult);
 
   nsresult ParseDeclarations(const nsAString&  aBuffer,
@@ -314,30 +308,22 @@ public:
                                            nsRuleData* aRuleData,
                                            nsIURI* aDocURL,
                                            nsIURI* aBaseURL,
                                            nsIPrincipal* aDocPrincipal,
                                            CSSStyleSheet* aSheet,
                                            uint32_t aLineNumber,
                                            uint32_t aLineOffset);
 
-  bool AgentRulesEnabled() const {
-    return mParsingMode == eAgentSheetFeatures;
-  }
-  bool UserRulesEnabled() const {
-    return mParsingMode == eAgentSheetFeatures ||
-           mParsingMode == eUserSheetFeatures;
-  }
-
   nsCSSProps::EnabledState PropertyEnabledState() const {
     static_assert(nsCSSProps::eEnabledForAllContent == 0,
                   "nsCSSProps::eEnabledForAllContent should be zero for "
                   "this bitfield to work");
     nsCSSProps::EnabledState enabledState = nsCSSProps::eEnabledForAllContent;
-    if (AgentRulesEnabled()) {
+    if (mUnsafeRulesEnabled) {
       enabledState |= nsCSSProps::eEnabledInUASheets;
     }
     if (mIsChromeOrCertifiedApp) {
       enabledState |= nsCSSProps::eEnabledInChromeOrCertifiedApp;
     }
     return enabledState;
   }
 
@@ -1213,22 +1199,18 @@ protected:
   bool          mNavQuirkMode : 1;
 
   // True when the hashless color quirk applies.
   bool mHashlessColorQuirk : 1;
 
   // True when the unitless length quirk applies.
   bool mUnitlessLengthQuirk : 1;
 
-  // Controls access to nonstandard style constructs that are not safe
-  // for use on the public Web but necessary in UA sheets and/or
-  // useful in user sheets.  The only values stored in this field are
-  // 0, 1, and 2; three bits are allocated to avoid issues should the
-  // enum type be signed.
-  SheetParsingMode mParsingMode : 3;
+  // True if unsafe rules should be allowed
+  bool mUnsafeRulesEnabled : 1;
 
   // True if we are in parsing rules for Chrome or Certified App content,
   // in which case CSS properties with the
   // CSS_PROPERTY_ALWAYS_ENABLED_IN_CHROME_OR_CERTIFIED_APP
   // flag should be allowed.
   bool mIsChromeOrCertifiedApp : 1;
 
   // True if viewport units should be allowed.
@@ -1347,17 +1329,17 @@ CSSParserImpl::CSSParserImpl()
     mReporter(nullptr),
     mChildLoader(nullptr),
     mSection(eCSSSection_Charset),
     mNameSpaceMap(nullptr),
     mHavePushBack(false),
     mNavQuirkMode(false),
     mHashlessColorQuirk(false),
     mUnitlessLengthQuirk(false),
-    mParsingMode(eAuthorSheetFeatures),
+    mUnsafeRulesEnabled(false),
     mIsChromeOrCertifiedApp(false),
     mViewportUnitsEnabled(true),
     mHTMLMediaMode(false),
     mParsingCompoundProperty(false),
     mInSupportsCondition(false),
     mInFailingSupportsRule(false),
     mSuppressErrors(false),
     mSheetPrincipalRequired(true),
@@ -1454,17 +1436,17 @@ CSSParserImpl::ReleaseScanner()
 }
 
 nsresult
 CSSParserImpl::ParseSheet(const nsAString& aInput,
                           nsIURI*          aSheetURI,
                           nsIURI*          aBaseURI,
                           nsIPrincipal*    aSheetPrincipal,
                           uint32_t         aLineNumber,
-                          SheetParsingMode aParsingMode)
+                          bool             aAllowUnsafeRules)
 {
   NS_PRECONDITION(aSheetPrincipal, "Must have principal here!");
   NS_PRECONDITION(aBaseURI, "need base URI");
   NS_PRECONDITION(aSheetURI, "need sheet URI");
   NS_PRECONDITION(mSheet, "Must have sheet to parse into");
   NS_ENSURE_STATE(mSheet);
 
 #ifdef DEBUG
@@ -1499,17 +1481,17 @@ CSSParserImpl::ParseSheet(const nsAStrin
           break;
       }
     }
   }
   else {
     mSection = eCSSSection_Charset; // sheet is empty, any rules are fair
   }
 
-  mParsingMode = aParsingMode;
+  mUnsafeRulesEnabled = aAllowUnsafeRules;
   mIsChromeOrCertifiedApp =
     dom::IsChromeURI(aSheetURI) ||
     aSheetPrincipal->GetAppStatus() == nsIPrincipal::APP_STATUS_CERTIFIED;
 
   nsCSSToken* tk = &mToken;
   for (;;) {
     // Get next non-whitespace token
     if (!GetToken(true)) {
@@ -1525,17 +1507,17 @@ CSSParserImpl::ParseSheet(const nsAStrin
     }
     UngetToken();
     if (ParseRuleSet(AppendRuleToSheet, this)) {
       mSection = eCSSSection_General;
     }
   }
   ReleaseScanner();
 
-  mParsingMode = eAuthorSheetFeatures;
+  mUnsafeRulesEnabled = false;
   mIsChromeOrCertifiedApp = false;
 
   // XXX check for low level errors
   return NS_OK;
 }
 
 /**
  * Determines whether the identifier contained in the given string is a
@@ -1703,17 +1685,17 @@ CSSParserImpl::ParseProperty(const nsCSS
   mSection = eCSSSection_General;
   scanner.SetSVGMode(aIsSVGMode);
 
   *aChanged = false;
 
   // Check for unknown or preffed off properties
   if (eCSSProperty_UNKNOWN == aPropID ||
       !(nsCSSProps::IsEnabled(aPropID) ||
-        (AgentRulesEnabled() &&
+        (mUnsafeRulesEnabled &&
          nsCSSProps::PropHasFlags(aPropID,
                                   CSS_PROPERTY_ALWAYS_ENABLED_IN_UA_SHEETS)))) {
     NS_ConvertASCIItoUTF16 propName(nsCSSProps::GetStringValue(aPropID));
     REPORT_UNEXPECTED_P(PEUnknownProperty, propName);
     REPORT_UNEXPECTED(PEDeclDropped);
     OUTPUT_ERROR();
     ReleaseScanner();
     return;
@@ -2994,24 +2976,18 @@ CSSParserImpl::ParseAtRule(RuleAppendFun
     parseFunc = &CSSParserImpl::ParseNameSpaceRule;
     newSection = eCSSSection_NameSpace;
 
   } else if (mToken.mIdent.LowerCaseEqualsLiteral("media")) {
     parseFunc = &CSSParserImpl::ParseMediaRule;
     newSection = eCSSSection_General;
 
   } else if (mToken.mIdent.LowerCaseEqualsLiteral("-moz-document")) {
-    if (UserRulesEnabled()) {
-      parseFunc = &CSSParserImpl::ParseMozDocumentRule;
-      newSection = eCSSSection_General;
-    } else {
-      REPORT_UNEXPECTED_TOKEN(PEMozDocumentRuleNotAllowed);
-      OUTPUT_ERROR();
-      return SkipAtRule(aInAtRule);
-    }
+    parseFunc = &CSSParserImpl::ParseMozDocumentRule;
+    newSection = eCSSSection_General;
 
   } else if (mToken.mIdent.LowerCaseEqualsLiteral("font-face")) {
     parseFunc = &CSSParserImpl::ParseFontFaceRule;
     newSection = eCSSSection_General;
 
   } else if (mToken.mIdent.LowerCaseEqualsLiteral("font-feature-values")) {
     parseFunc = &CSSParserImpl::ParseFontFeatureValuesRule;
     newSection = eCSSSection_General;
@@ -5609,17 +5585,17 @@ CSSParserImpl::ParsePseudoSelector(int32
   bool isTreePseudo = false;
   nsCSSPseudoElements::Type pseudoElementType =
     nsCSSPseudoElements::GetPseudoType(pseudo);
   nsCSSPseudoClasses::Type pseudoClassType =
     nsCSSPseudoClasses::GetPseudoType(pseudo);
   bool pseudoClassIsUserAction =
     nsCSSPseudoClasses::IsUserActionPseudoClass(pseudoClassType);
 
-  if (!AgentRulesEnabled() &&
+  if (!mUnsafeRulesEnabled &&
       ((pseudoElementType < nsCSSPseudoElements::ePseudo_PseudoElementCount &&
         nsCSSPseudoElements::PseudoElementIsUASheetOnly(pseudoElementType)) ||
        (pseudoClassType != nsCSSPseudoClasses::ePseudoClass_NotPseudoClass &&
         nsCSSPseudoClasses::PseudoClassIsUASheetOnly(pseudoClassType)))) {
     // This pseudo-element or pseudo-class is not exposed to content.
     REPORT_UNEXPECTED_TOKEN(PEPseudoSelUnknown);
     UngetToken();
     return eSelectorParsingStatus_Error;
@@ -5645,20 +5621,20 @@ CSSParserImpl::ParsePseudoSelector(int32
   // be false, and it will still pass that check.  So the tree
   // pseudo-elements are allowed to be either functions or not, as
   // desired.
   bool isTree = (eCSSToken_Function == mToken.mType) && isTreePseudo;
 #endif
   bool isPseudoElement =
     (pseudoElementType < nsCSSPseudoElements::ePseudo_PseudoElementCount);
   // anonymous boxes are only allowed if they're the tree boxes or we have
-  // enabled agent rules
+  // enabled unsafe rules
   bool isAnonBox = isTreePseudo ||
     (pseudoElementType == nsCSSPseudoElements::ePseudo_AnonBox &&
-     AgentRulesEnabled());
+     mUnsafeRulesEnabled);
   bool isPseudoClass =
     (pseudoClassType != nsCSSPseudoClasses::ePseudoClass_NotPseudoClass);
 
   NS_ASSERTION(!isPseudoClass ||
                pseudoElementType == nsCSSPseudoElements::ePseudo_NotPseudoElement,
                "Why is this atom both a pseudo-class and a pseudo-element?");
   NS_ASSERTION(isPseudoClass + isPseudoElement + isAnonBox <= 1,
                "Shouldn't be more than one of these");
@@ -10480,21 +10456,21 @@ CSSParserImpl::ParseSingleValueProperty(
   }
 
   uint32_t variant = nsCSSProps::ParserVariant(aPropID);
   if (variant == 0) {
     MOZ_ASSERT(false, "not a single value property");
     return false;
   }
 
-  // We only allow 'script-level' when agent rules are enabled, because
+  // We only allow 'script-level' when unsafe rules are enabled, because
   // otherwise it could interfere with rulenode optimizations if used in
   // a non-MathML-enabled document. We also only allow math-display when
-  // agent rules are enabled.
-  if (!AgentRulesEnabled() &&
+  // unsafe rules are enabled.
+  if (!mUnsafeRulesEnabled &&
       (aPropID == eCSSProperty_script_level ||
        aPropID == eCSSProperty_math_display))
     return false;
 
   const KTableValue* kwtable = nsCSSProps::kKeywordTableTable[aPropID];
   uint32_t restrictions = nsCSSProps::ValueRestrictions(aPropID);
   return ParseVariantWithRestrictions(aValue, variant, kwtable, restrictions);
 }
@@ -15800,21 +15776,21 @@ nsCSSParser::SetChildLoader(mozilla::css
 }
 
 nsresult
 nsCSSParser::ParseSheet(const nsAString& aInput,
                         nsIURI*          aSheetURI,
                         nsIURI*          aBaseURI,
                         nsIPrincipal*    aSheetPrincipal,
                         uint32_t         aLineNumber,
-                        SheetParsingMode aParsingMode)
+                        bool             aAllowUnsafeRules)
 {
   return static_cast<CSSParserImpl*>(mImpl)->
     ParseSheet(aInput, aSheetURI, aBaseURI, aSheetPrincipal, aLineNumber,
-               aParsingMode);
+               aAllowUnsafeRules);
 }
 
 nsresult
 nsCSSParser::ParseStyleAttribute(const nsAString&  aAttributeValue,
                                  nsIURI*           aDocURI,
                                  nsIURI*           aBaseURI,
                                  nsIPrincipal*     aNodePrincipal,
                                  css::StyleRule**  aResult)
--- a/layout/style/nsCSSParser.h
+++ b/layout/style/nsCSSParser.h
@@ -4,17 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* parsing of CSS stylesheets, based on a token stream from the CSS scanner */
 
 #ifndef nsCSSParser_h___
 #define nsCSSParser_h___
 
 #include "mozilla/Attributes.h"
-#include "mozilla/css/Loader.h"
 
 #include "nsCSSProperty.h"
 #include "nsCSSScanner.h"
 #include "nsCOMPtr.h"
 #include "nsAutoPtr.h"
 #include "nsStringFwd.h"
 #include "nsTArrayForwardDeclare.h"
 
@@ -28,16 +27,17 @@ class nsCSSValue;
 struct nsRuleData;
 
 namespace mozilla {
 class CSSStyleSheet;
 class CSSVariableValues;
 namespace css {
 class Rule;
 class Declaration;
+class Loader;
 class StyleRule;
 } // namespace css
 } // namespace mozilla
 
 // Interface to the css parser.
 
 class MOZ_STACK_CLASS nsCSSParser {
 public:
@@ -72,24 +72,25 @@ public:
    * @param aInput the data to parse
    * @param aSheetURL the URI to use as the sheet URI (for error reporting).
    *                  This must match the URI of the sheet passed to
    *                  SetStyleSheet.
    * @param aBaseURI the URI to use for relative URI resolution
    * @param aSheetPrincipal the principal of the stylesheet.  This must match
    *                        the principal of the sheet passed to SetStyleSheet.
    * @param aLineNumber the line number of the first line of the sheet.
-   * @param aParsingMode  see SheetParsingMode in css/Loader.h
+   * @param aAllowUnsafeRules see aEnableUnsafeRules in
+   *                          mozilla::css::Loader::LoadSheetSync
    */
   nsresult ParseSheet(const nsAString& aInput,
                       nsIURI*          aSheetURL,
                       nsIURI*          aBaseURI,
                       nsIPrincipal*    aSheetPrincipal,
                       uint32_t         aLineNumber,
-                      mozilla::css::SheetParsingMode aParsingMode);
+                      bool             aAllowUnsafeRules);
 
   // Parse HTML style attribute or its equivalent in other markup
   // languages.  aBaseURL is the base url to use for relative links in
   // the declaration.
   nsresult ParseStyleAttribute(const nsAString&  aAttributeValue,
                                nsIURI*           aDocURL,
                                nsIURI*           aBaseURL,
                                nsIPrincipal*     aNodePrincipal,
--- a/layout/style/nsLayoutStylesheetCache.cpp
+++ b/layout/style/nsLayoutStylesheetCache.cpp
@@ -14,17 +14,16 @@
 #include "nsIFile.h"
 #include "nsNetUtil.h"
 #include "nsIObserverService.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIXULRuntime.h"
 #include "nsPrintfCString.h"
 
 using namespace mozilla;
-using namespace mozilla::css;
 
 static bool sNumberControlEnabled;
 
 #define NUMBER_CONTROL_PREF "dom.forms.number"
 
 NS_IMPL_ISUPPORTS(
   nsLayoutStylesheetCache, nsIObserver, nsIMemoryReporter)
 
@@ -55,48 +54,48 @@ nsLayoutStylesheetCache::Observe(nsISupp
 CSSStyleSheet*
 nsLayoutStylesheetCache::ScrollbarsSheet()
 {
   EnsureGlobal();
 
   if (!gStyleCache->mScrollbarsSheet) {
     // Scrollbars don't need access to unsafe rules
     LoadSheetURL("chrome://global/skin/scrollbars.css",
-                 gStyleCache->mScrollbarsSheet, eAuthorSheetFeatures);
+                 gStyleCache->mScrollbarsSheet, false);
   }
 
   return gStyleCache->mScrollbarsSheet;
 }
 
 CSSStyleSheet*
 nsLayoutStylesheetCache::FormsSheet()
 {
   EnsureGlobal();
 
   if (!gStyleCache->mFormsSheet) {
     // forms.css needs access to unsafe rules
     LoadSheetURL("resource://gre-resources/forms.css",
-                 gStyleCache->mFormsSheet, eAgentSheetFeatures);
+                 gStyleCache->mFormsSheet, true);
   }
 
   return gStyleCache->mFormsSheet;
 }
 
 CSSStyleSheet*
 nsLayoutStylesheetCache::NumberControlSheet()
 {
   EnsureGlobal();
 
   if (!sNumberControlEnabled) {
     return nullptr;
   }
 
   if (!gStyleCache->mNumberControlSheet) {
     LoadSheetURL("resource://gre-resources/number-control.css",
-                 gStyleCache->mNumberControlSheet, eAgentSheetFeatures);
+                 gStyleCache->mNumberControlSheet, true);
   }
 
   return gStyleCache->mNumberControlSheet;
 }
 
 CSSStyleSheet*
 nsLayoutStylesheetCache::UserContentSheet()
 {
@@ -113,30 +112,30 @@ nsLayoutStylesheetCache::UserChromeSheet
 
 CSSStyleSheet*
 nsLayoutStylesheetCache::UASheet()
 {
   EnsureGlobal();
 
   if (!gStyleCache->mUASheet) {
     LoadSheetURL("resource://gre-resources/ua.css",
-                 gStyleCache->mUASheet, eAgentSheetFeatures);
+                 gStyleCache->mUASheet, true);
   }
 
   return gStyleCache->mUASheet;
 }
 
 CSSStyleSheet*
 nsLayoutStylesheetCache::HTMLSheet()
 {
   EnsureGlobal();
 
   if (!gStyleCache->mHTMLSheet) {
     LoadSheetURL("resource://gre-resources/html.css",
-                 gStyleCache->mHTMLSheet, eAgentSheetFeatures);
+                 gStyleCache->mHTMLSheet, true);
   }
 
   return gStyleCache->mHTMLSheet;
 }
 
 CSSStyleSheet*
 nsLayoutStylesheetCache::MinimalXULSheet()
 {
@@ -174,17 +173,17 @@ nsLayoutStylesheetCache::SVGSheet()
 
 CSSStyleSheet*
 nsLayoutStylesheetCache::MathMLSheet()
 {
   EnsureGlobal();
 
   if (!gStyleCache->mMathMLSheet) {
     LoadSheetURL("resource://gre-resources/mathml.css",
-                 gStyleCache->mMathMLSheet, eAgentSheetFeatures);
+                 gStyleCache->mMathMLSheet, true);
   }
 
   return gStyleCache->mMathMLSheet;
 }
 
 CSSStyleSheet*
 nsLayoutStylesheetCache::CounterStylesSheet()
 {
@@ -195,30 +194,30 @@ nsLayoutStylesheetCache::CounterStylesSh
 
 CSSStyleSheet*
 nsLayoutStylesheetCache::NoScriptSheet()
 {
   EnsureGlobal();
 
   if (!gStyleCache->mNoScriptSheet) {
     LoadSheetURL("resource://gre-resources/noscript.css",
-                 gStyleCache->mNoScriptSheet, eAgentSheetFeatures);
+                 gStyleCache->mNoScriptSheet, true);
   }
 
   return gStyleCache->mNoScriptSheet;
 }
 
 CSSStyleSheet*
 nsLayoutStylesheetCache::NoFramesSheet()
 {
   EnsureGlobal();
 
   if (!gStyleCache->mNoFramesSheet) {
     LoadSheetURL("resource://gre-resources/noframes.css",
-                 gStyleCache->mNoFramesSheet, eAgentSheetFeatures);
+                 gStyleCache->mNoFramesSheet, true);
   }
 
   return gStyleCache->mNoFramesSheet;
 }
 
 /* static */ CSSStyleSheet*
 nsLayoutStylesheetCache::ChromePreferenceSheet(nsPresContext* aPresContext)
 {
@@ -247,30 +246,30 @@ nsLayoutStylesheetCache::ContentPreferen
 
 /* static */ CSSStyleSheet*
 nsLayoutStylesheetCache::ContentEditableSheet()
 {
   EnsureGlobal();
 
   if (!gStyleCache->mContentEditableSheet) {
     LoadSheetURL("resource://gre/res/contenteditable.css",
-                 gStyleCache->mContentEditableSheet, eAgentSheetFeatures);
+                 gStyleCache->mContentEditableSheet, true);
   }
 
   return gStyleCache->mContentEditableSheet;
 }
 
 /* static */ CSSStyleSheet*
 nsLayoutStylesheetCache::DesignModeSheet()
 {
   EnsureGlobal();
 
   if (!gStyleCache->mDesignModeSheet) {
     LoadSheetURL("resource://gre/res/designmode.css",
-                 gStyleCache->mDesignModeSheet, eAgentSheetFeatures);
+                 gStyleCache->mDesignModeSheet, true);
   }
 
   return gStyleCache->mDesignModeSheet;
 }
 
 void
 nsLayoutStylesheetCache::Shutdown()
 {
@@ -339,27 +338,27 @@ nsLayoutStylesheetCache::nsLayoutStylesh
     obsSvc->AddObserver(this, "chrome-flush-caches", false);
   }
 
   InitFromProfile();
 
   // And make sure that we load our UA sheets.  No need to do this
   // per-profile, since they're profile-invariant.
   LoadSheetURL("resource://gre-resources/counterstyles.css",
-               mCounterStylesSheet, eAgentSheetFeatures);
+               mCounterStylesSheet, true);
   LoadSheetURL("resource://gre-resources/full-screen-override.css",
-               mFullScreenOverrideSheet, eAgentSheetFeatures);
+               mFullScreenOverrideSheet, true);
   LoadSheetURL("chrome://global/content/minimal-xul.css",
-               mMinimalXULSheet, eAgentSheetFeatures);
+               mMinimalXULSheet, true);
   LoadSheetURL("resource://gre-resources/quirk.css",
-               mQuirkSheet, eAgentSheetFeatures);
+               mQuirkSheet, true);
   LoadSheetURL("resource://gre/res/svg.css",
-               mSVGSheet, eAgentSheetFeatures);
+               mSVGSheet, true);
   LoadSheetURL("chrome://global/content/xul.css",
-               mXULSheet, eAgentSheetFeatures);
+               mXULSheet, true);
 
   // The remaining sheets are created on-demand do to their use being rarer
   // (which helps save memory for Firefox OS apps) or because they need to
   // be re-loadable in DependentPrefChanged.
 }
 
 nsLayoutStylesheetCache::~nsLayoutStylesheetCache()
 {
@@ -416,81 +415,79 @@ nsLayoutStylesheetCache::InitFromProfile
   }
 
   contentFile->Clone(getter_AddRefs(chromeFile));
   if (!chromeFile) return;
 
   contentFile->Append(NS_LITERAL_STRING("userContent.css"));
   chromeFile->Append(NS_LITERAL_STRING("userChrome.css"));
 
-  LoadSheetFile(contentFile, mUserContentSheet, eUserSheetFeatures);
-  LoadSheetFile(chromeFile, mUserChromeSheet, eUserSheetFeatures);
+  LoadSheetFile(contentFile, mUserContentSheet);
+  LoadSheetFile(chromeFile, mUserChromeSheet);
 }
 
 /* static */ void
 nsLayoutStylesheetCache::LoadSheetURL(const char* aURL,
                                       nsRefPtr<CSSStyleSheet>& aSheet,
-                                      SheetParsingMode aParsingMode)
+                                      bool aEnableUnsafeRules)
 {
   nsCOMPtr<nsIURI> uri;
   NS_NewURI(getter_AddRefs(uri), aURL);
-  LoadSheet(uri, aSheet, aParsingMode);
+  LoadSheet(uri, aSheet, aEnableUnsafeRules);
   if (!aSheet) {
     NS_ERROR(nsPrintfCString("Could not load %s", aURL).get());
   }
 }
 
 void
-nsLayoutStylesheetCache::LoadSheetFile(nsIFile* aFile,
-                                       nsRefPtr<CSSStyleSheet>& aSheet,
-                                       SheetParsingMode aParsingMode)
+nsLayoutStylesheetCache::LoadSheetFile(nsIFile* aFile, nsRefPtr<CSSStyleSheet>& aSheet)
 {
   bool exists = false;
   aFile->Exists(&exists);
 
   if (!exists) return;
 
   nsCOMPtr<nsIURI> uri;
   NS_NewFileURI(getter_AddRefs(uri), aFile);
 
-  LoadSheet(uri, aSheet, aParsingMode);
+  LoadSheet(uri, aSheet, false);
 }
 
 static void
 ErrorLoadingBuiltinSheet(nsIURI* aURI, const char* aMsg)
 {
   nsAutoCString spec;
   if (aURI) {
     aURI->GetSpec(spec);
   }
   NS_RUNTIMEABORT(nsPrintfCString("%s loading built-in stylesheet '%s'",
                                   aMsg, spec.get()).get());
 }
 
 void
 nsLayoutStylesheetCache::LoadSheet(nsIURI* aURI,
                                    nsRefPtr<CSSStyleSheet>& aSheet,
-                                   SheetParsingMode aParsingMode)
+                                   bool aEnableUnsafeRules)
 {
   if (!aURI) {
     ErrorLoadingBuiltinSheet(aURI, "null URI");
     return;
   }
 
   if (!gCSSLoader) {
     gCSSLoader = new mozilla::css::Loader();
     NS_IF_ADDREF(gCSSLoader);
     if (!gCSSLoader) {
       ErrorLoadingBuiltinSheet(aURI, "no Loader");
       return;
     }
   }
 
 
-  nsresult rv = gCSSLoader->LoadSheetSync(aURI, aParsingMode, true,
+  nsresult rv = gCSSLoader->LoadSheetSync(aURI, aEnableUnsafeRules, true,
                                           getter_AddRefs(aSheet));
   if (NS_FAILED(rv)) {
     ErrorLoadingBuiltinSheet(aURI,
       nsPrintfCString("LoadSheetSync failed with error %x", rv).get());
   }
 }
 
 /* static */ void
--- a/layout/style/nsLayoutStylesheetCache.h
+++ b/layout/style/nsLayoutStylesheetCache.h
@@ -8,23 +8,25 @@
 #define nsLayoutStylesheetCache_h__
 
 #include "nsIMemoryReporter.h"
 #include "nsIObserver.h"
 #include "nsAutoPtr.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/StaticPtr.h"
-#include "mozilla/css/Loader.h"
 
 class nsIFile;
 class nsIURI;
 
 namespace mozilla {
 class CSSStyleSheet;
+namespace css {
+class Loader;
+} // namespace css
 } // namespace mozilla
 
 class nsLayoutStylesheetCache final
  : public nsIObserver
  , public nsIMemoryReporter
 {
   NS_DECL_ISUPPORTS
   NS_DECL_NSIOBSERVER
@@ -63,22 +65,21 @@ private:
   nsLayoutStylesheetCache();
   ~nsLayoutStylesheetCache();
 
   static void EnsureGlobal();
   void InitFromProfile();
   void InitMemoryReporter();
   static void LoadSheetURL(const char* aURL,
                            nsRefPtr<mozilla::CSSStyleSheet>& aSheet,
-                           mozilla::css::SheetParsingMode aParsingMode);
+                           bool aEnableUnsafeRules);
   static void LoadSheetFile(nsIFile* aFile,
-                            nsRefPtr<mozilla::CSSStyleSheet>& aSheet,
-                            mozilla::css::SheetParsingMode aParsingMode);
+                            nsRefPtr<mozilla::CSSStyleSheet>& aSheet);
   static void LoadSheet(nsIURI* aURI, nsRefPtr<mozilla::CSSStyleSheet>& aSheet,
-                        mozilla::css::SheetParsingMode aParsingMode);
+                        bool aEnableUnsafeRules);
   static void InvalidateSheet(nsRefPtr<mozilla::CSSStyleSheet>& aSheet);
   static void DependentPrefChanged(const char* aPref, void* aData);
   void BuildPreferenceSheet(nsRefPtr<mozilla::CSSStyleSheet>& aSheet,
                             nsPresContext* aPresContext);
   static void AppendPreferenceRule(mozilla::CSSStyleSheet* aSheet,
                                    const nsAString& aRule);
   static void AppendPreferenceColorRule(mozilla::CSSStyleSheet* aSheet,
                                         const char* aString, nscolor aColor);
--- a/layout/style/test/chrome/chrome.ini
+++ b/layout/style/test/chrome/chrome.ini
@@ -3,27 +3,19 @@ skip-if = buildapp == 'b2g' || os == 'an
 support-files =
   bug418986-2.js
   bug535806-css.css
   bug535806-html.html
   bug535806-xul.xul
   hover_helper.html
   match.png
   mismatch.png
-  moz_document_condition_text.css
-  moz_document_nesting.css
-  moz_document_serialization.css
 
 [test_addSheet.html]
 [test_additional_sheets.html]
 [test_author_specified_style.html]
 [test_bug418986-2.xul]
 [test_bug1157097.html]
 [test_bug1160724.xul]
 [test_bug535806.xul]
 [test_hover.html]
 skip-if = buildapp == 'mulet'
-[test_moz_document_condition_text.html]
-[test_moz_document_crashes.html]
-[test_moz_document_matching.html]
-[test_moz_document_nesting.html]
-[test_moz_document_serialization.html]
-[test_moz_document_usability.html]
+[test_moz_document_rules.html]
deleted file mode 100644
--- a/layout/style/test/chrome/moz_document_condition_text.css
+++ /dev/null
@@ -1,10 +0,0 @@
-/* Bug 814907 (@-moz-document cases) */
-@-moz-document url(http://www.example.com/) {}
-@-moz-document url('http://www.example.com/') {}
-@-moz-document url("http://www.example.com/") {}
-@-moz-document url-prefix('http://www.example.com/') {}
-@-moz-document url-prefix("http://www.example.com/") {}
-@-moz-document domain('example.com') {}
-@-moz-document domain("example.com") {}
-@-moz-document regexp('http://www.w3.org/TR/\\d{4}/[^/]*-CSS2-\\d{8}/') {}
-@-moz-document regexp("http://www.w3.org/TR/\\d{4}/[^/]*-CSS2-\\d{8}/") {}
deleted file mode 100644
--- a/layout/style/test/chrome/moz_document_nesting.css
+++ /dev/null
@@ -1,89 +0,0 @@
-/* formerly test_bug511909.html */
-
-a {
-    font-weight: bold;
-}
-#pink {
-    color: pink;
-}
-
-#green {
-    color: green;
-}
-
-#blue {
-    color: blue;
-}
-
-
-pre {
-    border: 1px solid black;
-}
-
-@-moz-document regexp(".*test_moz_document_nesting.*") {
-    #d {
-        color: pink;
-    }
-}
-
-@media screen {
-    #m {
-        color: green;
-    }
-}
-
-@-moz-document regexp(".*test_moz_document_nesting.*") {
-    @media screen {
-        #dm {
-            color: blue;
-        }
-    }
-}
-
-@media screen {
-    @-moz-document regexp(".*test_moz_document_nesting.*") {
-        #md {
-            color: green;
-        }
-    }
-}
-
-/* syntax error - recover at end of @media block */
-@media print { @-moz-document regexp("not_this_url") , }
-#mx {
-    color: pink;
-}
-
-/* syntax error - recover at end of @-moz-document block */
-@-moz-document regexp("not_this_url") { @media , }
-#mxx {
-    color: blue;
-}
-
-@media screen {
-    @-moz-document regexp(".*test_moz_document_nesting.*") {
-        @media screen {
-            @-moz-document regexp(".*test_moz_document_nesting.*") {
-                @media screen {
-                    #me {
-                        color: blue;
-                    }
-                }
-            }
-        }
-    }
-}
-
-/* formerly reftests/w3c-css/submitted/conditional3/css-supports-027.xht */
-@-moz-document regexp(".*test_moz_document_nesting.*") {
-    @supports (color: green) {
-        #mf { color: green }
-    }
-}
-
-/* formerly reftests/w3c-css/submitted/conditional3/css-supports-028.xht */
-@supports (color: pink) {
-    @-moz-document regexp(".*test_moz_document_nesting.*") {
-        #mg { color: pink }
-    }
-}
deleted file mode 100644
--- a/layout/style/test/chrome/moz_document_serialization.css
+++ /dev/null
@@ -1,9 +0,0 @@
-@-moz-document url(http://www.example.com/) {}
-@-moz-document url('http://www.example.com/') {}
-@-moz-document url("http://www.example.com/") {}
-@-moz-document url-prefix('http://www.example.com/') {}
-@-moz-document url-prefix("http://www.example.com/") {}
-@-moz-document domain('example.com') {}
-@-moz-document domain("example.com") {}
-@-moz-document regexp('http://www.w3.org/TR/\\d{4}/[^/]*-CSS2-\\d{8}/') {}
-@-moz-document regexp("http://www.w3.org/TR/\\d{4}/[^/]*-CSS2-\\d{8}/") {}
deleted file mode 100644
--- a/layout/style/test/chrome/test_moz_document_condition_text.html
+++ /dev/null
@@ -1,61 +0,0 @@
-<!doctype html><html><head><meta charset="utf-8">
-<title>Test for Bug 814907 (@-moz-document cases)</title>
-<!-- Split from test_condition_text.html.
-     This is a chrome test because @-moz-document can only be used
-     from user style sheets.  See bug 1035091. -->
-
-<script type="application/javascript" src="/content/tests/SimpleTest/SimpleTest.js"></script>
-<link rel="stylesheet" type="text/css" href="/content/tests/SimpleTest/test.css"/>
-</head><body>
-  <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=814907">Mozilla Bug 814907</a>
-  <p id="display"></p>
-  <div id="content" style="display: none"></div>
-<pre id="test">
-<script type="application/javascript">
-SimpleTest.waitForExplicitFinish();
-
-var windowUtils =
-    window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-          .getInterface(Components.interfaces.nsIDOMWindowUtils);
-
-var sheetURI =
-    Components.classes["@mozilla.org/network/io-service;1"]
-    .getService(Components.interfaces.nsIIOService)
-    .newURI("moz_document_condition_text.css", null, document.baseURIObject);
-
-var sheet =
-    Components.classes["@mozilla.org/content/style-sheet-service;1"]
-    .getService(Components.interfaces.nsIStyleSheetService)
-    .preloadSheet(sheetURI, Components.interfaces.nsIStyleSheetService.USER_SHEET);
-
-windowUtils.addSheet(sheet, windowUtils.USER_SHEET);
-
-addLoadEvent(function () {
-  var conditions = [
-    "url(\"http://www.example.com/\")",
-    "url(\"http://www.example.com/\")",
-    "url(\"http://www.example.com/\")",
-    "url-prefix(\"http://www.example.com/\")",
-    "url-prefix(\"http://www.example.com/\")",
-    "domain(\"example.com\")",
-    "domain(\"example.com\")",
-    "regexp(\"http://www.w3.org/TR/\\\\d{4}/[^/]*-CSS2-\\\\d{8}/\")",
-    "regexp(\"http://www.w3.org/TR/\\\\d{4}/[^/]*-CSS2-\\\\d{8}/\")",
-  ];
-
-  is(sheet.cssRules.length, conditions.length);
-
-  for (var i = 0; i < sheet.cssRules.length; i++) {
-    var rule = sheet.cssRules[i];
-    is(rule.conditionText, conditions[i], "rule " + i + " has expected conditionText");
-    if (rule.type == CSSRule.MEDIA_RULE) {
-      is(rule.conditionText, rule.media.mediaText, "rule " + i + " conditionText matches media.mediaText");
-    }
-  }
-
-  SimpleTest.finish();
-});
-</script>
-</pre>
-</body>
-</html>
deleted file mode 100644
--- a/layout/style/test/chrome/test_moz_document_crashes.html
+++ /dev/null
@@ -1,53 +0,0 @@
-<!doctype html><html><head><meta charset="UTF-8">
-<title>@-moz-document crash tests</title>
-<!-- This test was formerly known as
-     crashtests/long-url-list-stack-overflow.html and
-     crashtests/495269-2.html.
-
-     This is a chrome mochitest because @-moz-document can only be
-     used from user style sheets.  See bug 1035091. -->
-
-<script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-<link rel="stylesheet" href="chrome://mochikit/content/tests/SimpleTest/test.css">
-
-</head><body>
-<script>
-    // Duplicates the string 2^n times
-    function exp(s, n)
-    {
-        for (var i = 0; i < n; ++i)
-            s += s;
-        return s;
-    }
-
-    var windowUtils =
-        window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-              .getInterface(Components.interfaces.nsIDOMWindowUtils);
-
-    var ios =
-        Components.classes["@mozilla.org/network/io-service;1"]
-        .getService(Components.interfaces.nsIIOService);
-
-    var sss =
-        Components.classes["@mozilla.org/content/style-sheet-service;1"]
-       .getService(Components.interfaces.nsIStyleSheetService);
-
-    var style = "@-moz-document url(http://www.w3.org/)" + exp(", url-prefix(file:///)", 20) + " { }";
-    var url1 = ios.newURI("data:text/css," + style, null, null)
-
-    // should not crash at this point
-    windowUtils.loadSheet(url1, windowUtils.USER_SHEET);
-    ok(true, "long-url-list-stack-overflow: no crash");
-
-    var url2 = ios.newURI("data:text/css,@-moz-document domain(example.com) {}';", null, null);
-
-    var sheet1 = sss.preloadSheet(url2, sss.USER_SHEET);
-    var sheet2 = sss.preloadSheet(url2, sss.USER_SHEET);
-    windowUtils.addSheet(sheet1, windowUtils.USER_SHEET);
-    windowUtils.addSheet(sheet2, windowUtils.USER_SHEET);
-
-    // Force a unique inner for the second linked sheet; should not crash
-    sheet2.cssRules[0];
-    ok(true, "495269-2: no crash");
-</script>
-</body></html>
rename from layout/style/test/chrome/test_moz_document_matching.html
rename to layout/style/test/chrome/test_moz_document_rules.html
deleted file mode 100644
--- a/layout/style/test/chrome/test_moz_document_usability.html
+++ /dev/null
@@ -1,56 +0,0 @@
-<!doctype html><html><head><meta charset="UTF-8">
-<title>@-moz-document usability test (Bug 1035091)</title>
-<!-- Per https://bugzilla.mozilla.org/show_bug.cgi?id=1035091
-     @-moz-document rules can only be used in user and UA style sheets
-     until further notice. -->
-
-<script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-<link rel="stylesheet" href="chrome://mochikit/content/tests/SimpleTest/test.css">
-
-<style>
-  #green  { color: green }
-  #author { color: green }
-  #user   { color: red }
-  #agent  { color: red }
-</style>
-</head><body>
-
-<p id="green">All text should be green.</p>
-<p id="author">All text should be green.</p>
-<p id="user">All text should be green.</p>
-<p id="agent">All text should be green.</p>
-
-<script>
-    SimpleTest.waitForExplicitFinish();
-    var wu =
-        window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-              .getInterface(Components.interfaces.nsIDOMWindowUtils);
-
-    var ios =
-        Components.classes["@mozilla.org/network/io-service;1"]
-        .getService(Components.interfaces.nsIIOService);
-
-    function makeSheet(whom, color) {
-        return ios.newURI(
-          "data:text/css,@-moz-document regexp('.*test_moz_document.*') {" +
-          "%23" + whom + " { color: " + color + "!important } }",
-          null, null);
-    }
-    wu.loadSheet(makeSheet("author", "red"),   wu.AUTHOR_SHEET);
-    wu.loadSheet(makeSheet("user",   "green"), wu.USER_SHEET);
-    wu.loadSheet(makeSheet("agent",  "green"), wu.AGENT_SHEET);
-
-    addLoadEvent(function () {
-        var green  = getComputedStyle(document.getElementById("green"),  "").color;
-        var author = getComputedStyle(document.getElementById("author"), "").color;
-        var user   = getComputedStyle(document.getElementById("user"),   "").color;
-        var agent  = getComputedStyle(document.getElementById("agent"),  "").color;
-
-        is(author, green, "@-moz-document should not be honored in author sheets");
-        is(user,   green, "@-moz-document should be honored in user sheets");
-        is(agent,  green, "@-moz-document should be honored in agent sheets");
-
-        SimpleTest.finish();
-    });
-</script>
-</body></html>
--- a/layout/style/test/mochitest.ini
+++ b/layout/style/test/mochitest.ini
@@ -88,16 +88,17 @@ skip-if = android_version == '18' # bug 
 [test_bug418986-2.html]
 [test_bug437915.html]
 [test_bug450191.html]
 [test_bug453896_deck.html]
 support-files = bug453896_iframe.html
 [test_bug470769.html]
 [test_bug499655.html]
 [test_bug499655.xhtml]
+[test_bug511909.html]
 [test_bug517224.html]
 support-files = bug517224.sjs
 [test_bug524175.html]
 [test_bug525952.html]
 [test_bug534804.html]
 [test_bug573255.html]
 [test_bug580685.html]
 [test_bug621351.html]
@@ -214,16 +215,17 @@ skip-if = (toolkit == 'gonk' && debug) #
 skip-if = (toolkit == 'gonk' && debug) || e10s #debug-only failure
 [test_pseudoelement_parsing.html]
 [test_redundant_font_download.html]
 support-files = redundant_font_download.sjs
 [test_rem_unit.html]
 [test_root_node_display.html]
 [test_rule_insertion.html]
 skip-if = (buildapp == 'b2g' && (toolkit != 'gonk' || debug)) # b2g-debug(monospace and serif text have sufficiently different widths) b2g-desktop(monospace and serif text have sufficiently different widths)
+[test_rule_serialization.html]
 [test_rules_out_of_sheets.html]
 [test_selectors.html]
 skip-if = (toolkit == 'gonk' && debug) || toolkit == 'android' #bug 775227 #debug-only failure; timed out
 [test_selectors_on_anonymous_content.html]
 [test_setPropertyWithNull.html]
 [test_shorthand_property_getters.html]
 [test_specified_value_serialization.html]
 [test_style_attribute_quirks.html]
rename from layout/style/test/chrome/test_moz_document_nesting.html
rename to layout/style/test/test_bug511909.html
--- a/layout/style/test/chrome/test_moz_document_nesting.html
+++ b/layout/style/test/test_bug511909.html
@@ -1,120 +1,205 @@
-<!doctype html><html><head><meta charset="UTF-8">
+<html><!--
+   https://bugzilla.mozilla.org/show_bug.cgi?id=511909
+   --><head>
+<meta http-equiv="content-type" content="text/html; charset=UTF-8">
 <title>@media and @-moz-document testcases</title>
-<!-- This test was formerly known as test_bug511909.html.
-     This is a chrome test because @-moz-document can only be used
-     from user style sheets.  See bug 1035091. -->
+  
+<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
+
+<style type="text/css">
+a {
+    font-weight: bold; 
+}
+  #pink {
+    color: pink;
+  }
+  
+  #green {
+    color: green;
+  }
+  
+  #blue {
+    color: blue;
+  }
+
+
+pre {
+   border: 1px solid black;
+}
+</style>
+  
+<style type="text/css">
+@-moz-document regexp(".*test_bug511909.*"){
+    #d {
+      color: pink;
+    }
+}
+
+</style>
+  
+<style type="text/css">
+    
+@media screen {
+   #m {
+      color: green;
+   }
+}
+
+</style>
+  
+<style type="text/css">
+  
+@-moz-document regexp(".*test_bug511909.*"){
+  @media screen {
+      #dm {
+         color: blue;
+      }
+   }
+}
 
-<script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-<link rel="stylesheet" href="chrome://mochikit/content/tests/SimpleTest/test.css">
+</style>
+  
+<!-- should parse -->
+<style type="text/css">
+
+@media print {
+  @-moz-document regexp("not_this_url"),}
+    #mx {
+        color: pink;
+    }
+  }
+}
+
+</style>
+  
+<!-- should parse -->
+<style type="text/css">
+    
+@-moz-document regexp("not_this_url"){
+  @media print ,}
+    #mxx {
+      color: blue;
+    }
+  }
+}
 
-</head><body>
-<script>
+</style>
+  
+<style type="text/css">  
+  
+@media screen {
+  @-moz-document regexp(".*test_bug511909.*"){
+      #md {
+         color: green;
+      }
+   }
+}
+
+</style>
+  
+<style type="text/css">
+    
+@media screen {
+  @-moz-document regexp(".*test_bug511909.*"){
+      @media screen { 
+        @-moz-document regexp(".*test_bug511909.*"){
+          @media screen {
+            #me {
+             color: blue; 
+            }
+          }
+        }
+     }
+   }
+}
+  
+</style>
+</head>
+<body>
+  <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=511909">Mozilla Bug 511909</a>
+  <p id="display"></p>
+  <div id="content" style="display: none">
+    
+  </div>
+  
+  <script class="testbody" type="text/javascript">
+
     SimpleTest.waitForExplicitFinish();
-
-    var windowUtils =
-        window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-              .getInterface(Components.interfaces.nsIDOMWindowUtils);
-
-    var sheetURI =
-        Components.classes["@mozilla.org/network/io-service;1"]
-        .getService(Components.interfaces.nsIIOService)
-        .newURI("moz_document_nesting.css", null, document.baseURIObject);
-
-    windowUtils.loadSheet(sheetURI, windowUtils.USER_SHEET);
-
+    
     addLoadEvent(function() {
-      var pink = getComputedStyle(document.getElementById("pink"), "");
-      var green = getComputedStyle(document.getElementById("green"), "");
-      var blue = getComputedStyle(document.getElementById("blue"), "");
-
-      var cs1 = getComputedStyle(document.getElementById("d"), "");
-      var cs2 = getComputedStyle(document.getElementById("m"), "");
-      var cs3 = getComputedStyle(document.getElementById("dm"), "");
-      var cs4 = getComputedStyle(document.getElementById("md"), "");
-      var cs5 = getComputedStyle(document.getElementById("mx"), "");
-      var cs6 = getComputedStyle(document.getElementById("mxx"), "");
-      var cs7 = getComputedStyle(document.getElementById("me"), "");
-      var cs8 = getComputedStyle(document.getElementById("mf"), "");
-      var cs9 = getComputedStyle(document.getElementById("mg"), "");
-
-      is(cs1.color, pink.color, "@-moz-document applies");
-      is(cs2.color, green.color, "@media applies");
-      is(cs3.color, blue.color, "@media nested in @-moz-document applies");
-      is(cs4.color, green.color, "@-moz-document nested in @media applies");
-      is(cs5.color, pink.color, "broken @media nested in @-moz-document correctly handled");
-      is(cs6.color, blue.color, "broken @-moz-document nested in @media correctly handled");
-      is(cs7.color, blue.color, "@media nested in @-moz-document nested in @media applies");
-      is(cs8.color, green.color, "@supports nested in @-moz-document applies");
-      is(cs9.color, pink.color, "@-moz-document nested in @supports applies");
-
-      SimpleTest.finish();
+    var pink = getComputedStyle(document.getElementById("pink"), "");
+    var green = getComputedStyle(document.getElementById("green"), "");
+    var blue = getComputedStyle(document.getElementById("blue"), "");
+                 
+    var cs1 = getComputedStyle(document.getElementById("d"), "");
+    var cs2 = getComputedStyle(document.getElementById("m"), "");
+    var cs3 = getComputedStyle(document.getElementById("dm"), "");
+    var cs4 = getComputedStyle(document.getElementById("md"), "");
+    var cs5 = getComputedStyle(document.getElementById("mx"), "");                 
+    var cs6 = getComputedStyle(document.getElementById("mxx"), "");                  
+    var cs7 = getComputedStyle(document.getElementById("me"), "");  
+                 
+    is(cs1.color, pink.color, "@-moz-document applies");
+    is(cs2.color, green.color, "@media applies");
+    is(cs3.color, blue.color, "@media nested in @-moz-document applies");
+    is(cs4.color, green.color, "@-moz-document nested in @media applies");
+    is(cs5.color, pink.color, "broken @media nested in @-moz-document correctly handled");      
+    is(cs6.color, blue.color, "broken @-moz-document nested in @media correctly handled");   
+    is(cs7.color, blue.color, "@media nested in @-moz-document nested in @media applies");
+    SimpleTest.finish();
     });
-</script>
-
+  </script>
+<div>
 <pre>default style
 </pre>
 <a id="pink">This line should be pink</a><br>
+  
 <a id="green">This line should be green</a><br>
+  
 <a id="blue">This line should be blue</a><br>
-
+  
 <pre>@-moz-document {...}
 </pre>
 <a id="d">This line should be pink</a><br>
-
 <pre>@media screen {...}
 </pre>
 <a id="m">This line should be green</a><br>
-
 <pre>@-moz-document {
    @media screen {...}
 }
 </pre>
 <a id="dm">This line should be blue</a><br>
-
 <pre>@media print {
   @-moz-document regexp("not_this_url"),}
     #mx {
         color: pink;
     }
   }
 }
 </pre>
 <a id="mx">This line should be pink</a><br></div>
-
 <pre>@-moz-document regexp("not_this_url"){
   @media print ,}
     #mxx {
       color: blue;
     }
   }
 }
 </pre>
 <a id="mxx">This line should be blue</a><br>
-
 <pre>@media screen {
-  @-moz-document {...}
+  @-moz-documen {...}
 }
 </pre>
 <a id="md">This line should be green</a><br>
-
 <pre>@media screen {
   @-moz-document {
     @media screen {...}
   }
 }
 </pre>
 <a id="me">This line should be blue</a><br>
 
-<pre>@-moz-document {
-  @supports { ... }
-}
-</pre>
-<a id="mf">This line should be green</a><br>
-
-<pre>@supports {
-  @-moz-document { ... }
-}
-</pre>
-<a id="mg">This line should be pink</a><br>
 
 </body></html>
--- a/layout/style/test/test_condition_text.html
+++ b/layout/style/test/test_condition_text.html
@@ -3,16 +3,26 @@
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=814907
 -->
 <head>
   <title>Test for Bug 814907</title>
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
   <style id="style">
+    @-moz-document url(http://www.example.com/) {}
+    @-moz-document url('http://www.example.com/') {}
+    @-moz-document url("http://www.example.com/") {}
+    @-moz-document url-prefix('http://www.example.com/') {}
+    @-moz-document url-prefix("http://www.example.com/") {}
+    @-moz-document domain('example.com') {}
+    @-moz-document domain("example.com") {}
+    @-moz-document regexp('http://www.w3.org/TR/\\d{4}/[^/]*-CSS2-\\d{8}/') {}
+    @-moz-document regexp("http://www.w3.org/TR/\\d{4}/[^/]*-CSS2-\\d{8}/") {}
+
     @media all {}
     @media only color {}
     @media (color ) {}
     @media color \0061ND ( monochrome ) {}
     @media (max-width: 200px), (color) {}
 
     @supports(color: green){}
     @supports (color: green) {}
@@ -27,39 +37,57 @@ https://bugzilla.mozilla.org/show_bug.cg
 <div id="content" style="display: none">
 
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 814907 **/
 
-var style = document.getElementById("style");
-style.textContent += " ";
+function runTest()
+{
+  // re-parse the style sheet with the pref turned on
+  var style = document.getElementById("style");
+  style.textContent += " ";
 
-var sheet = style.sheet;
+  var sheet = style.sheet;
 
-var conditions = [
-  "all",
-  "only color",
-  "(color)",
-  "color and (monochrome)",
-  "(max-width: 200px), (color)",
-  "(color: green)",
-  "(color: green)",
-  "((color: green))",
-  "(color: green) and (color: blue)",
-  "( Font:  20px serif ! Important)"
-];
+  var conditions = [
+    "url(\"http://www.example.com/\")",
+    "url(\"http://www.example.com/\")",
+    "url(\"http://www.example.com/\")",
+    "url-prefix(\"http://www.example.com/\")",
+    "url-prefix(\"http://www.example.com/\")",
+    "domain(\"example.com\")",
+    "domain(\"example.com\")",
+    "regexp(\"http://www.w3.org/TR/\\\\d{4}/[^/]*-CSS2-\\\\d{8}/\")",
+    "regexp(\"http://www.w3.org/TR/\\\\d{4}/[^/]*-CSS2-\\\\d{8}/\")",
+    "all",
+    "only color",
+    "(color)",
+    "color and (monochrome)",
+    "(max-width: 200px), (color)",
+    "(color: green)",
+    "(color: green)",
+    "((color: green))",
+    "(color: green) and (color: blue)",
+    "( Font:  20px serif ! Important)"
+  ];
 
-is(sheet.cssRules.length, conditions.length);
+  is(sheet.cssRules.length, conditions.length);
 
-for (var i = 0; i < sheet.cssRules.length; i++) {
-  var rule = sheet.cssRules[i];
-  is(rule.conditionText, conditions[i], "rule " + i + " has expected conditionText");
-  if (rule.type == CSSRule.MEDIA_RULE) {
-    is(rule.conditionText, rule.media.mediaText, "rule " + i + " conditionText matches media.mediaText");
+  for (var i = 0; i < sheet.cssRules.length; i++) {
+    var rule = sheet.cssRules[i];
+    is(rule.conditionText, conditions[i], "rule " + i + " has expected conditionText");
+    if (rule.type == CSSRule.MEDIA_RULE) {
+      is(rule.conditionText, rule.media.mediaText, "rule " + i + " conditionText matches media.mediaText");
+    }
   }
+
+  SimpleTest.finish();
 }
+
+SimpleTest.waitForExplicitFinish();
+runTest();
 </script>
 </pre>
 </body>
 </html>
--- a/layout/style/test/test_css_eof_handling.html
+++ b/layout/style/test/test_css_eof_handling.html
@@ -178,16 +178,26 @@ const tests = [
       ref: "@namespace 'http://foo.example.com/';",
       tst: "@namespace 'http://foo.example.com/'"
   },
   {
       name: "@namespace 2e",
       ref: "@namespace 'http://foo.example.com/';",
       tst: "@namespace 'http://foo.example.com/"
   },
+  {
+      name: "@-moz-document 1",
+      ref: "@-moz-document domain('example.com') {}",
+      tst: "@-moz-document domain('example.com') {"
+  },
+  {
+      name: "@-moz-document 2",
+      ref: "@-moz-document domain('example.com') { p {} }",
+      tst: "@-moz-document domain('example.com') { p {"
+  }
 ];
 
 const basestyle = ("table {\n"+
 		   "    border-collapse: collapse;\n"+
 		   "}\n"+
 		   "td {\n"+
 		   "    width: 1.5em;\n"+
 		   "    height: 1.5em;\n"+
--- a/layout/style/test/test_rule_insertion.html
+++ b/layout/style/test/test_rule_insertion.html
@@ -64,16 +64,17 @@ var controlCJKDecimal = document.getElem
 var testCounterStyle = document.getElementById("test-counter-style");
 
 var decimalWidth = controlDecimal.getBoundingClientRect().width;
 var cjkDecimalWidth = controlCJKDecimal.getBoundingClientRect().width;
 
 // [at-rule type, passing condition, failing condition]
 var outerRuleInfo = [
   ["@media", "all", "not all"],
+  ["@-moz-document", "url-prefix('')", "url-prefix('zzz')"],
   ["@supports", "(color: green)", "(unknown: unknown)"]
 ];
 
 // [rule, function to test whether the rule was successfully inserted and applied]
 var innerRuleInfo = [
   ["#test { text-decoration: underline; }",
    function(aApplied, aParent, aException) {
      return !aException &&
rename from layout/style/test/chrome/test_moz_document_serialization.html
rename to layout/style/test/test_rule_serialization.html
--- a/layout/style/test/chrome/test_moz_document_serialization.html
+++ b/layout/style/test/test_rule_serialization.html
@@ -1,50 +1,53 @@
-<!doctype html><html><head><meta charset="utf-8">
-<title>Test for reserialization of @-moz-document rules</title>
-<!-- This is a chrome test because @-moz-document can only be used
-     from user style sheets.  See bug 1035091. -->
-
-<script type="application/javascript" src="/content/tests/SimpleTest/SimpleTest.js"></script>
-<link rel="stylesheet" type="text/css" href="/content/tests/SimpleTest/test.css"/>
-
-</head><body>
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=
+-->
+<head>
+  <title>Test for Bug </title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <style type="text/css" id="style"></style>
+</head>
+<body>
+<pre id="test">
 <script type="application/javascript">
-    SimpleTest.waitForExplicitFinish();
-
-    var windowUtils =
-        window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-              .getInterface(Components.interfaces.nsIDOMWindowUtils);
-
-    var sheetURI =
-        Components.classes["@mozilla.org/network/io-service;1"]
-        .getService(Components.interfaces.nsIIOService)
-        .newURI("moz_document_serialization.css", null, document.baseURIObject);
 
-    var sheet =
-        Components.classes["@mozilla.org/content/style-sheet-service;1"]
-        .getService(Components.interfaces.nsIStyleSheetService)
-        .preloadSheet(sheetURI, Components.interfaces.nsIStyleSheetService.USER_SHEET);
+var rules = [
+  { rule: "@-moz-document url(http://www.example.com/) {}" },
+  { rule: "@-moz-document url('http://www.example.com/') {}" },
+  { rule: '@-moz-document url("http://www.example.com/") {}' },
+  { rule: "@-moz-document url-prefix('http://www.example.com/') {}" },
+  { rule: '@-moz-document url-prefix("http://www.example.com/") {}' },
+  { rule: "@-moz-document domain('example.com') {}" },
+  { rule: '@-moz-document domain("example.com") {}' },
+  { rule: "@-moz-document regexp('http://www.w3.org/TR/\\d{4}/[^/]*-CSS2-\\d{8}/') {}" },
+  { rule: '@-moz-document regexp("http://www.w3.org/TR/\\d{4}/[^/]*-CSS2-\\d{8}/") {}' },
+];
 
-    windowUtils.addSheet(sheet, windowUtils.USER_SHEET);
+var style = document.getElementById("style");
+var style_text = document.createTextNode("");
+style.appendChild(style_text);
 
-    var rules = [
-        '@-moz-document url("http://www.example.com/") {\n}',
-        '@-moz-document url("http://www.example.com/") {\n}',
-        '@-moz-document url("http://www.example.com/") {\n}',
-        '@-moz-document url-prefix("http://www.example.com/") {\n}',
-        '@-moz-document url-prefix("http://www.example.com/") {\n}',
-        '@-moz-document domain("example.com") {\n}',
-        '@-moz-document domain("example.com") {\n}',
-        '@-moz-document regexp("http://www.w3.org/TR/\\\\d{4}/[^/]*-CSS2-\\\\d{8}/") {\n}',
-        '@-moz-document regexp("http://www.w3.org/TR/\\\\d{4}/[^/]*-CSS2-\\\\d{8}/") {\n}',
-    ];
+for (var i in rules) {
+  var obj = rules[i];
+  var rule = obj.rule;
 
-    addLoadEvent(function () {
-        is(sheet.cssRules.length, rules.length, "number of rules");
-        for (var i = 0; i < rules.length; i++) {
-            is(sheet.cssRules[i].cssText, rules[i], "serialization for rule " + i);
-        }
-        SimpleTest.finish();
-    });
+  style_text.data = rule;
+  is(style.sheet.cssRules.length, 1, "should have one rule");
+  var ser1 = style.sheet.cssRules[0].cssText;
+  if ("is_canonical" in obj) {
+    is(ser1, rule, "rule '" + rule + "' should serialize to itself");
+  }
+
+  style_text.data = ser1;
+  is(style.sheet.cssRules.length, 1, "should have one rule");
+  var ser2 = style.sheet.cssRules[0].cssText;
+  is(ser2, ser1,
+     "parse+serialize for rule '" + rule + "' should be idempotent");
+}
+
 </script>
+</pre>
 </body>
 </html>