servo: Merge #18967 - Bump bitflags to 1.0 (from Eijebong:bitflags2.0); r=mbrubeck
authorBastien Orivel <eijebong@bananium.fr>
Mon, 30 Oct 2017 18:25:45 -0500
changeset 389253 9723ad4dc43b13dad3db0ffd65893d5ae5a86a18
parent 389252 fae4ad05256fa6b0188cd3570e91c264e0de06dc
child 389254 401840a241b9861cac205bd866ba24e69d11b7e2
push id96819
push useracraciun@mozilla.com
push dateTue, 31 Oct 2017 10:54:52 +0000
treeherdermozilla-inbound@2eb64f1369c6 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmbrubeck
milestone58.0a1
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
servo: Merge #18967 - Bump bitflags to 1.0 (from Eijebong:bitflags2.0); r=mbrubeck See #18809 Still haven't had time to test it but it should fix the tests failures that appeared in m-c Source-Repo: https://github.com/servo/servo Source-Revision: fe4139b779b3af749ec1426ddf4e1393c7b85442
servo/Cargo.lock
servo/components/bluetooth/Cargo.toml
servo/components/bluetooth/lib.rs
servo/components/devtools/actors/console.rs
servo/components/devtools_traits/Cargo.toml
servo/components/devtools_traits/lib.rs
servo/components/gfx/Cargo.toml
servo/components/gfx/font.rs
servo/components/gfx/text/shaping/harfbuzz.rs
servo/components/gfx/text/text_run.rs
servo/components/layout/Cargo.toml
servo/components/layout/block.rs
servo/components/layout/construct.rs
servo/components/layout/data.rs
servo/components/layout/display_list_builder.rs
servo/components/layout/flex.rs
servo/components/layout/floats.rs
servo/components/layout/flow.rs
servo/components/layout/fragment.rs
servo/components/layout/generated_content.rs
servo/components/layout/incremental.rs
servo/components/layout/inline.rs
servo/components/layout/list_item.rs
servo/components/layout/query.rs
servo/components/layout/sequential.rs
servo/components/layout/table.rs
servo/components/layout/table_cell.rs
servo/components/layout/table_row.rs
servo/components/layout/table_rowgroup.rs
servo/components/layout/table_wrapper.rs
servo/components/layout/text.rs
servo/components/layout/traversal.rs
servo/components/layout/wrapper.rs
servo/components/layout_thread/dom_wrapper.rs
servo/components/layout_thread/lib.rs
servo/components/msg/Cargo.toml
servo/components/msg/constellation_msg.rs
servo/components/script/Cargo.toml
servo/components/script/devtools.rs
servo/components/script/dom/bindings/cell.rs
servo/components/script/dom/bindings/codegen/CodegenRust.py
servo/components/script/dom/css.rs
servo/components/script/dom/cssmediarule.rs
servo/components/script/dom/cssstyledeclaration.rs
servo/components/script/dom/csssupportsrule.rs
servo/components/script/dom/dedicatedworkerglobalscope.rs
servo/components/script/dom/document.rs
servo/components/script/dom/element.rs
servo/components/script/dom/htmlbuttonelement.rs
servo/components/script/dom/htmlelement.rs
servo/components/script/dom/htmlfieldsetelement.rs
servo/components/script/dom/htmlformelement.rs
servo/components/script/dom/htmliframeelement.rs
servo/components/script/dom/htmlinputelement.rs
servo/components/script/dom/htmllinkelement.rs
servo/components/script/dom/htmloptgroupelement.rs
servo/components/script/dom/htmloptionelement.rs
servo/components/script/dom/htmlselectelement.rs
servo/components/script/dom/htmlstyleelement.rs
servo/components/script/dom/htmltextareaelement.rs
servo/components/script/dom/keyboardevent.rs
servo/components/script/dom/medialist.rs
servo/components/script/dom/node.rs
servo/components/script/dom/serviceworkerglobalscope.rs
servo/components/script/dom/validitystate.rs
servo/components/script/dom/webglrenderingcontext.rs
servo/components/script/dom/window.rs
servo/components/script/dom/worklet.rs
servo/components/script/lib.rs
servo/components/script/script_runtime.rs
servo/components/script/script_thread.rs
servo/components/script/textinput.rs
servo/components/selectors/Cargo.toml
servo/components/selectors/matching.rs
servo/components/style/Cargo.toml
servo/components/style/context.rs
servo/components/style/data.rs
servo/components/style/dom.rs
servo/components/style/element_state.rs
servo/components/style/gecko/pseudo_element.rs
servo/components/style/gecko/selector_parser.rs
servo/components/style/gecko/wrapper.rs
servo/components/style/gecko_bindings/sugar/origin_flags.rs
servo/components/style/invalidation/element/collector.rs
servo/components/style/invalidation/element/invalidation_map.rs
servo/components/style/invalidation/element/restyle_hints.rs
servo/components/style/invalidation/stylesheets.rs
servo/components/style/logical_geometry.rs
servo/components/style/matching.rs
servo/components/style/parser.rs
servo/components/style/properties/computed_value_flags.rs
servo/components/style/properties/declaration_block.rs
servo/components/style/properties/gecko.mako.rs
servo/components/style/properties/longhand/box.mako.rs
servo/components/style/properties/longhand/font.mako.rs
servo/components/style/properties/longhand/text.mako.rs
servo/components/style/properties/properties.mako.rs
servo/components/style/servo/restyle_damage.rs
servo/components/style/servo/selector_parser.rs
servo/components/style/style_adjuster.rs
servo/components/style/style_resolver.rs
servo/components/style/stylesheets/keyframes_rule.rs
servo/components/style/stylesheets/mod.rs
servo/components/style/stylesheets/origin.rs
servo/components/style/stylesheets/stylesheet.rs
servo/components/style/stylist.rs
servo/components/style/thread_state.rs
servo/components/style/traversal.rs
servo/components/style/traversal_flags.rs
servo/components/style/values/computed/align.rs
servo/components/style/values/specified/align.rs
servo/components/style/values/specified/time.rs
servo/components/style_traits/Cargo.toml
servo/components/style_traits/lib.rs
servo/components/style_traits/viewport.rs
servo/components/webdriver_server/keys.rs
servo/ports/cef/browser_host.rs
servo/ports/geckolib/glue.rs
servo/ports/glutin/Cargo.toml
servo/ports/glutin/window.rs
servo/support/gecko/nsstring/Cargo.toml
servo/support/gecko/nsstring/src/lib.rs
servo/tests/unit/script/textinput.rs
servo/tests/unit/style/logical_geometry.rs
servo/tests/unit/style/parsing/length.rs
servo/tests/unit/style/parsing/mod.rs
servo/tests/unit/style/parsing/value.rs
servo/tests/unit/style/properties/mod.rs
servo/tests/unit/style/rule_tree/bench.rs
servo/tests/unit/style/stylist.rs
servo/tests/unit/style/viewport.rs
--- a/servo/Cargo.lock
+++ b/servo/Cargo.lock
@@ -1,18 +1,8 @@
-[root]
-name = "webvr_traits"
-version = "0.0.1"
-dependencies = [
- "ipc-channel 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
- "msg 0.0.1",
- "rust-webvr-api 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)",
- "serde 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)",
-]
-
 [[package]]
 name = "adler32"
 version = "1.0.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 
 [[package]]
 name = "aho-corasick"
 version = "0.6.3"
@@ -205,17 +195,17 @@ source = "registry+https://github.com/ru
 name = "block"
 version = "0.1.6"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 
 [[package]]
 name = "bluetooth"
 version = "0.0.1"
 dependencies = [
- "bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bitflags 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "bluetooth_traits 0.0.1",
  "device 0.0.1 (git+https://github.com/servo/devices)",
  "ipc-channel 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "servo_config 0.0.1",
  "servo_rand 0.0.1",
  "tinyfiledialogs 2.5.9 (registry+https://github.com/rust-lang/crates.io-index)",
  "uuid 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
@@ -712,17 +702,17 @@ dependencies = [
  "serde_json 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
  "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
 name = "devtools_traits"
 version = "0.0.1"
 dependencies = [
- "bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bitflags 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)",
  "hyper_serde 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "ipc-channel 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "malloc_size_of 0.0.1",
  "malloc_size_of_derive 0.0.1",
  "msg 0.0.1",
  "serde 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)",
  "servo_url 0.0.1",
@@ -1086,17 +1076,17 @@ name = "getopts"
 version = "0.2.14"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 
 [[package]]
 name = "gfx"
 version = "0.0.1"
 dependencies = [
  "app_units 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
- "bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bitflags 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "byteorder 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "core-foundation 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)",
  "core-graphics 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)",
  "core-text 7.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "dwrote 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "euclid 0.15.3 (registry+https://github.com/rust-lang/crates.io-index)",
  "fnv 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
  "fontsan 0.4.0 (git+https://github.com/servo/fontsan)",
@@ -1185,17 +1175,17 @@ dependencies = [
 name = "glob"
 version = "0.2.11"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 
 [[package]]
 name = "glutin_app"
 version = "0.0.1"
 dependencies = [
- "bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bitflags 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "compositing 0.0.1",
  "euclid 0.15.3 (registry+https://github.com/rust-lang/crates.io-index)",
  "gdi32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "gleam 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)",
  "libservo 0.0.1",
  "log 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)",
  "msg 0.0.1",
  "net_traits 0.0.1",
@@ -1515,17 +1505,17 @@ version = "0.2.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 
 [[package]]
 name = "layout"
 version = "0.0.1"
 dependencies = [
  "app_units 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
  "atomic_refcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
- "bitflags 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bitflags 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "canvas_traits 0.0.1",
  "euclid 0.15.3 (registry+https://github.com/rust-lang/crates.io-index)",
  "fnv 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
  "gfx 0.0.1",
  "gfx_traits 0.0.1",
  "html5ever 0.21.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "ipc-channel 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "libc 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -1927,17 +1917,17 @@ dependencies = [
  "bitreader 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "byteorder 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
 name = "msg"
 version = "0.0.1"
 dependencies = [
- "bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bitflags 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "malloc_size_of 0.0.1",
  "malloc_size_of_derive 0.0.1",
  "nonzero 0.0.1",
  "serde 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)",
  "webrender_api 0.53.1 (git+https://github.com/servo/webrender)",
 ]
 
 [[package]]
@@ -2081,17 +2071,17 @@ version = "0.0.1"
 dependencies = [
  "serde 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
 name = "nsstring"
 version = "0.1.0"
 dependencies = [
- "bitflags 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bitflags 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
 name = "num-integer"
 version = "0.1.34"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 dependencies = [
  "num-traits 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -2602,17 +2592,17 @@ source = "registry+https://github.com/ru
 [[package]]
 name = "script"
 version = "0.0.1"
 dependencies = [
  "angle 0.5.0 (git+https://github.com/servo/angle?branch=servo)",
  "app_units 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
  "audio-video-metadata 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
  "base64 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)",
- "bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bitflags 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "bluetooth_traits 0.0.1",
  "byteorder 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "canvas_traits 0.0.1",
  "caseless 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
  "cmake 0.1.22 (registry+https://github.com/rust-lang/crates.io-index)",
  "cookie 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)",
  "cssparser 0.22.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "deny_public_fields 0.0.1",
@@ -2757,17 +2747,17 @@ dependencies = [
  "webrender_api 0.53.1 (git+https://github.com/servo/webrender)",
  "webvr_traits 0.0.1",
 ]
 
 [[package]]
 name = "selectors"
 version = "0.19.0"
 dependencies = [
- "bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bitflags 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "cssparser 0.22.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "fnv 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
  "log 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)",
  "malloc_size_of 0.0.1",
  "malloc_size_of_derive 0.0.1",
  "matches 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
  "phf 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)",
  "phf_codegen 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -3157,17 +3147,17 @@ source = "registry+https://github.com/ru
 [[package]]
 name = "style"
 version = "0.0.1"
 dependencies = [
  "app_units 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
  "arrayvec 0.3.23 (registry+https://github.com/rust-lang/crates.io-index)",
  "atomic_refcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "bindgen 0.29.1 (registry+https://github.com/rust-lang/crates.io-index)",
- "bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bitflags 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "byteorder 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "cfg-if 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
  "cssparser 0.22.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "encoding 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)",
  "euclid 0.15.3 (registry+https://github.com/rust-lang/crates.io-index)",
  "fallible 0.0.1",
  "fnv 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
  "hashglobe 0.1.0",
@@ -3240,17 +3230,17 @@ dependencies = [
  "style_traits 0.0.1",
 ]
 
 [[package]]
 name = "style_traits"
 version = "0.0.1"
 dependencies = [
  "app_units 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
- "bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bitflags 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "cssparser 0.22.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "euclid 0.15.3 (registry+https://github.com/rust-lang/crates.io-index)",
  "malloc_size_of 0.0.1",
  "malloc_size_of_derive 0.0.1",
  "selectors 0.19.0",
  "serde 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)",
  "servo_arc 0.0.1",
  "servo_atoms 0.0.1",
@@ -3679,16 +3669,26 @@ dependencies = [
  "msg 0.0.1",
  "rust-webvr 0.9.4 (registry+https://github.com/rust-lang/crates.io-index)",
  "script_traits 0.0.1",
  "servo_config 0.0.1",
  "webvr_traits 0.0.1",
 ]
 
 [[package]]
+name = "webvr_traits"
+version = "0.0.1"
+dependencies = [
+ "ipc-channel 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "msg 0.0.1",
+ "rust-webvr-api 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)",
+ "serde 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
 name = "winapi"
 version = "0.2.8"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 
 [[package]]
 name = "winapi-build"
 version = "0.1.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
--- a/servo/components/bluetooth/Cargo.toml
+++ b/servo/components/bluetooth/Cargo.toml
@@ -5,17 +5,17 @@ authors = ["The Servo Project Developers
 license = "MPL-2.0"
 publish = false
 
 [lib]
 name = "bluetooth"
 path = "lib.rs"
 
 [dependencies]
-bitflags = "0.7"
+bitflags = "1.0"
 bluetooth_traits = {path = "../bluetooth_traits"}
 device = {git = "https://github.com/servo/devices", features = ["bluetooth-test"]}
 ipc-channel = "0.9"
 servo_config = {path = "../config"}
 servo_rand = {path = "../rand"}
 uuid = {version = "0.5", features = ["v4"]}
 
 [target.'cfg(target_os = "linux")'.dependencies]
--- a/servo/components/bluetooth/lib.rs
+++ b/servo/components/bluetooth/lib.rs
@@ -42,26 +42,26 @@ const DISCOVERY_TIMEOUT_MS: u64 = 1500;
 #[cfg(target_os = "linux")]
 const DIALOG_TITLE: &'static str = "Choose a device";
 #[cfg(target_os = "linux")]
 const DIALOG_COLUMN_ID: &'static str = "Id";
 #[cfg(target_os = "linux")]
 const DIALOG_COLUMN_NAME: &'static str = "Name";
 
 bitflags! {
-    flags Flags: u32 {
-        const BROADCAST                   = 0b000000001,
-        const READ                        = 0b000000010,
-        const WRITE_WITHOUT_RESPONSE      = 0b000000100,
-        const WRITE                       = 0b000001000,
-        const NOTIFY                      = 0b000010000,
-        const INDICATE                    = 0b000100000,
-        const AUTHENTICATED_SIGNED_WRITES = 0b001000000,
-        const RELIABLE_WRITE              = 0b010000000,
-        const WRITABLE_AUXILIARIES        = 0b100000000,
+    struct Flags: u32 {
+        const BROADCAST                   = 0b000000001;
+        const READ                        = 0b000000010;
+        const WRITE_WITHOUT_RESPONSE      = 0b000000100;
+        const WRITE                       = 0b000001000;
+        const NOTIFY                      = 0b000010000;
+        const INDICATE                    = 0b000100000;
+        const AUTHENTICATED_SIGNED_WRITES = 0b001000000;
+        const RELIABLE_WRITE              = 0b010000000;
+        const WRITABLE_AUXILIARIES        = 0b100000000;
     }
 }
 
 macro_rules! return_if_cached(
     ($cache:expr, $key:expr) => (
         if $cache.contains_key($key) {
             return $cache.get($key);
         }
@@ -502,25 +502,25 @@ impl BluetoothManager {
         None
     }
 
     fn get_characteristic_properties(&self, characteristic: &BluetoothGATTCharacteristic) -> Flags {
         let mut props: Flags = Flags::empty();
         let flags = characteristic.get_flags().unwrap_or(vec!());
         for flag in flags {
             match flag.as_ref() {
-                "broadcast" => props.insert(BROADCAST),
-                "read" => props.insert(READ),
-                "write-without-response" => props.insert(WRITE_WITHOUT_RESPONSE),
-                "write" => props.insert(WRITE),
-                "notify" => props.insert(NOTIFY),
-                "indicate" => props.insert(INDICATE),
-                "authenticated-signed-writes" => props.insert(AUTHENTICATED_SIGNED_WRITES),
-                "reliable-write" => props.insert(RELIABLE_WRITE),
-                "writable-auxiliaries" => props.insert(WRITABLE_AUXILIARIES),
+                "broadcast" => props.insert(Flags::BROADCAST),
+                "read" => props.insert(Flags::READ),
+                "write-without-response" => props.insert(Flags::WRITE_WITHOUT_RESPONSE),
+                "write" => props.insert(Flags::WRITE),
+                "notify" => props.insert(Flags::NOTIFY),
+                "indicate" => props.insert(Flags::INDICATE),
+                "authenticated-signed-writes" => props.insert(Flags::AUTHENTICATED_SIGNED_WRITES),
+                "reliable-write" => props.insert(Flags::RELIABLE_WRITE),
+                "writable-auxiliaries" => props.insert(Flags::WRITABLE_AUXILIARIES),
                 _ => (),
             }
         }
         props
     }
 
     fn characteristic_is_cached(&self, characteristic_id: &str) -> bool {
         self.cached_characteristics.contains_key(characteristic_id) &&
@@ -724,25 +724,25 @@ impl BluetoothManager {
                 let mut characteristics_vec = vec!();
                 for characteristic in characteristics {
                     if let Ok(uuid) = characteristic.get_uuid() {
                         let properties = self.get_characteristic_properties(&characteristic);
                         characteristics_vec.push(
                             BluetoothCharacteristicMsg {
                                 uuid: uuid,
                                 instance_id: characteristic.get_id(),
-                                broadcast: properties.contains(BROADCAST),
-                                read: properties.contains(READ),
-                                write_without_response: properties.contains(WRITE_WITHOUT_RESPONSE),
-                                write: properties.contains(WRITE),
-                                notify: properties.contains(NOTIFY),
-                                indicate: properties.contains(INDICATE),
-                                authenticated_signed_writes: properties.contains(AUTHENTICATED_SIGNED_WRITES),
-                                reliable_write: properties.contains(RELIABLE_WRITE),
-                                writable_auxiliaries: properties.contains(WRITABLE_AUXILIARIES),
+                                broadcast: properties.contains(Flags::BROADCAST),
+                                read: properties.contains(Flags::READ),
+                                write_without_response: properties.contains(Flags::WRITE_WITHOUT_RESPONSE),
+                                write: properties.contains(Flags::WRITE),
+                                notify: properties.contains(Flags::NOTIFY),
+                                indicate: properties.contains(Flags::INDICATE),
+                                authenticated_signed_writes: properties.contains(Flags::AUTHENTICATED_SIGNED_WRITES),
+                                reliable_write: properties.contains(Flags::RELIABLE_WRITE),
+                                writable_auxiliaries: properties.contains(Flags::WRITABLE_AUXILIARIES),
                             }
                         );
                     }
                 }
 
                 // Step 7.
                 if characteristics_vec.is_empty() {
                     return Err(BluetoothError::NotFound);
--- a/servo/components/devtools/actors/console.rs
+++ b/servo/components/devtools/actors/console.rs
@@ -4,17 +4,17 @@
 
 //! Liberally derived from the [Firefox JS implementation]
 //! (http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webconsole.js).
 //! Mediates interaction between the remote web console and equivalent functionality (object
 //! inspection, JS evaluation, autocompletion) in Servo.
 
 use actor::{Actor, ActorMessageStatus, ActorRegistry};
 use actors::object::ObjectActor;
-use devtools_traits::{CONSOLE_API, CachedConsoleMessageTypes, DevtoolScriptControlMsg, PAGE_ERROR};
+use devtools_traits::{CachedConsoleMessageTypes, DevtoolScriptControlMsg};
 use devtools_traits::CachedConsoleMessage;
 use devtools_traits::EvaluateJSReply::{ActorValue, BooleanValue, StringValue};
 use devtools_traits::EvaluateJSReply::{NullValue, NumberValue, VoidValue};
 use ipc_channel::ipc::{self, IpcSender};
 use msg::constellation_msg::PipelineId;
 use protocol::JsonPacketStream;
 use serde_json::{self, Map, Number, Value};
 use std::cell::RefCell;
@@ -102,18 +102,18 @@ impl Actor for ConsoleActor {
         Ok(match msg_type {
             "getCachedMessages" => {
                 let str_types = msg.get("messageTypes").unwrap().as_array().unwrap().into_iter().map(|json_type| {
                     json_type.as_str().unwrap()
                 });
                 let mut message_types = CachedConsoleMessageTypes::empty();
                 for str_type in str_types {
                     match str_type {
-                        "PageError" => message_types.insert(PAGE_ERROR),
-                        "ConsoleAPI" => message_types.insert(CONSOLE_API),
+                        "PageError" => message_types.insert(CachedConsoleMessageTypes::PAGE_ERROR),
+                        "ConsoleAPI" => message_types.insert(CachedConsoleMessageTypes::CONSOLE_API),
                         s => debug!("unrecognized message type requested: \"{}\"", s),
                     };
                 };
                 let (chan, port) = ipc::channel().unwrap();
                 self.script_chan.send(DevtoolScriptControlMsg::GetCachedMessages(
                     self.pipeline, message_types, chan)).unwrap();
                 let messages = port.recv().map_err(|_| ())?.into_iter().map(|message| {
                     let json_string = message.encode().unwrap();
--- a/servo/components/devtools_traits/Cargo.toml
+++ b/servo/components/devtools_traits/Cargo.toml
@@ -5,17 +5,17 @@ authors = ["The Servo Project Developers
 license = "MPL-2.0"
 publish = false
 
 [lib]
 name = "devtools_traits"
 path = "lib.rs"
 
 [dependencies]
-bitflags = "0.7"
+bitflags = "1.0"
 hyper = "0.10"
 hyper_serde = "0.7"
 ipc-channel = "0.9"
 malloc_size_of = { path = "../malloc_size_of" }
 malloc_size_of_derive = { path = "../malloc_size_of_derive" }
 msg = {path = "../msg"}
 serde = "1.0"
 servo_url = {path = "../url"}
--- a/servo/components/devtools_traits/lib.rs
+++ b/servo/components/devtools_traits/lib.rs
@@ -238,19 +238,19 @@ pub struct ConsoleMessage {
     pub logLevel: LogLevel,
     pub filename: String,
     pub lineNumber: usize,
     pub columnNumber: usize,
 }
 
 bitflags! {
     #[derive(Deserialize, Serialize)]
-    pub flags CachedConsoleMessageTypes: u8 {
-        const PAGE_ERROR  = 1 << 0,
-        const CONSOLE_API = 1 << 1,
+    pub struct CachedConsoleMessageTypes: u8 {
+        const PAGE_ERROR  = 1 << 0;
+        const CONSOLE_API = 1 << 1;
     }
 }
 
 #[derive(Debug, Deserialize, Serialize)]
 pub struct PageError {
     #[serde(rename = "_type")]
     pub type_: String,
     pub errorMessage: String,
--- a/servo/components/gfx/Cargo.toml
+++ b/servo/components/gfx/Cargo.toml
@@ -10,17 +10,17 @@ publish = false
 name = "gfx"
 path = "lib.rs"
 
 [features]
 unstable = ["simd"]
 
 [dependencies]
 app_units = "0.5"
-bitflags = "0.7"
+bitflags = "1.0"
 euclid = "0.15"
 fnv = "1.0"
 fontsan = {git = "https://github.com/servo/fontsan"}
 gfx_traits = {path = "../gfx_traits"}
 harfbuzz-sys = "0.1"
 ipc-channel = "0.9"
 lazy_static = "0.2"
 libc = "0.2"
--- a/servo/components/gfx/font.rs
+++ b/servo/components/gfx/font.rs
@@ -134,27 +134,27 @@ impl Font {
             shape_cache: RefCell::new(HashMap::new()),
             glyph_advance_cache: RefCell::new(HashMap::new()),
             font_key: font_key,
         }
     }
 }
 
 bitflags! {
-    pub flags ShapingFlags: u8 {
+    pub struct ShapingFlags: u8 {
         #[doc = "Set if the text is entirely whitespace."]
-        const IS_WHITESPACE_SHAPING_FLAG = 0x01,
+        const IS_WHITESPACE_SHAPING_FLAG = 0x01;
         #[doc = "Set if we are to ignore ligatures."]
-        const IGNORE_LIGATURES_SHAPING_FLAG = 0x02,
+        const IGNORE_LIGATURES_SHAPING_FLAG = 0x02;
         #[doc = "Set if we are to disable kerning."]
-        const DISABLE_KERNING_SHAPING_FLAG = 0x04,
+        const DISABLE_KERNING_SHAPING_FLAG = 0x04;
         #[doc = "Text direction is right-to-left."]
-        const RTL_FLAG = 0x08,
+        const RTL_FLAG = 0x08;
         #[doc = "Set if word-break is set to keep-all."]
-        const KEEP_ALL_FLAG = 0x10,
+        const KEEP_ALL_FLAG = 0x10;
     }
 }
 
 /// Various options that control text shaping.
 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
 pub struct ShapingOptions {
     /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property.
     /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null.
@@ -181,18 +181,18 @@ impl Font {
 
         let lookup_key = ShapeCacheEntry {
             text: text.to_owned(),
             options: *options,
         };
         let result = self.shape_cache.borrow_mut().entry(lookup_key).or_insert_with(|| {
             let start_time = time::precise_time_ns();
             let mut glyphs = GlyphStore::new(text.len(),
-                                             options.flags.contains(IS_WHITESPACE_SHAPING_FLAG),
-                                             options.flags.contains(RTL_FLAG));
+                                             options.flags.contains(ShapingFlags::IS_WHITESPACE_SHAPING_FLAG),
+                                             options.flags.contains(ShapingFlags::RTL_FLAG));
 
             if self.can_do_fast_shaping(text, options) {
                 debug!("shape_text: Using ASCII fast path.");
                 self.shape_text_fast(text, options, &mut glyphs);
             } else {
                 debug!("shape_text: Using Harfbuzz.");
                 if shaper.is_none() {
                     shaper = Some(Shaper::new(this));
@@ -206,17 +206,17 @@ impl Font {
             Arc::new(glyphs)
         }).clone();
         self.shaper = shaper;
         result
     }
 
     fn can_do_fast_shaping(&self, text: &str, options: &ShapingOptions) -> bool {
         options.script == Script::Latin &&
-            !options.flags.contains(RTL_FLAG) &&
+            !options.flags.contains(ShapingFlags::RTL_FLAG) &&
             self.handle.can_do_fast_shaping() &&
             text.is_ascii()
     }
 
     /// Fast path for ASCII text that only needs simple horizontal LTR kerning.
     fn shape_text_fast(&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) {
         let mut prev_glyph_id = None;
         for (i, byte) in text.bytes().enumerate() {
--- a/servo/components/gfx/text/shaping/harfbuzz.rs
+++ b/servo/components/gfx/text/shaping/harfbuzz.rs
@@ -1,18 +1,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #![allow(unsafe_code)]
 
 use app_units::Au;
 use euclid::Point2D;
-use font::{DISABLE_KERNING_SHAPING_FLAG, Font, FontTableMethods, FontTableTag};
-use font::{IGNORE_LIGATURES_SHAPING_FLAG, KERN, RTL_FLAG, ShapingOptions};
+use font::{ShapingFlags, Font, FontTableMethods, FontTableTag, ShapingOptions, KERN};
 use harfbuzz::{HB_DIRECTION_LTR, HB_DIRECTION_RTL, HB_MEMORY_MODE_READONLY};
 use harfbuzz::{hb_blob_create, hb_face_create_for_tables};
 use harfbuzz::{hb_buffer_create, hb_font_destroy};
 use harfbuzz::{hb_buffer_get_glyph_infos, hb_shape};
 use harfbuzz::{hb_buffer_set_direction, hb_buffer_set_script};
 use harfbuzz::{hb_buffer_t, hb_codepoint_t, hb_font_funcs_t};
 use harfbuzz::{hb_face_t, hb_font_t};
 use harfbuzz::{hb_position_t, hb_tag_t};
@@ -184,40 +183,40 @@ impl Shaper {
 }
 
 impl ShaperMethods for Shaper {
     /// Calculate the layout metrics associated with the given text when painted in a specific
     /// font.
     fn shape_text(&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) {
         unsafe {
             let hb_buffer: *mut hb_buffer_t = hb_buffer_create();
-            hb_buffer_set_direction(hb_buffer, if options.flags.contains(RTL_FLAG) {
+            hb_buffer_set_direction(hb_buffer, if options.flags.contains(ShapingFlags::RTL_FLAG) {
                 HB_DIRECTION_RTL
             } else {
                 HB_DIRECTION_LTR
             });
 
             hb_buffer_set_script(hb_buffer, options.script.to_hb_script());
 
             hb_buffer_add_utf8(hb_buffer,
                                text.as_ptr() as *const c_char,
                                text.len() as c_int,
                                0,
                                text.len() as c_int);
 
             let mut features = Vec::new();
-            if options.flags.contains(IGNORE_LIGATURES_SHAPING_FLAG) {
+            if options.flags.contains(ShapingFlags::IGNORE_LIGATURES_SHAPING_FLAG) {
                 features.push(hb_feature_t {
                     tag: LIGA,
                     value: 0,
                     start: 0,
                     end: hb_buffer_get_length(hb_buffer),
                 })
             }
-            if options.flags.contains(DISABLE_KERNING_SHAPING_FLAG) {
+            if options.flags.contains(ShapingFlags::DISABLE_KERNING_SHAPING_FLAG) {
                 features.push(hb_feature_t {
                     tag: KERN,
                     value: 0,
                     start: 0,
                     end: hb_buffer_get_length(hb_buffer),
                 })
             }
 
--- a/servo/components/gfx/text/text_run.rs
+++ b/servo/components/gfx/text/text_run.rs
@@ -1,14 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 use app_units::Au;
-use font::{Font, FontHandleMethods, FontMetrics, IS_WHITESPACE_SHAPING_FLAG, KEEP_ALL_FLAG};
+use font::{Font, FontHandleMethods, FontMetrics, ShapingFlags};
 use font::{RunMetrics, ShapingOptions};
 use platform::font_template::FontTemplateData;
 use range::Range;
 use std::cell::Cell;
 use std::cmp::{Ordering, max};
 use std::slice::Iter;
 use std::sync::Arc;
 use style::str::char_is_whitespace;
@@ -205,31 +205,31 @@ impl<'a> TextRun {
             let word = &text[slice.clone()];
 
             // Split off any trailing whitespace into a separate glyph run.
             let mut whitespace = slice.end..slice.end;
             if let Some((i, _)) = word.char_indices().rev()
                 .take_while(|&(_, c)| char_is_whitespace(c)).last() {
                     whitespace.start = slice.start + i;
                     slice.end = whitespace.start;
-                } else if idx != text.len() && options.flags.contains(KEEP_ALL_FLAG) {
+                } else if idx != text.len() && options.flags.contains(ShapingFlags::KEEP_ALL_FLAG) {
                     // If there's no whitespace and word-break is set to
                     // keep-all, try increasing the slice.
                     continue;
                 }
             if slice.len() > 0 {
                 glyphs.push(GlyphRun {
                     glyph_store: font.shape_text(&text[slice.clone()], options),
                     range: Range::new(ByteIndex(slice.start as isize),
                                       ByteIndex(slice.len() as isize)),
                 });
             }
             if whitespace.len() > 0 {
                 let mut options = options.clone();
-                options.flags.insert(IS_WHITESPACE_SHAPING_FLAG);
+                options.flags.insert(ShapingFlags::IS_WHITESPACE_SHAPING_FLAG);
                 glyphs.push(GlyphRun {
                     glyph_store: font.shape_text(&text[whitespace.clone()], &options),
                     range: Range::new(ByteIndex(whitespace.start as isize),
                                       ByteIndex(whitespace.len() as isize)),
                 });
             }
             slice.start = whitespace.end;
         }
--- a/servo/components/layout/Cargo.toml
+++ b/servo/components/layout/Cargo.toml
@@ -7,17 +7,17 @@ publish = false
 
 [lib]
 name = "layout"
 path = "lib.rs"
 
 [dependencies]
 app_units = "0.5"
 atomic_refcell = "0.1"
-bitflags = "0.8"
+bitflags = "1.0"
 canvas_traits = {path = "../canvas_traits"}
 euclid = "0.15"
 fnv = "1.0"
 gfx = {path = "../gfx"}
 gfx_traits = {path = "../gfx_traits"}
 html5ever = "0.21.0"
 ipc-channel = "0.9"
 libc = "0.2"
--- a/servo/components/layout/block.rs
+++ b/servo/components/layout/block.rs
@@ -30,39 +30,35 @@
 use app_units::{Au, MAX_AU};
 use context::LayoutContext;
 use display_list_builder::{BlockFlowDisplayListBuilding, BorderPaintingMode};
 use display_list_builder::{DisplayListBuildState, StackingContextCollectionFlags};
 use display_list_builder::StackingContextCollectionState;
 use euclid::{Point2D, Rect, SideOffsets2D, Size2D};
 use floats::{ClearType, FloatKind, Floats, PlacementInfo};
 use flow::{self, BaseFlow, EarlyAbsolutePositionInfo, Flow, FlowClass, ForceNonfloatedFlag};
-use flow::{BLOCK_POSITION_IS_STATIC, CLEARS_LEFT, CLEARS_RIGHT};
-use flow::{CONTAINS_TEXT_OR_REPLACED_FRAGMENTS, INLINE_POSITION_IS_STATIC};
-use flow::{IS_ABSOLUTELY_POSITIONED, FragmentationContext, MARGINS_CANNOT_COLLAPSE};
-use flow::{ImmutableFlowUtils, LateAbsolutePositionInfo, OpaqueFlow};
+use flow::{ImmutableFlowUtils, LateAbsolutePositionInfo, OpaqueFlow, FragmentationContext, FlowFlags};
 use flow_list::FlowList;
-use fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, Overflow};
-use fragment::{IS_INLINE_FLEX_ITEM, IS_BLOCK_FLEX_ITEM};
+use fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, Overflow, FragmentFlags};
 use gfx_traits::print_tree::PrintTree;
 use incremental::RelayoutMode;
 use layout_debug;
 use model::{AdjoiningMargins, CollapsibleMargins, IntrinsicISizes, MarginCollapseInfo, MaybeAuto};
 use sequential;
 use serde::{Serialize, Serializer};
 use servo_geometry::max_rect;
 use std::cmp::{max, min};
 use std::fmt;
 use std::sync::Arc;
 use style::computed_values::{box_sizing, display, float, overflow_x};
 use style::computed_values::{position, text_align};
 use style::context::SharedStyleContext;
 use style::logical_geometry::{LogicalMargin, LogicalPoint, LogicalRect, LogicalSize, WritingMode};
 use style::properties::ComputedValues;
-use style::servo::restyle_damage::{BUBBLE_ISIZES, REFLOW, REFLOW_OUT_OF_FLOW};
+use style::servo::restyle_damage::ServoRestyleDamage;
 use style::values::computed::{LengthOrPercentageOrNone, LengthOrPercentage};
 use style::values::computed::LengthOrPercentageOrAuto;
 use traversal::PreorderFlowTraversal;
 
 /// Information specific to floated blocks.
 #[derive(Clone, Serialize)]
 pub struct FloatedBlockInfo {
     /// The amount of inline size that is available for the float.
@@ -450,21 +446,21 @@ impl<'a> PreorderFlowTraversal for Absol
     #[inline]
     fn process(&self, flow: &mut Flow) {
         if !flow.is_block_like() {
             return
         }
 
         // This flow might not be an absolutely positioned flow if it is the root of the tree.
         let block = flow.as_mut_block();
-        if !block.base.flags.contains(IS_ABSOLUTELY_POSITIONED) {
+        if !block.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
             return;
         }
 
-        if !block.base.restyle_damage.intersects(REFLOW_OUT_OF_FLOW | REFLOW) {
+        if !block.base.restyle_damage.intersects(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW) {
             return
         }
 
         block.calculate_absolute_block_size_and_margins(self.0);
     }
 }
 
 pub enum BlockType {
@@ -508,21 +504,21 @@ pub struct BlockFlow {
     /// Additional floating flow members.
     pub float: Option<Box<FloatedBlockInfo>>,
 
     /// Various flags.
     flags: BlockFlowFlags,
 }
 
 bitflags! {
-    flags BlockFlowFlags: u8 {
+    struct BlockFlowFlags: u8 {
         #[doc = "If this is set, then this block flow is the root flow."]
-        const IS_ROOT = 0b0000_0001,
+        const IS_ROOT = 0b0000_0001;
         #[doc = "If this is set, then this block flow has overflow and it will scroll."]
-        const HAS_SCROLLING_OVERFLOW = 0b0000_0010,
+        const HAS_SCROLLING_OVERFLOW = 0b0000_0010;
     }
 }
 
 impl Serialize for BlockFlowFlags {
     fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
         self.bits().serialize(serializer)
     }
 }
@@ -546,17 +542,17 @@ impl BlockFlow {
         }
     }
 
     /// Return the type of this block.
     ///
     /// This determines the algorithm used to calculate inline-size, block-size, and the
     /// relevant margins for this Block.
     pub fn block_type(&self) -> BlockType {
-        if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) {
+        if self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
             if self.fragment.is_replaced() {
                 BlockType::AbsoluteReplaced
             } else {
                 BlockType::AbsoluteNonReplaced
             }
         } else if self.is_inline_flex_item() {
             BlockType::InlineFlexItem
         } else if self.base.flags.is_float() {
@@ -659,17 +655,17 @@ impl BlockFlow {
     /// Return the size of the containing block for the given immediate absolute descendant of this
     /// flow.
     ///
     /// Right now, this only gets the containing block size for absolutely positioned elements.
     /// Note: We assume this is called in a top-down traversal, so it is ok to reference the CB.
     #[inline]
     pub fn containing_block_size(&self, viewport_size: &Size2D<Au>, descendant: OpaqueFlow)
                                  -> LogicalSize<Au> {
-        debug_assert!(self.base.flags.contains(IS_ABSOLUTELY_POSITIONED));
+        debug_assert!(self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED));
         if self.is_fixed() || self.is_root() {
             // Initial containing block is the CB for the root
             LogicalSize::from_physical(self.base.writing_mode, *viewport_size)
         } else {
             self.base.absolute_cb.generated_containing_block_size(descendant)
         }
     }
 
@@ -778,53 +774,53 @@ impl BlockFlow {
                                         mut fragmentation_context: Option<FragmentationContext>,
                                         margins_may_collapse: MarginsMayCollapseFlag)
                                         -> Option<Arc<Flow>> {
         let _scope = layout_debug_scope!("assign_block_size_block_base {:x}",
                                          self.base.debug_id());
 
         let mut break_at = None;
         let content_box = self.fragment.content_box();
-        if self.base.restyle_damage.contains(REFLOW) {
+        if self.base.restyle_damage.contains(ServoRestyleDamage::REFLOW) {
             // Our current border-box position.
             let mut cur_b = Au(0);
 
             // Absolute positioning establishes a block formatting context. Don't propagate floats
             // in or out. (But do propagate them between kids.)
-            if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) ||
+            if self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) ||
                     margins_may_collapse != MarginsMayCollapseFlag::MarginsMayCollapse {
                 self.base.floats = Floats::new(self.fragment.style.writing_mode);
             }
 
             let mut margin_collapse_info = MarginCollapseInfo::new();
             let writing_mode = self.base.floats.writing_mode;
             self.base.floats.translate(LogicalSize::new(
                 writing_mode, -self.fragment.inline_start_offset(), Au(0)));
 
             // The sum of our block-start border and block-start padding.
             let block_start_offset = self.fragment.border_padding.block_start;
             translate_including_floats(&mut cur_b, block_start_offset, &mut self.base.floats);
 
             let can_collapse_block_start_margin_with_kids =
                 margins_may_collapse == MarginsMayCollapseFlag::MarginsMayCollapse &&
-                !self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) &&
+                !self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) &&
                 self.fragment.border_padding.block_start == Au(0);
             margin_collapse_info.initialize_block_start_margin(
                 &self.fragment,
                 can_collapse_block_start_margin_with_kids);
 
             // At this point, `cur_b` is at the content edge of our box. Now iterate over children.
             let mut floats = self.base.floats.clone();
             let thread_id = self.base.thread_id;
             let (mut had_floated_children, mut had_children_with_clearance) = (false, false);
             for (child_index, kid) in self.base.child_iter_mut().enumerate() {
-                if flow::base(kid).flags.contains(IS_ABSOLUTELY_POSITIONED) {
+                if flow::base(kid).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
                     // Assume that the *hypothetical box* for an absolute flow starts immediately
                     // after the margin-end border edge of the previous flow.
-                    if flow::base(kid).flags.contains(BLOCK_POSITION_IS_STATIC) {
+                    if flow::base(kid).flags.contains(FlowFlags::BLOCK_POSITION_IS_STATIC) {
                         let previous_bottom_margin = margin_collapse_info.current_float_ceiling();
 
                         flow::mut_base(kid).position.start.b = cur_b +
                             flow::base(kid).collapsible_margins
                                            .block_start_margin_for_noncollapsible_context() +
                             previous_bottom_margin
                     }
                     kid.place_float_if_applicable();
@@ -882,36 +878,36 @@ impl BlockFlow {
                 // Lay the child out if this was an in-order traversal.
                 let need_to_process_child_floats =
                     kid.assign_block_size_for_inorder_child_if_necessary(layout_context,
                                                                          thread_id,
                                                                          content_box);
 
                 if !had_children_with_clearance &&
                         floats.is_present() &&
-                        (flow::base(kid).flags.contains(CLEARS_LEFT) ||
-                         flow::base(kid).flags.contains(CLEARS_RIGHT)) {
+                        (flow::base(kid).flags.contains(FlowFlags::CLEARS_LEFT) ||
+                         flow::base(kid).flags.contains(FlowFlags::CLEARS_RIGHT)) {
                     had_children_with_clearance = true
                 }
 
                 // Handle any (possibly collapsed) top margin.
                 let delta = margin_collapse_info.advance_block_start_margin(
                     &flow::base(kid).collapsible_margins,
                     !had_children_with_clearance);
                 translate_including_floats(&mut cur_b, delta, &mut floats);
 
                 // Collapse-through margins should be placed at the top edge,
                 // so we'll handle the delta after the bottom margin is processed
                 if let CollapsibleMargins::CollapseThrough(_) = flow::base(kid).collapsible_margins {
                     cur_b = cur_b - delta;
                 }
 
                 // Clear past the floats that came in, if necessary.
-                let clearance = match (flow::base(kid).flags.contains(CLEARS_LEFT),
-                                       flow::base(kid).flags.contains(CLEARS_RIGHT)) {
+                let clearance = match (flow::base(kid).flags.contains(FlowFlags::CLEARS_LEFT),
+                                       flow::base(kid).flags.contains(FlowFlags::CLEARS_RIGHT)) {
                     (false, false) => Au(0),
                     (true, false) => floats.clearance(ClearType::Left),
                     (false, true) => floats.clearance(ClearType::Right),
                     (true, true) => floats.clearance(ClearType::Both),
                 };
                 translate_including_floats(&mut cur_b, clearance, &mut floats);
 
                 // At this point, `cur_b` is at the border edge of the child.
@@ -962,38 +958,38 @@ impl BlockFlow {
                 // For consecutive collapse-through flows, their top margin should be calculated
                 // from the same baseline.
                 cur_b = cur_b - collapse_delta;
             }
 
             // Add in our block-end margin and compute our collapsible margins.
             let can_collapse_block_end_margin_with_kids =
                 margins_may_collapse == MarginsMayCollapseFlag::MarginsMayCollapse &&
-                !self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) &&
+                !self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) &&
                 self.fragment.border_padding.block_end == Au(0);
             let (collapsible_margins, delta) =
                 margin_collapse_info.finish_and_compute_collapsible_margins(
                 &self.fragment,
                 self.base.block_container_explicit_block_size,
                 can_collapse_block_end_margin_with_kids,
                 !had_floated_children);
             self.base.collapsible_margins = collapsible_margins;
             translate_including_floats(&mut cur_b, delta, &mut floats);
 
             let mut block_size = cur_b - block_start_offset;
             let is_root = self.is_root();
 
             if is_root || self.formatting_context_type() != FormattingContextType::None ||
-                    self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) {
+                    self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
                 // The content block-size includes all the floats per CSS 2.1 § 10.6.7. The easiest
                 // way to handle this is to just treat it as clearance.
                 block_size = block_size + floats.clearance(ClearType::Both);
             }
 
-            if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) {
+            if self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
                 // FIXME(#2003, pcwalton): The max is taken here so that you can scroll the page,
                 // but this is not correct behavior according to CSS 2.1 § 10.5. Instead I think we
                 // should treat the root element as having `overflow: scroll` and use the layers-
                 // based scrolling infrastructure to make it scrollable.
                 if is_root {
                     let viewport_size =
                         LogicalSize::from_physical(self.fragment.style.writing_mode,
                                                    layout_context.shared_context().viewport_size());
@@ -1003,17 +999,17 @@ impl BlockFlow {
                 // Store the content block-size for use in calculating the absolute flow's
                 // dimensions later.
                 //
                 // FIXME(pcwalton): This looks not idempotent. Is it?
                 self.fragment.border_box.size.block = block_size;
             }
 
 
-            if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) {
+            if self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
                 self.propagate_early_absolute_position_info_to_children();
                 return None
             }
 
             // Compute any explicitly-specified block size.
             // Can't use `for` because we assign to `candidate_block_size_iterator.candidate_value`.
             let mut candidate_block_size_iterator = CandidateBSizeIterator::new(
                 &self.fragment,
@@ -1071,19 +1067,19 @@ impl BlockFlow {
         }
 
         // Don't remove the dirty bits yet if we're absolutely-positioned, since our final size
         // has not been calculated yet. (See `calculate_absolute_block_size_and_margins` for that.)
         // Also don't remove the dirty bits if we're a block formatting context since our inline
         // size has not yet been computed. (See `assign_inline_position_for_formatting_context()`.)
         if (self.base.flags.is_float() ||
                 self.formatting_context_type() == FormattingContextType::None) &&
-                !self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) {
-            self.base.restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW);
-            self.fragment.restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW);
+                !self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
+            self.base.restyle_damage.remove(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW);
+            self.fragment.restyle_damage.remove(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW);
         }
 
         break_at.and_then(|(i, child_remaining)| {
             if i == self.base.children.len() && child_remaining.is_none() {
                 None
             } else {
                 let mut children = self.base.children.split_off(i);
                 if let Some(child) = child_remaining {
@@ -1157,17 +1153,17 @@ impl BlockFlow {
                                                           self.base.position.size);
     }
 
     pub fn explicit_block_containing_size(&self, shared_context: &SharedStyleContext) -> Option<Au> {
         if self.is_root() || self.is_fixed() {
             let viewport_size = LogicalSize::from_physical(self.fragment.style.writing_mode,
                                                            shared_context.viewport_size());
             Some(viewport_size.block)
-        } else if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) &&
+        } else if self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) &&
                   self.base.block_container_explicit_block_size.is_none() {
             self.base.absolute_cb.explicit_block_containing_size(shared_context)
         } else {
             self.base.block_container_explicit_block_size
         }
     }
 
     pub fn explicit_block_size(&self, containing_block_size: Option<Au>) -> Option<Au> {
@@ -1295,26 +1291,26 @@ impl BlockFlow {
             }
         }
 
         let solution = solution.unwrap();
         self.fragment.margin.block_start = solution.margin_block_start;
         self.fragment.margin.block_end = solution.margin_block_end;
         self.fragment.border_box.start.b = Au(0);
 
-        if !self.base.flags.contains(BLOCK_POSITION_IS_STATIC) {
+        if !self.base.flags.contains(FlowFlags::BLOCK_POSITION_IS_STATIC) {
             self.base.position.start.b = solution.block_start + self.fragment.margin.block_start
         }
 
         let block_size = solution.block_size + self.fragment.border_padding.block_start_end();
         self.fragment.border_box.size.block = block_size;
         self.base.position.size.block = block_size;
 
-        self.base.restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW);
-        self.fragment.restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW);
+        self.base.restyle_damage.remove(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW);
+        self.fragment.restyle_damage.remove(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW);
     }
 
     /// Compute inline size based using the `block_container_inline_size` set by the parent flow.
     ///
     /// This is run in the `AssignISizes` traversal.
     fn propagate_and_compute_used_inline_size(&mut self, shared_context: &SharedStyleContext) {
         let containing_block_inline_size = self.base.block_container_inline_size;
         self.compute_used_inline_size(shared_context, containing_block_inline_size);
@@ -1353,17 +1349,17 @@ impl BlockFlow {
         };
         let parent_container_size = self.explicit_block_containing_size(shared_context);
         // https://drafts.csswg.org/css-ui-3/#box-sizing
         let mut explicit_content_size = self
                                     .explicit_block_size(parent_container_size)
                                     .map(|x| if x < box_border { Au(0) } else { x - box_border });
         if self.is_root() { explicit_content_size = max(parent_container_size, explicit_content_size); }
         // Calculate containing block inline size.
-        let containing_block_size = if flags.contains(IS_ABSOLUTELY_POSITIONED) {
+        let containing_block_size = if flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
             self.containing_block_size(&shared_context.viewport_size(), opaque_self).inline
         } else {
             content_inline_size
         };
         // FIXME (mbrubeck): Get correct mode for absolute containing block
         let containing_block_mode = self.base.writing_mode;
 
         let mut inline_start_margin_edge = inline_start_content_edge;
@@ -1381,22 +1377,22 @@ impl BlockFlow {
                 // Otherwise, the position we assign might be incorrect and never fixed up. (Issue
                 // #13704.)
                 //
                 // For instance, floats have their true inline position calculated in
                 // `assign_block_size()`, which won't do anything unless `REFLOW` is set. So, if a
                 // float child does not have `REFLOW` set, we must be careful to avoid touching its
                 // inline position, as no logic will run afterward to set its true value.
                 let kid_base = flow::mut_base(kid);
-                let reflow_damage = if kid_base.flags.contains(IS_ABSOLUTELY_POSITIONED) {
-                    REFLOW_OUT_OF_FLOW
+                let reflow_damage = if kid_base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
+                    ServoRestyleDamage::REFLOW_OUT_OF_FLOW
                 } else {
-                    REFLOW
+                    ServoRestyleDamage::REFLOW
                 };
-                if kid_base.flags.contains(INLINE_POSITION_IS_STATIC) &&
+                if kid_base.flags.contains(FlowFlags::INLINE_POSITION_IS_STATIC) &&
                         kid_base.restyle_damage.contains(reflow_damage) {
                     kid_base.position.start.i =
                         if kid_mode.is_bidi_ltr() == containing_block_mode.is_bidi_ltr() {
                             inline_start_content_edge
                         } else {
                             // The kid's inline 'start' is at the parent's 'end'
                             inline_end_content_edge
                         };
@@ -1470,23 +1466,23 @@ impl BlockFlow {
     /// on the floats we could see at the time of inline-size assignment. The job of this function,
     /// therefore, is not only to assign the final size but also to perform the layout again for
     /// this block formatting context if our speculation was wrong.
     fn assign_inline_position_for_formatting_context(&mut self,
                                                      layout_context: &LayoutContext,
                                                      content_box: LogicalRect<Au>) {
         debug_assert!(self.formatting_context_type() != FormattingContextType::None);
 
-        if !self.base.restyle_damage.intersects(REFLOW_OUT_OF_FLOW | REFLOW) {
+        if !self.base.restyle_damage.intersects(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW) {
             return
         }
 
         // We do this first to avoid recomputing our inline size when we propagate it.
-        self.base.restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW);
-        self.fragment.restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW);
+        self.base.restyle_damage.remove(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW);
+        self.fragment.restyle_damage.remove(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW);
 
         // The code below would completely wreck the layout if run on a flex item, however:
         //   * Flex items are always the children of flex containers.
         //   * Flex containers only contain flex items.
         //   * Floats cannot intrude into flex containers.
         //   * Floats cannot escape flex items.
         //   * Flex items cannot also be floats.
         // Therefore, a flex item cannot be impacted by a float.
@@ -1586,60 +1582,60 @@ impl BlockFlow {
     pub fn bubble_inline_sizes_for_block(&mut self, consult_children: bool) {
         let _scope = layout_debug_scope!("block::bubble_inline_sizes {:x}", self.base.debug_id());
 
         let mut flags = self.base.flags;
         if self.definitely_has_zero_block_size() {
             // This is kind of a hack for Acid2. But it's a harmless one, because (a) this behavior
             // is unspecified; (b) it matches the behavior one would intuitively expect, since
             // floats don't flow around blocks that take up no space in the block direction.
-            flags.remove(CONTAINS_TEXT_OR_REPLACED_FRAGMENTS);
+            flags.remove(FlowFlags::CONTAINS_TEXT_OR_REPLACED_FRAGMENTS);
         } else if self.fragment.is_text_or_replaced() {
-            flags.insert(CONTAINS_TEXT_OR_REPLACED_FRAGMENTS);
+            flags.insert(FlowFlags::CONTAINS_TEXT_OR_REPLACED_FRAGMENTS);
         } else {
-            flags.remove(CONTAINS_TEXT_OR_REPLACED_FRAGMENTS);
+            flags.remove(FlowFlags::CONTAINS_TEXT_OR_REPLACED_FRAGMENTS);
             for kid in self.base.children.iter() {
-                if flow::base(kid).flags.contains(CONTAINS_TEXT_OR_REPLACED_FRAGMENTS) {
-                    flags.insert(CONTAINS_TEXT_OR_REPLACED_FRAGMENTS);
+                if flow::base(kid).flags.contains(FlowFlags::CONTAINS_TEXT_OR_REPLACED_FRAGMENTS) {
+                    flags.insert(FlowFlags::CONTAINS_TEXT_OR_REPLACED_FRAGMENTS);
                     break
                 }
             }
         }
 
         // Find the maximum inline-size from children.
         //
         // See: https://lists.w3.org/Archives/Public/www-style/2014Nov/0085.html
         //
         // FIXME(pcwalton): This doesn't exactly follow that algorithm at the moment.
         // FIXME(pcwalton): This should consider all float descendants, not just children.
         let mut computation = self.fragment.compute_intrinsic_inline_sizes();
         let (mut left_float_width, mut right_float_width) = (Au(0), Au(0));
         let (mut left_float_width_accumulator, mut right_float_width_accumulator) = (Au(0), Au(0));
         let mut preferred_inline_size_of_children_without_text_or_replaced_fragments = Au(0);
         for kid in self.base.child_iter_mut() {
-            if flow::base(kid).flags.contains(IS_ABSOLUTELY_POSITIONED) || !consult_children {
+            if flow::base(kid).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) || !consult_children {
                 continue
             }
 
             let child_base = flow::mut_base(kid);
             let float_kind = child_base.flags.float_kind();
             computation.content_intrinsic_sizes.minimum_inline_size =
                 max(computation.content_intrinsic_sizes.minimum_inline_size,
                     child_base.intrinsic_inline_sizes.minimum_inline_size);
 
-            if child_base.flags.contains(CLEARS_LEFT) {
+            if child_base.flags.contains(FlowFlags::CLEARS_LEFT) {
                 left_float_width = max(left_float_width, left_float_width_accumulator);
                 left_float_width_accumulator = Au(0)
             }
-            if child_base.flags.contains(CLEARS_RIGHT) {
+            if child_base.flags.contains(FlowFlags::CLEARS_RIGHT) {
                 right_float_width = max(right_float_width, right_float_width_accumulator);
                 right_float_width_accumulator = Au(0)
             }
 
-            match (float_kind, child_base.flags.contains(CONTAINS_TEXT_OR_REPLACED_FRAGMENTS)) {
+            match (float_kind, child_base.flags.contains(FlowFlags::CONTAINS_TEXT_OR_REPLACED_FRAGMENTS)) {
                 (float::T::none, true) => {
                     computation.content_intrinsic_sizes.preferred_inline_size =
                         max(computation.content_intrinsic_sizes.preferred_inline_size,
                             child_base.intrinsic_inline_sizes.preferred_inline_size);
                 }
                 (float::T::none, false) => {
                     preferred_inline_size_of_children_without_text_or_replaced_fragments = max(
                         preferred_inline_size_of_children_without_text_or_replaced_fragments,
@@ -1676,17 +1672,17 @@ impl BlockFlow {
             (overflow_x::T::auto, _) | (overflow_x::T::scroll, _) | (overflow_x::T::hidden, _) |
             (_, overflow_x::T::auto) | (_, overflow_x::T::scroll) | (_, overflow_x::T::hidden) =>
                 true,
             (_, _) => false,
         }
     }
 
     pub fn compute_inline_sizes(&mut self, shared_context: &SharedStyleContext) {
-        if !self.base.restyle_damage.intersects(REFLOW_OUT_OF_FLOW | REFLOW) {
+        if !self.base.restyle_damage.intersects(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW) {
             return
         }
 
         debug!("assign_inline_sizes({}): assigning inline_size for flow",
                if self.base.flags.is_float() {
                    "float"
                } else {
                    "block"
@@ -1757,33 +1753,33 @@ impl BlockFlow {
         if border_width.block_start != Au(0) || border_width.block_end != Au(0) {
             return false
         }
         let padding = self.fragment.style.logical_padding();
         padding.block_start.is_definitely_zero() && padding.block_end.is_definitely_zero()
     }
 
     pub fn is_inline_flex_item(&self) -> bool {
-        self.fragment.flags.contains(IS_INLINE_FLEX_ITEM)
+        self.fragment.flags.contains(FragmentFlags::IS_INLINE_FLEX_ITEM)
     }
 
     pub fn is_block_flex_item(&self) -> bool {
-        self.fragment.flags.contains(IS_BLOCK_FLEX_ITEM)
+        self.fragment.flags.contains(FragmentFlags::IS_BLOCK_FLEX_ITEM)
     }
 
     pub fn mark_scrolling_overflow(&mut self, has_scrolling_overflow: bool) {
         if has_scrolling_overflow {
-            self.flags.insert(HAS_SCROLLING_OVERFLOW);
+            self.flags.insert(BlockFlowFlags::HAS_SCROLLING_OVERFLOW);
         } else {
-            self.flags.remove(HAS_SCROLLING_OVERFLOW);
+            self.flags.remove(BlockFlowFlags::HAS_SCROLLING_OVERFLOW);
         }
     }
 
     pub fn has_scrolling_overflow(&mut self) -> bool {
-        self.flags.contains(HAS_SCROLLING_OVERFLOW)
+        self.flags.contains(BlockFlowFlags::HAS_SCROLLING_OVERFLOW)
     }
 
     // Return offset from original position because of `position: sticky`.
     pub fn sticky_position(&self) -> SideOffsets2D<MaybeAuto> {
         let containing_block_size = &self.base.early_absolute_position_info
                                               .relative_containing_block_size;
         let writing_mode = self.base.early_absolute_position_info.relative_containing_block_mode;
         let offsets = self.fragment.style().logical_position();
@@ -1819,17 +1815,17 @@ impl Flow for BlockFlow {
     fn bubble_inline_sizes(&mut self) {
         // If this block has a fixed width, just use that for the minimum and preferred width,
         // rather than bubbling up children inline width.
         let consult_children = match self.fragment.style().get_position().width {
             LengthOrPercentageOrAuto::Length(_) => false,
             _ => true,
         };
         self.bubble_inline_sizes_for_block(consult_children);
-        self.fragment.restyle_damage.remove(BUBBLE_ISIZES);
+        self.fragment.restyle_damage.remove(ServoRestyleDamage::BUBBLE_ISIZES);
     }
 
     /// Recursively (top-down) determines the actual inline-size of child contexts and fragments.
     /// When called on this context, the context has had its inline-size set by the parent context.
     ///
     /// Dual fragments consume some inline-size first, and the remainder is assigned to all child
     /// (block) contexts.
     fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) {
@@ -1869,23 +1865,24 @@ impl Flow for BlockFlow {
                                                         parent_thread_id: u8,
                                                         content_box: LogicalRect<Au>)
                                                         -> bool {
         if self.base.flags.is_float() {
             return false
         }
 
         let is_formatting_context = self.formatting_context_type() != FormattingContextType::None;
-        if !self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) && is_formatting_context {
+        if !self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) && is_formatting_context {
             self.assign_inline_position_for_formatting_context(layout_context, content_box);
         }
 
         if (self as &Flow).floats_might_flow_through() {
             self.base.thread_id = parent_thread_id;
-            if self.base.restyle_damage.intersects(REFLOW_OUT_OF_FLOW | REFLOW) {
+            if self.base.restyle_damage.intersects(ServoRestyleDamage::REFLOW_OUT_OF_FLOW |
+                                                   ServoRestyleDamage::REFLOW) {
                 self.assign_block_size(layout_context);
                 // Don't remove the restyle damage; `assign_block_size` decides whether that is
                 // appropriate (which in the case of e.g. absolutely-positioned flows, it is not).
             }
             return true
         }
 
         if is_formatting_context {
@@ -1909,33 +1906,34 @@ impl Flow for BlockFlow {
                 fragmentation_context: Option<FragmentationContext>)
                 -> Option<Arc<Flow>> {
         if self.fragment.is_replaced() {
             let _scope = layout_debug_scope!("assign_replaced_block_size_if_necessary {:x}",
                                              self.base.debug_id());
 
             // Assign block-size for fragment if it is an image fragment.
             self.fragment.assign_replaced_block_size_if_necessary();
-            if !self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) {
+            if !self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
                 self.base.position.size.block = self.fragment.border_box.size.block;
                 let mut block_start = AdjoiningMargins::from_margin(self.fragment.margin.block_start);
                 let block_end = AdjoiningMargins::from_margin(self.fragment.margin.block_end);
                 if self.fragment.border_box.size.block == Au(0) {
                     block_start.union(block_end);
                     self.base.collapsible_margins = CollapsibleMargins::CollapseThrough(block_start);
                 } else {
                     self.base.collapsible_margins = CollapsibleMargins::Collapse(block_start, block_end);
                 }
-                self.base.restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW);
-                self.fragment.restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW);
+                self.base.restyle_damage.remove(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW);
+                self.fragment.restyle_damage.remove(ServoRestyleDamage::REFLOW_OUT_OF_FLOW |
+                                                    ServoRestyleDamage::REFLOW);
             }
             None
         } else if self.is_root() ||
                 self.formatting_context_type() != FormattingContextType::None ||
-                self.base.flags.contains(MARGINS_CANNOT_COLLAPSE) {
+                self.base.flags.contains(FlowFlags::MARGINS_CANNOT_COLLAPSE) {
             // Root element margins should never be collapsed according to CSS § 8.3.1.
             debug!("assign_block_size: assigning block_size for root flow {:?}",
                    flow::base(self).debug_id());
             self.assign_block_size_block_base(
                 layout_context,
                 fragmentation_context,
                 MarginsMayCollapseFlag::MarginsMayNotCollapse)
         } else {
@@ -1952,17 +1950,17 @@ impl Flow for BlockFlow {
         // FIXME (mbrubeck): Get the real container size, taking the container writing mode into
         // account.  Must handle vertical writing modes.
         let container_size = Size2D::new(self.base.block_container_inline_size, Au(0));
 
         if self.is_root() {
             self.base.clip = max_rect();
         }
 
-        if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) {
+        if self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
             let position_start = self.base.position.start.to_physical(self.base.writing_mode,
                                                                       container_size);
 
             // Compute our position relative to the nearest ancestor stacking context. This will be
             // passed down later as part of containing block details for absolute descendants.
             let absolute_stacking_relative_position = if self.is_fixed() {
                 // The viewport is initially at (0, 0).
                 position_start
@@ -1970,27 +1968,27 @@ impl Flow for BlockFlow {
                 // Absolute position of the containing block + position of absolute
                 // flow w.r.t. the containing block.
                 self.base
                     .late_absolute_position_info
                     .stacking_relative_position_of_absolute_containing_block + position_start.to_vector()
             };
 
             if !self.base.writing_mode.is_vertical() {
-                if !self.base.flags.contains(INLINE_POSITION_IS_STATIC) {
+                if !self.base.flags.contains(FlowFlags::INLINE_POSITION_IS_STATIC) {
                     self.base.stacking_relative_position.x = absolute_stacking_relative_position.x
                 }
-                if !self.base.flags.contains(BLOCK_POSITION_IS_STATIC) {
+                if !self.base.flags.contains(FlowFlags::BLOCK_POSITION_IS_STATIC) {
                     self.base.stacking_relative_position.y = absolute_stacking_relative_position.y
                 }
             } else {
-                if !self.base.flags.contains(INLINE_POSITION_IS_STATIC) {
+                if !self.base.flags.contains(FlowFlags::INLINE_POSITION_IS_STATIC) {
                     self.base.stacking_relative_position.y = absolute_stacking_relative_position.y
                 }
-                if !self.base.flags.contains(BLOCK_POSITION_IS_STATIC) {
+                if !self.base.flags.contains(FlowFlags::BLOCK_POSITION_IS_STATIC) {
                     self.base.stacking_relative_position.x = absolute_stacking_relative_position.x
                 }
             }
         }
 
         // For relatively-positioned descendants, the containing block formed by a block is just
         // the content box. The containing block for absolutely-positioned descendants, on the
         // other hand, is established in other circumstances (see `is_absolute_containing_block').
@@ -2053,55 +2051,55 @@ impl Flow for BlockFlow {
             let margin = self.fragment.margin.to_physical(self.base.writing_mode);
             Point2D::new(-margin.left, Au(0))
         } else {
             self.base.stacking_relative_position.to_point() + relative_offset
         };
 
         // Process children.
         for kid in self.base.child_iter_mut() {
-            if flow::base(kid).flags.contains(INLINE_POSITION_IS_STATIC) ||
-                    flow::base(kid).flags.contains(BLOCK_POSITION_IS_STATIC) {
+            if flow::base(kid).flags.contains(FlowFlags::INLINE_POSITION_IS_STATIC) ||
+                    flow::base(kid).flags.contains(FlowFlags::BLOCK_POSITION_IS_STATIC) {
                 let kid_base = flow::mut_base(kid);
                 let physical_position = kid_base.position.to_physical(kid_base.writing_mode,
                                                                       container_size_for_children);
 
                 // Set the inline and block positions as necessary.
                 if !kid_base.writing_mode.is_vertical() {
-                    if kid_base.flags.contains(INLINE_POSITION_IS_STATIC) {
+                    if kid_base.flags.contains(FlowFlags::INLINE_POSITION_IS_STATIC) {
                         kid_base.stacking_relative_position.x = origin_for_children.x +
                             physical_position.origin.x
                     }
-                    if kid_base.flags.contains(BLOCK_POSITION_IS_STATIC) {
+                    if kid_base.flags.contains(FlowFlags::BLOCK_POSITION_IS_STATIC) {
                         kid_base.stacking_relative_position.y = origin_for_children.y +
                             physical_position.origin.y
                     }
                 } else {
-                    if kid_base.flags.contains(INLINE_POSITION_IS_STATIC) {
+                    if kid_base.flags.contains(FlowFlags::INLINE_POSITION_IS_STATIC) {
                         kid_base.stacking_relative_position.y = origin_for_children.y +
                             physical_position.origin.y
                     }
-                    if kid_base.flags.contains(BLOCK_POSITION_IS_STATIC) {
+                    if kid_base.flags.contains(FlowFlags::BLOCK_POSITION_IS_STATIC) {
                         kid_base.stacking_relative_position.x = origin_for_children.x +
                             physical_position.origin.x
                     }
                 }
             }
 
             flow::mut_base(kid).late_absolute_position_info =
                 late_absolute_position_info_for_children;
         }
     }
 
     fn mark_as_root(&mut self) {
-        self.flags.insert(IS_ROOT)
+        self.flags.insert(BlockFlowFlags::IS_ROOT)
     }
 
     fn is_root(&self) -> bool {
-        self.flags.contains(IS_ROOT)
+        self.flags.contains(BlockFlowFlags::IS_ROOT)
     }
 
     /// The 'position' property of this flow.
     fn positioning(&self) -> position::T {
         self.fragment.style.get_box().position
     }
 
     /// Return the dimensions of the containing block generated by this flow for absolutely-
@@ -2117,27 +2115,27 @@ impl Flow for BlockFlow {
     }
 
     /// Returns true if this is an absolute containing block.
     fn is_absolute_containing_block(&self) -> bool {
         self.contains_positioned_fragments() || self.fragment.has_filter_transform_or_perspective()
     }
 
     fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
-        if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) &&
+        if self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) &&
                 self.fragment.style().logical_position().inline_start ==
                     LengthOrPercentageOrAuto::Auto &&
                 self.fragment.style().logical_position().inline_end ==
                 LengthOrPercentageOrAuto::Auto {
             self.base.position.start.i = inline_position
         }
     }
 
     fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
-        if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) &&
+        if self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) &&
                 self.fragment.style().logical_position().block_start ==
                     LengthOrPercentageOrAuto::Auto &&
                 self.fragment.style().logical_position().block_end ==
                 LengthOrPercentageOrAuto::Auto {
             self.base.position.start.b = block_position
         }
     }
 
@@ -2743,17 +2741,17 @@ impl ISizeAndMarginsComputer for Absolut
         let opaque_block = OpaqueFlow::from_flow(block);
         block.containing_block_size(&shared_context.viewport_size(), opaque_block).inline
     }
 
     fn set_inline_position_of_flow_if_necessary(&self,
                                                 block: &mut BlockFlow,
                                                 solution: ISizeConstraintSolution) {
         // Set the inline position of the absolute flow wrt to its containing block.
-        if !block.base.flags.contains(INLINE_POSITION_IS_STATIC) {
+        if !block.base.flags.contains(FlowFlags::INLINE_POSITION_IS_STATIC) {
             block.base.position.start.i = solution.inline_start;
         }
     }
 }
 
 impl ISizeAndMarginsComputer for AbsoluteReplaced {
     /// Solve the horizontal constraint equation for absolute replaced elements.
     ///
--- a/servo/components/layout/construct.rs
+++ b/servo/components/layout/construct.rs
@@ -11,32 +11,29 @@
 //! maybe it's an absolute or fixed position thing that hasn't found its containing block yet.
 //! Construction items bubble up the tree from children to parents until they find their homes.
 
 #![deny(unsafe_code)]
 
 use ServoArc;
 use block::BlockFlow;
 use context::{LayoutContext, with_thread_local_font_context};
-use data::{HAS_NEWLY_CONSTRUCTED_FLOW, LayoutData};
+use data::{LayoutDataFlags, LayoutData};
 use flex::FlexFlow;
 use floats::FloatKind;
 use flow::{self, AbsoluteDescendants, Flow, FlowClass, ImmutableFlowUtils};
-use flow::{CAN_BE_FRAGMENTED, IS_ABSOLUTELY_POSITIONED, MARGINS_CANNOT_COLLAPSE};
-use flow::{MutableFlowUtils, MutableOwnedFlowUtils};
+use flow::{FlowFlags, MutableFlowUtils, MutableOwnedFlowUtils};
 use flow_ref::FlowRef;
 use fragment::{CanvasFragmentInfo, ImageFragmentInfo, InlineAbsoluteFragmentInfo, SvgFragmentInfo};
-use fragment::{Fragment, GeneratedContentInfo, IframeFragmentInfo};
-use fragment::{IS_INLINE_FLEX_ITEM, IS_BLOCK_FLEX_ITEM};
+use fragment::{Fragment, GeneratedContentInfo, IframeFragmentInfo, FragmentFlags};
 use fragment::{InlineAbsoluteHypotheticalFragmentInfo, TableColumnFragmentInfo};
 use fragment::{InlineBlockFragmentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo};
 use fragment::WhitespaceStrippingResult;
 use gfx::display_list::OpaqueNode;
-use inline::{FIRST_FRAGMENT_OF_ELEMENT, InlineFlow};
-use inline::{InlineFragmentNodeInfo, LAST_FRAGMENT_OF_ELEMENT};
+use inline::{InlineFlow, InlineFragmentNodeInfo, InlineFragmentNodeFlags};
 use linked_list::prepend_from;
 use list_item::{ListItemFlow, ListStyleTypeContent};
 use multicol::{MulticolColumnFlow, MulticolFlow};
 use parallel;
 use script_layout_interface::{LayoutElementType, LayoutNodeType, is_image_data};
 use script_layout_interface::wrapper_traits::{PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode};
 use servo_config::opts;
 use servo_url::ServoUrl;
@@ -49,17 +46,17 @@ use std::sync::atomic::Ordering;
 use style::computed_values::{caption_side, display, empty_cells, float, list_style_position};
 use style::computed_values::content::ContentItem;
 use style::computed_values::position;
 use style::context::SharedStyleContext;
 use style::logical_geometry::Direction;
 use style::properties::ComputedValues;
 use style::properties::longhands::list_style_image;
 use style::selector_parser::{PseudoElement, RestyleDamage};
-use style::servo::restyle_damage::{BUBBLE_ISIZES, RECONSTRUCT_FLOW};
+use style::servo::restyle_damage::ServoRestyleDamage;
 use style::values::Either;
 use table::TableFlow;
 use table_caption::TableCaptionFlow;
 use table_cell::TableCellFlow;
 use table_colgroup::TableColGroupFlow;
 use table_row::TableRowFlow;
 use table_rowgroup::TableRowGroupFlow;
 use table_wrapper::TableWrapperFlow;
@@ -168,27 +165,28 @@ impl InlineBlockSplit {
     /// subsequent fragments.
     fn new<ConcreteThreadSafeLayoutNode: ThreadSafeLayoutNode>(fragment_accumulator: &mut InlineFragmentsAccumulator,
                                                                node: &ConcreteThreadSafeLayoutNode,
                                                                style_context: &SharedStyleContext,
                                                                flow: FlowRef)
                                                                -> InlineBlockSplit {
         fragment_accumulator.enclosing_node.as_mut().expect(
             "enclosing_node is None; Are {ib} splits being generated outside of an inline node?"
-        ).flags.remove(LAST_FRAGMENT_OF_ELEMENT);
+        ).flags.remove(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT);
 
         let split = InlineBlockSplit {
             predecessors: mem::replace(
                 fragment_accumulator,
                 InlineFragmentsAccumulator::from_inline_node(
                     node, style_context)).to_intermediate_inline_fragments(style_context),
             flow: flow,
         };
 
-        fragment_accumulator.enclosing_node.as_mut().unwrap().flags.remove(FIRST_FRAGMENT_OF_ELEMENT);
+        fragment_accumulator.enclosing_node.as_mut().unwrap().flags.remove(
+            InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT);
 
         split
     }
 }
 
 /// Holds inline fragments and absolute descendants.
 #[derive(Clone)]
 pub struct IntermediateInlineFragments {
@@ -253,17 +251,18 @@ impl InlineFragmentsAccumulator {
             where N: ThreadSafeLayoutNode {
         InlineFragmentsAccumulator {
             fragments: IntermediateInlineFragments::new(),
             enclosing_node: Some(InlineFragmentNodeInfo {
                 address: node.opaque(),
                 pseudo: node.get_pseudo_element_type().strip(),
                 style: node.style(style_context),
                 selected_style: node.selected_style(),
-                flags: FIRST_FRAGMENT_OF_ELEMENT | LAST_FRAGMENT_OF_ELEMENT,
+                flags: InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT |
+                       InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT,
             }),
             bidi_control_chars: None,
             restyle_damage: node.restyle_damage(),
         }
     }
 
     fn push(&mut self, fragment: Fragment) {
         self.fragments.fragments.push_back(fragment)
@@ -282,27 +281,28 @@ impl InlineFragmentsAccumulator {
             bidi_control_chars,
             restyle_damage,
         } = self;
         if let Some(mut enclosing_node) = enclosing_node {
             let fragment_count = fragments.fragments.len();
             for (index, fragment) in fragments.fragments.iter_mut().enumerate() {
                 let mut enclosing_node = enclosing_node.clone();
                 if index != 0 {
-                    enclosing_node.flags.remove(FIRST_FRAGMENT_OF_ELEMENT)
+                    enclosing_node.flags.remove(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT)
                 }
                 if index != fragment_count - 1 {
-                    enclosing_node.flags.remove(LAST_FRAGMENT_OF_ELEMENT)
+                    enclosing_node.flags.remove(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT)
                 }
                 fragment.add_inline_context_style(enclosing_node);
             }
 
             // Control characters are later discarded in transform_text, so they don't affect the
             // is_first/is_last styles above.
-            enclosing_node.flags.remove(FIRST_FRAGMENT_OF_ELEMENT | LAST_FRAGMENT_OF_ELEMENT);
+            enclosing_node.flags.remove(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT |
+                                        InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT);
 
             if let Some((start, end)) = bidi_control_chars {
                 fragments.fragments.push_front(
                     control_chars_to_fragment(&enclosing_node, context, start, restyle_damage));
                 fragments.fragments.push_back(
                     control_chars_to_fragment(&enclosing_node, context, end, restyle_damage));
             }
         }
@@ -488,17 +488,17 @@ impl<'a, ConcreteThreadSafeLayoutNode: T
             ConstructionResult::Flow(kid_flow, kid_abs_descendants) => {
                 // If kid_flow is TableCaptionFlow, kid_flow should be added under
                 // TableWrapperFlow.
                 if flow.is_table() && kid_flow.is_table_caption() {
                     let construction_result =
                         ConstructionResult::Flow(kid_flow, AbsoluteDescendants::new());
                     self.set_flow_construction_result(&kid, construction_result)
                 } else {
-                    if !flow::base(&*kid_flow).flags.contains(IS_ABSOLUTELY_POSITIONED) {
+                    if !flow::base(&*kid_flow).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
                         // Flush any inline fragments that we were gathering up. This allows us to
                         // handle {ib} splits.
                         let old_inline_fragment_accumulator =
                             mem::replace(inline_fragment_accumulator,
                                          InlineFragmentsAccumulator::new());
                         self.flush_inline_fragments_to_flow(old_inline_fragment_accumulator,
                                                             flow,
                                                             abs_descendants,
@@ -616,17 +616,17 @@ impl<'a, ConcreteThreadSafeLayoutNode: T
         flow.finish();
 
         // Set up the absolute descendants.
         if flow.is_absolute_containing_block() {
             // This is the containing block for all the absolute descendants.
             flow.set_absolute_descendants(abs_descendants);
 
             abs_descendants = AbsoluteDescendants::new();
-            if flow::base(&*flow).flags.contains(IS_ABSOLUTELY_POSITIONED) {
+            if flow::base(&*flow).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
                 // This is now the only absolute flow in the subtree which hasn't yet
                 // reached its CB.
                 abs_descendants.push(flow.clone());
             }
         }
         ConstructionResult::Flow(flow, abs_descendants)
     }
 
@@ -771,17 +771,17 @@ impl<'a, ConcreteThreadSafeLayoutNode: T
         for kid in node.children() {
             is_empty = false;
             if kid.get_pseudo_element_type() != PseudoElementType::Normal {
                 self.process(&kid);
             }
             match kid.get_construction_result() {
                 ConstructionResult::None => {}
                 ConstructionResult::Flow(flow, kid_abs_descendants) => {
-                    if !flow::base(&*flow).flags.contains(IS_ABSOLUTELY_POSITIONED) {
+                    if !flow::base(&*flow).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
                         opt_inline_block_splits.push_back(InlineBlockSplit::new(
                             &mut fragment_accumulator, node, self.style_context(), flow));
                         abs_descendants.push_descendants(kid_abs_descendants);
                     } else {
                         // Push the absolutely-positioned kid as an inline containing block.
                         let kid_node = flow.as_block().fragment.node;
                         let kid_pseudo = flow.as_block().fragment.pseudo.clone();
                         let kid_style = flow.as_block().fragment.style.clone();
@@ -1061,17 +1061,17 @@ impl<'a, ConcreteThreadSafeLayoutNode: T
         // The flow is done.
         flow.finish();
         if flow.is_absolute_containing_block() {
             // This is the containing block for all the absolute descendants.
             flow.set_absolute_descendants(abs_descendants);
 
             abs_descendants = AbsoluteDescendants::new();
 
-            if flow::base(&*flow).flags.contains(IS_ABSOLUTELY_POSITIONED) {
+            if flow::base(&*flow).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
                 // This is now the only absolute flow in the subtree which hasn't yet
                 // reached its containing block.
                 abs_descendants.push(flow.clone());
             }
         }
 
         ConstructionResult::Flow(flow, abs_descendants)
     }
@@ -1132,17 +1132,17 @@ impl<'a, ConcreteThreadSafeLayoutNode: T
         wrapper_flow.finish();
 
         if wrapper_flow.is_absolute_containing_block() {
             // This is the containing block for all the absolute descendants.
             wrapper_flow.set_absolute_descendants(abs_descendants);
 
             abs_descendants = AbsoluteDescendants::new();
 
-            if flow::base(&*wrapper_flow).flags.contains(IS_ABSOLUTELY_POSITIONED) {
+            if flow::base(&*wrapper_flow).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
                 // This is now the only absolute flow in the subtree which hasn't yet
                 // reached its containing block.
                 abs_descendants.push(wrapper_flow.clone());
             }
         }
 
         ConstructionResult::Flow(wrapper_flow, abs_descendants)
     }
@@ -1327,27 +1327,27 @@ impl<'a, ConcreteThreadSafeLayoutNode: T
 
         // If the node has display: none, it's possible that we haven't even
         // styled the children once, so we need to bailout early here.
         if node.style(self.style_context()).get_box().clone_display() == display::T::none {
             return false;
         }
 
         for kid in node.children() {
-            if kid.flags().contains(HAS_NEWLY_CONSTRUCTED_FLOW) {
-                kid.remove_flags(HAS_NEWLY_CONSTRUCTED_FLOW);
+            if kid.flags().contains(LayoutDataFlags::HAS_NEWLY_CONSTRUCTED_FLOW) {
+                kid.remove_flags(LayoutDataFlags::HAS_NEWLY_CONSTRUCTED_FLOW);
                 need_to_reconstruct = true
             }
         }
 
         if need_to_reconstruct {
             return false
         }
 
-        if node.restyle_damage().contains(RECONSTRUCT_FLOW) {
+        if node.restyle_damage().contains(ServoRestyleDamage::RECONSTRUCT_FLOW) {
             return false
         }
 
         if node.can_be_fragmented() || node.style(self.style_context()).is_multicol() {
             return false
         }
 
         let mut set_has_newly_constructed_flow_flag = false;
@@ -1431,33 +1431,33 @@ impl<'a, ConcreteThreadSafeLayoutNode: T
                     true
                 }
                 ConstructionResult::ConstructionItem(_) => {
                     false
                 }
             }
         };
         if set_has_newly_constructed_flow_flag {
-            node.insert_flags(HAS_NEWLY_CONSTRUCTED_FLOW);
+            node.insert_flags(LayoutDataFlags::HAS_NEWLY_CONSTRUCTED_FLOW);
         }
         return result;
     }
 }
 
 impl<'a, ConcreteThreadSafeLayoutNode> PostorderNodeMutTraversal<ConcreteThreadSafeLayoutNode>
                                        for FlowConstructor<'a, ConcreteThreadSafeLayoutNode>
                                        where ConcreteThreadSafeLayoutNode: ThreadSafeLayoutNode {
     // Construct Flow based on 'display', 'position', and 'float' values.
     //
     // CSS 2.1 Section 9.7
     //
     // TODO: This should actually consult the table in that section to get the
     // final computed value for 'display'.
     fn process(&mut self, node: &ConcreteThreadSafeLayoutNode) {
-        node.insert_flags(HAS_NEWLY_CONSTRUCTED_FLOW);
+        node.insert_flags(LayoutDataFlags::HAS_NEWLY_CONSTRUCTED_FLOW);
 
         // Bail out if this node has an ancestor with display: none.
         if node.style(self.style_context()).is_in_display_none_subtree() {
             self.set_flow_construction_result(node, ConstructionResult::None);
             return;
         }
 
         // Get the `display` property for this node, and determine whether this node is floated.
@@ -1649,17 +1649,17 @@ impl<ConcreteThreadSafeLayoutNode> NodeU
             PseudoElementType::Normal    => &mut data.flow_construction_result,
         }
     }
 
     #[inline(always)]
     fn set_flow_construction_result(self, mut result: ConstructionResult) {
         if self.can_be_fragmented() {
             if let ConstructionResult::Flow(ref mut flow, _) = result {
-                flow::mut_base(FlowRef::deref_mut(flow)).flags.insert(CAN_BE_FRAGMENTED);
+                flow::mut_base(FlowRef::deref_mut(flow)).flags.insert(FlowFlags::CAN_BE_FRAGMENTED);
             }
         }
 
         let mut layout_data = self.mutate_layout_data().unwrap();
         let dst = self.construction_result_mut(&mut *layout_data);
 
         *dst = result;
     }
@@ -1739,17 +1739,17 @@ impl FlowConstructionUtils for FlowRef {
     /// it. This will normally run the bubble-inline-sizes (minimum and preferred -- i.e. intrinsic
     /// -- inline-size) calculation, unless the global `bubble_inline-sizes_separately` flag is on.
     ///
     /// All flows must be finished at some point, or they will not have their intrinsic inline-sizes
     /// properly computed. (This is not, however, a memory safety problem.)
     fn finish(&mut self) {
         if !opts::get().bubble_inline_sizes_separately {
             FlowRef::deref_mut(self).bubble_inline_sizes();
-            flow::mut_base(FlowRef::deref_mut(self)).restyle_damage.remove(BUBBLE_ISIZES);
+            flow::mut_base(FlowRef::deref_mut(self)).restyle_damage.remove(ServoRestyleDamage::BUBBLE_ISIZES);
         }
     }
 }
 
 /// Strips ignorable whitespace from the start of a list of fragments.
 pub fn strip_ignorable_whitespace_from_start(this: &mut LinkedList<Fragment>) {
     if this.is_empty() {
         return   // Fast path.
@@ -1940,48 +1940,48 @@ impl Legalizer {
             (_, FlowClass::TableRowGroup) |
             (_, FlowClass::TableRow) |
             (_, FlowClass::TableCaption) |
             (_, FlowClass::TableCell) => {
                 false
             }
 
             (FlowClass::Flex, FlowClass::Inline) => {
-                flow::mut_base(FlowRef::deref_mut(child)).flags.insert(MARGINS_CANNOT_COLLAPSE);
+                flow::mut_base(FlowRef::deref_mut(child)).flags.insert(FlowFlags::MARGINS_CANNOT_COLLAPSE);
                 let mut block_wrapper =
                     Legalizer::create_anonymous_flow(context,
                                                      parent,
                                                      &[PseudoElement::ServoAnonymousBlock],
                                                      SpecificFragmentInfo::Generic,
                                                      BlockFlow::from_fragment);
                 {
                     let flag = if parent.as_flex().main_mode() == Direction::Inline {
-                        IS_INLINE_FLEX_ITEM
+                        FragmentFlags::IS_INLINE_FLEX_ITEM
                     } else {
-                        IS_BLOCK_FLEX_ITEM
+                        FragmentFlags::IS_BLOCK_FLEX_ITEM
                     };
                     let block = FlowRef::deref_mut(&mut block_wrapper).as_mut_block();
-                    block.base.flags.insert(MARGINS_CANNOT_COLLAPSE);
+                    block.base.flags.insert(FlowFlags::MARGINS_CANNOT_COLLAPSE);
                     block.fragment.flags.insert(flag);
                 }
                 block_wrapper.add_new_child((*child).clone());
                 block_wrapper.finish();
                 parent.add_new_child(block_wrapper);
                 true
             }
 
             (FlowClass::Flex, _) => {
                 {
                     let flag = if parent.as_flex().main_mode() == Direction::Inline {
-                        IS_INLINE_FLEX_ITEM
+                        FragmentFlags::IS_INLINE_FLEX_ITEM
                     } else {
-                        IS_BLOCK_FLEX_ITEM
+                        FragmentFlags::IS_BLOCK_FLEX_ITEM
                     };
                     let block = FlowRef::deref_mut(child).as_mut_block();
-                    block.base.flags.insert(MARGINS_CANNOT_COLLAPSE);
+                    block.base.flags.insert(FlowFlags::MARGINS_CANNOT_COLLAPSE);
                     block.fragment.flags.insert(flag);
                 }
                 parent.add_new_child((*child).clone());
                 true
             }
 
             _ => {
                 parent.add_new_child((*child).clone());
--- a/servo/components/layout/data.rs
+++ b/servo/components/layout/data.rs
@@ -55,15 +55,15 @@ impl LayoutData {
             details_summary_flow_construction_result: ConstructionResult::None,
             details_content_flow_construction_result: ConstructionResult::None,
             flags: LayoutDataFlags::empty(),
         }
     }
 }
 
 bitflags! {
-    pub flags LayoutDataFlags: u8 {
+    pub struct LayoutDataFlags: u8 {
         #[doc = "Whether a flow has been newly constructed."]
-        const HAS_NEWLY_CONSTRUCTED_FLOW = 0x01,
+        const HAS_NEWLY_CONSTRUCTED_FLOW = 0x01;
         #[doc = "Whether this node has been traversed by layout."]
-        const HAS_BEEN_TRAVERSED = 0x02,
+        const HAS_BEEN_TRAVERSED = 0x02;
     }
 }
--- a/servo/components/layout/display_list_builder.rs
+++ b/servo/components/layout/display_list_builder.rs
@@ -11,34 +11,34 @@
 #![deny(unsafe_code)]
 
 use app_units::{AU_PER_PX, Au};
 use block::{BlockFlow, BlockStackingContextType};
 use canvas_traits::canvas::{CanvasMsg, FromLayoutMsg};
 use context::LayoutContext;
 use euclid::{Point2D, Rect, SideOffsets2D, Size2D, Transform3D, TypedRect, TypedSize2D, Vector2D};
 use flex::FlexFlow;
-use flow::{BaseFlow, Flow, IS_ABSOLUTELY_POSITIONED};
+use flow::{BaseFlow, Flow, FlowFlags};
 use flow_ref::FlowRef;
 use fnv::FnvHashMap;
 use fragment::{CanvasFragmentSource, CoordinateSystem, Fragment, ImageFragmentInfo, ScannedTextFragmentInfo};
 use fragment::SpecificFragmentInfo;
 use gfx::display_list;
 use gfx::display_list::{BLUR_INFLATION_FACTOR, BaseDisplayItem, BorderDetails, BorderDisplayItem};
 use gfx::display_list::{BorderRadii, BoxShadowClipMode, BoxShadowDisplayItem, ClipScrollNode};
 use gfx::display_list::{ClipScrollNodeIndex, ClipScrollNodeType, ClippingAndScrolling};
 use gfx::display_list::{ClippingRegion, DisplayItem, DisplayItemMetadata, DisplayList};
 use gfx::display_list::{DisplayListSection, GradientDisplayItem, IframeDisplayItem, ImageBorder};
 use gfx::display_list::{ImageDisplayItem, LineDisplayItem, NormalBorder, OpaqueNode};
 use gfx::display_list::{PopAllTextShadowsDisplayItem, PushTextShadowDisplayItem};
 use gfx::display_list::{RadialGradientDisplayItem, SolidColorDisplayItem, StackingContext};
 use gfx::display_list::{StackingContextType, StickyFrameData, TextDisplayItem, TextOrientation};
 use gfx::display_list::WebRenderImageInfo;
 use gfx_traits::{combine_id_with_fragment_type, FragmentType, StackingContextId};
-use inline::{FIRST_FRAGMENT_OF_ELEMENT, InlineFlow, LAST_FRAGMENT_OF_ELEMENT};
+use inline::{InlineFragmentNodeFlags, InlineFlow};
 use ipc_channel::ipc;
 use list_item::ListItemFlow;
 use model::{self, MaybeAuto};
 use msg::constellation_msg::{BrowsingContextId, PipelineId};
 use net_traits::image::base::PixelFormat;
 use net_traits::image_cache::UsePlaceholder;
 use range::Range;
 use script_layout_interface::wrapper_traits::PseudoElementType;
@@ -50,17 +50,17 @@ use std::mem;
 use std::sync::Arc;
 use style::computed_values::{background_attachment, background_clip, background_origin};
 use style::computed_values::{border_style, cursor};
 use style::computed_values::{image_rendering, overflow_x, pointer_events, position, visibility};
 use style::logical_geometry::{LogicalMargin, LogicalPoint, LogicalRect, LogicalSize, WritingMode};
 use style::properties::ComputedValues;
 use style::properties::longhands::border_image_repeat::computed_value::RepeatKeyword;
 use style::properties::style_structs;
-use style::servo::restyle_damage::REPAINT;
+use style::servo::restyle_damage::ServoRestyleDamage;
 use style::values::{Either, RGBA};
 use style::values::computed::{Angle, Gradient, GradientItem, LengthOrPercentage, Percentage};
 use style::values::computed::{LengthOrPercentageOrAuto, NumberOrPercentage, Position};
 use style::values::computed::effects::SimpleShadow;
 use style::values::computed::image::{EndingShape, LineDirection};
 use style::values::generics::background::BackgroundSize;
 use style::values::generics::effects::Filter;
 use style::values::generics::image::{Circle, Ellipse, EndingShape as GenericEndingShape};
@@ -101,17 +101,18 @@ fn convert_repeat_mode(from: RepeatKeywo
         RepeatKeyword::Round => RepeatMode::Round,
         RepeatKeyword::Space => RepeatMode::Space,
     }
 }
 
 fn establishes_containing_block_for_absolute(flags: StackingContextCollectionFlags,
                                              positioning: position::T)
                                              -> bool {
-    !flags.contains(NEVER_CREATES_CONTAINING_BLOCK) && position::T::static_ != positioning
+    !flags.contains(StackingContextCollectionFlags::NEVER_CREATES_CONTAINING_BLOCK) &&
+                    position::T::static_ != positioning
 }
 
 trait RgbColor {
     fn rgb(r: u8, g: u8, b: u8) -> Self;
 }
 
 impl RgbColor for ColorF {
     fn rgb(r: u8, g: u8, b: u8) -> Self {
@@ -1873,17 +1874,17 @@ impl FragmentDisplayListBuilding for Fra
     fn build_display_list(&mut self,
                           state: &mut DisplayListBuildState,
                           stacking_relative_flow_origin: &Vector2D<Au>,
                           relative_containing_block_size: &LogicalSize<Au>,
                           relative_containing_block_mode: WritingMode,
                           border_painting_mode: BorderPaintingMode,
                           display_list_section: DisplayListSection,
                           clip: &Rect<Au>) {
-        self.restyle_damage.remove(REPAINT);
+        self.restyle_damage.remove(ServoRestyleDamage::REPAINT);
         if self.style().get_inheritedbox().visibility != visibility::T::visible {
             return
         }
 
         // Compute the fragment position relative to the parent stacking context. If the fragment
         // itself establishes a stacking context, then the origin of its position will be (0, 0)
         // for the purposes of this computation.
         let stacking_relative_border_box =
@@ -1919,18 +1920,20 @@ impl FragmentDisplayListBuilding for Fra
                         &stacking_relative_border_box,
                         clip,
                     );
 
                     self.build_display_list_for_borders_if_applicable(
                         state,
                         &*node.style,
                         Some(InlineNodeBorderInfo {
-                            is_first_fragment_of_element: node.flags.contains(FIRST_FRAGMENT_OF_ELEMENT),
-                            is_last_fragment_of_element: node.flags.contains(LAST_FRAGMENT_OF_ELEMENT),
+                            is_first_fragment_of_element:
+                                node.flags.contains(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT),
+                            is_last_fragment_of_element:
+                                node.flags.contains(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT),
                         }),
                         border_painting_mode,
                         &stacking_relative_border_box,
                         display_list_section,
                         clip,
                     );
 
                     // FIXME(emilio): Why does outline not do the same width
@@ -2402,23 +2405,23 @@ impl FragmentDisplayListBuilding for Fra
             PseudoElementType::After(_) => FragmentType::AfterPseudoContent,
             PseudoElementType::DetailsSummary(_) => FragmentType::FragmentBody,
             PseudoElementType::DetailsContent(_) => FragmentType::FragmentBody,
         }
     }
 }
 
 bitflags! {
-    pub flags StackingContextCollectionFlags: u8 {
+    pub struct StackingContextCollectionFlags: u8 {
         /// This flow never establishes a containing block.
-        const NEVER_CREATES_CONTAINING_BLOCK = 0b001,
+        const NEVER_CREATES_CONTAINING_BLOCK = 0b001;
         /// This flow never creates a ClipScrollNode.
-        const NEVER_CREATES_CLIP_SCROLL_NODE = 0b010,
+        const NEVER_CREATES_CLIP_SCROLL_NODE = 0b010;
         /// This flow never creates a stacking context.
-        const NEVER_CREATES_STACKING_CONTEXT = 0b100,
+        const NEVER_CREATES_STACKING_CONTEXT = 0b100;
     }
 }
 
 pub trait BlockFlowDisplayListBuilding {
     fn collect_stacking_contexts_for_block(&mut self,
                                            state: &mut StackingContextCollectionState,
                                            flags: StackingContextCollectionFlags);
 
@@ -2674,27 +2677,27 @@ impl BlockFlowDisplayListBuilding for Bl
         } else {
             self.stacking_relative_border_box(CoordinateSystem::Parent)
         };
 
         if stacking_context_type == BlockStackingContextType::StackingContext {
             self.transform_clip_to_coordinate_space(state, preserved_state);
         }
 
-        if !flags.contains(NEVER_CREATES_CLIP_SCROLL_NODE) {
+        if !flags.contains(StackingContextCollectionFlags::NEVER_CREATES_CLIP_SCROLL_NODE) {
             self.setup_clip_scroll_node_for_position(state, &stacking_relative_border_box);
             self.setup_clip_scroll_node_for_overflow(state, &stacking_relative_border_box);
             self.setup_clip_scroll_node_for_css_clip(state, preserved_state,
                                                      &stacking_relative_border_box);
         }
         self.base.clip = state.clip_stack.last().cloned().unwrap_or_else(max_rect);
 
         // We keep track of our position so that any stickily positioned elements can
         // properly determine the extent of their movement relative to scrolling containers.
-        if !flags.contains(NEVER_CREATES_CONTAINING_BLOCK) {
+        if !flags.contains(StackingContextCollectionFlags::NEVER_CREATES_CONTAINING_BLOCK) {
             let border_box = if self.fragment.establishes_stacking_context() {
                 stacking_relative_border_box
             } else {
                 self.stacking_relative_border_box(CoordinateSystem::Own)
             };
             state.parent_stacking_relative_content_box =
                self.fragment.stacking_relative_content_box(&border_box)
         }
@@ -2882,17 +2885,17 @@ impl BlockFlowDisplayListBuilding for Bl
     }
 
     fn create_pseudo_stacking_context_for_block(
         &mut self,
         parent_stacking_context_id: StackingContextId,
         parent_clipping_and_scrolling: ClippingAndScrolling,
         state: &mut StackingContextCollectionState
     ) {
-        let creation_mode = if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) ||
+        let creation_mode = if self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) ||
                                self.fragment.style.get_box().position != position::T::static_ {
             StackingContextType::PseudoPositioned
         } else {
             assert!(self.base.flags.is_float());
             StackingContextType::PseudoFloat
         };
 
         let new_context = self.fragment.create_stacking_context(self.base.stacking_context_id,
@@ -2941,17 +2944,17 @@ impl BlockFlowDisplayListBuilding for Bl
         self.base.collect_stacking_contexts_for_children(state);
     }
 
     fn build_display_list_for_block(&mut self,
                                     state: &mut DisplayListBuildState,
                                     border_painting_mode: BorderPaintingMode) {
         let background_border_section = if self.base.flags.is_float() {
             DisplayListSection::BackgroundAndBorders
-        } else if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) {
+        } else if self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
             if self.fragment.establishes_stacking_context() {
                 DisplayListSection::BackgroundAndBorders
             } else {
                 DisplayListSection::BlockBackgroundsAndBorders
             }
         } else {
             DisplayListSection::BlockBackgroundsAndBorders
         };
@@ -2977,25 +2980,25 @@ impl BlockFlowDisplayListBuilding for Bl
         state.processing_scrolling_overflow_element = false;
     }
 
     #[inline]
     fn block_stacking_context_type(
         &self,
         flags: StackingContextCollectionFlags,
     ) -> BlockStackingContextType {
-        if flags.contains(NEVER_CREATES_STACKING_CONTEXT) {
+        if flags.contains(StackingContextCollectionFlags::NEVER_CREATES_STACKING_CONTEXT) {
             return BlockStackingContextType::NonstackingContext;
         }
 
         if self.fragment.establishes_stacking_context() {
             return BlockStackingContextType::StackingContext
         }
 
-        if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) {
+        if self.base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
             return BlockStackingContextType::PseudoStackingContext
         }
 
         if self.fragment.style.get_box().position != position::T::static_ {
             return BlockStackingContextType::PseudoStackingContext
         }
 
         if self.base.flags.is_float() {
--- a/servo/components/layout/flex.rs
+++ b/servo/components/layout/flex.rs
@@ -9,28 +9,27 @@
 use app_units::{Au, MAX_AU};
 use block::{AbsoluteAssignBSizesTraversal, BlockFlow, MarginsMayCollapseFlag};
 use context::LayoutContext;
 use display_list_builder::{DisplayListBuildState, FlexFlowDisplayListBuilding};
 use display_list_builder::StackingContextCollectionState;
 use euclid::Point2D;
 use floats::FloatKind;
 use flow;
-use flow::{Flow, FlowClass, ImmutableFlowUtils, OpaqueFlow};
-use flow::{INLINE_POSITION_IS_STATIC, IS_ABSOLUTELY_POSITIONED};
+use flow::{Flow, FlowClass, ImmutableFlowUtils, OpaqueFlow, FlowFlags};
 use fragment::{Fragment, FragmentBorderBoxIterator, Overflow};
 use layout_debug;
 use model::{AdjoiningMargins, CollapsibleMargins};
 use model::{IntrinsicISizes, MaybeAuto, SizeConstraint};
 use std::cmp::{max, min};
 use std::ops::Range;
 use style::computed_values::{align_content, align_self, flex_direction, flex_wrap, justify_content};
 use style::logical_geometry::{Direction, LogicalSize};
 use style::properties::ComputedValues;
-use style::servo::restyle_damage::{REFLOW, REFLOW_OUT_OF_FLOW};
+use style::servo::restyle_damage::ServoRestyleDamage;
 use style::values::computed::{LengthOrPercentage, LengthOrPercentageOrAuto, LengthOrPercentageOrNone};
 use style::values::computed::flex::FlexBasis;
 use style::values::generics::flex::FlexBasis as GenericFlexBasis;
 use traversal::PreorderFlowTraversal;
 
 /// The size of an axis. May be a specified size, a min/max
 /// constraint, or an unlimited size
 #[derive(Debug, Serialize)]
@@ -444,17 +443,17 @@ impl FlexFlow {
             LengthOrPercentageOrAuto::Length(_) => true,
             _ => false,
         };
 
         let mut computation = self.block_flow.fragment.compute_intrinsic_inline_sizes();
         if !fixed_width {
             for kid in self.block_flow.base.children.iter_mut() {
                 let base = flow::mut_base(kid);
-                let is_absolutely_positioned = base.flags.contains(IS_ABSOLUTELY_POSITIONED);
+                let is_absolutely_positioned = base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED);
                 if !is_absolutely_positioned {
                     let flex_item_inline_sizes = IntrinsicISizes {
                         minimum_inline_size: base.intrinsic_inline_sizes.minimum_inline_size,
                         preferred_inline_size: base.intrinsic_inline_sizes.preferred_inline_size,
                     };
                     computation.union_nonbreaking_inline(&flex_item_inline_sizes);
                 }
             }
@@ -470,17 +469,17 @@ impl FlexFlow {
             LengthOrPercentageOrAuto::Length(_) => true,
             _ => false,
         };
 
         let mut computation = self.block_flow.fragment.compute_intrinsic_inline_sizes();
         if !fixed_width {
             for kid in self.block_flow.base.children.iter_mut() {
                 let base = flow::mut_base(kid);
-                let is_absolutely_positioned = base.flags.contains(IS_ABSOLUTELY_POSITIONED);
+                let is_absolutely_positioned = base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED);
                 if !is_absolutely_positioned {
                     computation.content_intrinsic_sizes.minimum_inline_size =
                         max(computation.content_intrinsic_sizes.minimum_inline_size,
                             base.intrinsic_inline_sizes.minimum_inline_size);
 
                     computation.content_intrinsic_sizes.preferred_inline_size =
                         max(computation.content_intrinsic_sizes.preferred_inline_size,
                             base.intrinsic_inline_sizes.preferred_inline_size);
@@ -513,17 +512,17 @@ impl FlexFlow {
             AxisSize::MinMax(ref constraint) => constraint.clamp(content_inline_size),
             AxisSize::Infinite => content_inline_size
         };
 
         let mut children = self.block_flow.base.children.random_access_mut();
         for kid in &mut self.items {
             let kid_base = flow::mut_base(children.get(kid.index));
             kid_base.block_container_explicit_block_size = container_block_size;
-            if kid_base.flags.contains(INLINE_POSITION_IS_STATIC) {
+            if kid_base.flags.contains(FlowFlags::INLINE_POSITION_IS_STATIC) {
                 // The inline-start margin edge of the child flow is at our inline-start content
                 // edge, and its inline-size is our content inline-size.
                 kid_base.position.start.i =
                     if kid_base.writing_mode.is_bidi_ltr() == containing_block_mode.is_bidi_ltr() {
                         inline_start_content_edge
                     } else {
                         // The kid's inline 'start' is at the parent's 'end'
                         inline_end_content_edge
@@ -850,17 +849,17 @@ impl Flow for FlexFlow {
         // FIXME(stshine): This should be done during flow construction.
         let mut items: Vec<FlexItem> =
             self.block_flow
                 .base
                 .children
                 .iter()
                 .enumerate()
                 .filter(|&(_, flow)| {
-                    !flow.as_block().base.flags.contains(IS_ABSOLUTELY_POSITIONED)
+                    !flow.as_block().base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED)
                 })
                 .map(|(index, flow)| FlexItem::new(index, flow))
                 .collect();
 
         items.sort_by_key(|item| item.order);
         self.items = items;
 
         match self.main_mode {
@@ -868,17 +867,18 @@ impl Flow for FlexFlow {
             Direction::Block  => self.block_mode_bubble_inline_sizes()
         }
     }
 
     fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) {
         let _scope = layout_debug_scope!("flex::assign_inline_sizes {:x}", self.block_flow.base.debug_id());
         debug!("assign_inline_sizes");
 
-        if !self.block_flow.base.restyle_damage.intersects(REFLOW_OUT_OF_FLOW | REFLOW) {
+        if !self.block_flow.base.restyle_damage.intersects(ServoRestyleDamage::REFLOW_OUT_OF_FLOW |
+                                                           ServoRestyleDamage::REFLOW) {
             return
         }
 
         self.block_flow.initialize_container_size_for_root(layout_context.shared_context());
 
         // Our inline-size was set to the inline-size of the containing block by the flow's parent.
         // Now compute the real value.
         let containing_block_inline_size = self.block_flow.base.block_container_inline_size;
--- a/servo/components/layout/floats.rs
+++ b/servo/components/layout/floats.rs
@@ -1,15 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 use app_units::{Au, MAX_AU};
 use block::FormattingContextType;
-use flow::{self, CLEARS_LEFT, CLEARS_RIGHT, Flow, ImmutableFlowUtils};
+use flow::{self, Flow, FlowFlags, ImmutableFlowUtils};
 use persistent_list::PersistentList;
 use std::cmp::{max, min};
 use std::fmt;
 use style::computed_values::float;
 use style::logical_geometry::{LogicalRect, LogicalSize, WritingMode};
 use style::values::computed::LengthOrPercentageOrAuto;
 
 /// The kind of float: left or right.
@@ -454,20 +454,20 @@ impl SpeculatedFloatPlacement {
             right: Au(0),
         }
     }
 
     /// Given the speculated inline size of the floats out for the inorder predecessor of this
     /// flow, computes the speculated inline size of the floats flowing in.
     pub fn compute_floats_in(&mut self, flow: &mut Flow) {
         let base_flow = flow::base(flow);
-        if base_flow.flags.contains(CLEARS_LEFT) {
+        if base_flow.flags.contains(FlowFlags::CLEARS_LEFT) {
             self.left = Au(0)
         }
-        if base_flow.flags.contains(CLEARS_RIGHT) {
+        if base_flow.flags.contains(FlowFlags::CLEARS_RIGHT) {
             self.right = Au(0)
         }
     }
 
     /// Given the speculated inline size of the floats out for this flow's last child, computes the
     /// speculated inline size of the floats out for this flow.
     pub fn compute_floats_out(&mut self, flow: &mut Flow) {
         if flow.is_block_like() {
--- a/servo/components/layout/flow.rs
+++ b/servo/components/layout/flow.rs
@@ -49,17 +49,17 @@ use std::iter::Zip;
 use std::slice::IterMut;
 use std::sync::Arc;
 use std::sync::atomic::Ordering;
 use style::computed_values::{clear, float, overflow_x, position, text_align};
 use style::context::SharedStyleContext;
 use style::logical_geometry::{LogicalRect, LogicalSize, WritingMode};
 use style::properties::ComputedValues;
 use style::selector_parser::RestyleDamage;
-use style::servo::restyle_damage::{RECONSTRUCT_FLOW, REFLOW, REFLOW_OUT_OF_FLOW, REPAINT};
+use style::servo::restyle_damage::ServoRestyleDamage;
 use style::values::computed::LengthOrPercentageOrAuto;
 use table::TableFlow;
 use table_caption::TableCaptionFlow;
 use table_cell::TableCellFlow;
 use table_colgroup::TableColGroupFlow;
 use table_row::TableRowFlow;
 use table_rowgroup::TableRowGroupFlow;
 use table_wrapper::TableWrapperFlow;
@@ -247,17 +247,17 @@ pub trait Flow: HasBaseFlow + fmt::Debug
                                                         parent_thread_id: u8,
                                                         _content_box: LogicalRect<Au>)
                                                         -> bool {
         let might_have_floats_in_or_out = base(self).might_have_floats_in() ||
             base(self).might_have_floats_out();
         if might_have_floats_in_or_out {
             mut_base(self).thread_id = parent_thread_id;
             self.assign_block_size(layout_context);
-            mut_base(self).restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW);
+            mut_base(self).restyle_damage.remove(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW);
         }
         might_have_floats_in_or_out
     }
 
     fn get_overflow_in_parent_coordinates(&self) -> Overflow {
         // FIXME(#2795): Get the real container size.
         let container_size = Size2D::zero();
         let position = base(self).position.to_physical(base(self).writing_mode, container_size);
@@ -397,17 +397,17 @@ pub trait Flow: HasBaseFlow + fmt::Debug
 
     /// Return true if this flow has position 'fixed'.
     fn is_fixed(&self) -> bool {
         self.positioning() == position::T::fixed
     }
 
     fn contains_positioned_fragments(&self) -> bool {
         self.contains_relatively_positioned_fragments() ||
-            base(self).flags.contains(IS_ABSOLUTELY_POSITIONED)
+            base(self).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED)
     }
 
     fn contains_relatively_positioned_fragments(&self) -> bool {
         self.positioning() == position::T::relative
     }
 
     /// Returns true if this is an absolute containing block.
     fn is_absolute_containing_block(&self) -> bool {
@@ -586,101 +586,101 @@ impl FlowClass {
             FlowClass::TableWrapper | FlowClass::Flex => true,
             _ => false,
         }
     }
 }
 
 bitflags! {
     #[doc = "Flags used in flows."]
-    pub flags FlowFlags: u32 {
+    pub struct FlowFlags: u32 {
         // text align flags
         #[doc = "Whether this flow is absolutely positioned. This is checked all over layout, so a"]
         #[doc = "virtual call is too expensive."]
-        const IS_ABSOLUTELY_POSITIONED = 0b0000_0000_0000_0000_0100_0000,
+        const IS_ABSOLUTELY_POSITIONED = 0b0000_0000_0000_0000_0100_0000;
         #[doc = "Whether this flow clears to the left. This is checked all over layout, so a"]
         #[doc = "virtual call is too expensive."]
-        const CLEARS_LEFT = 0b0000_0000_0000_0000_1000_0000,
+        const CLEARS_LEFT = 0b0000_0000_0000_0000_1000_0000;
         #[doc = "Whether this flow clears to the right. This is checked all over layout, so a"]
         #[doc = "virtual call is too expensive."]
-        const CLEARS_RIGHT = 0b0000_0000_0000_0001_0000_0000,
+        const CLEARS_RIGHT = 0b0000_0000_0000_0001_0000_0000;
         #[doc = "Whether this flow is left-floated. This is checked all over layout, so a"]
         #[doc = "virtual call is too expensive."]
-        const FLOATS_LEFT = 0b0000_0000_0000_0010_0000_0000,
+        const FLOATS_LEFT = 0b0000_0000_0000_0010_0000_0000;
         #[doc = "Whether this flow is right-floated. This is checked all over layout, so a"]
         #[doc = "virtual call is too expensive."]
-        const FLOATS_RIGHT = 0b0000_0000_0000_0100_0000_0000,
+        const FLOATS_RIGHT = 0b0000_0000_0000_0100_0000_0000;
         #[doc = "Text alignment. \
 
                  NB: If you update this, update `TEXT_ALIGN_SHIFT` below."]
-        const TEXT_ALIGN = 0b0000_0000_0111_1000_0000_0000,
+        const TEXT_ALIGN = 0b0000_0000_0111_1000_0000_0000;
         #[doc = "Whether this flow has a fragment with `counter-reset` or `counter-increment` \
                  styles."]
-        const AFFECTS_COUNTERS = 0b0000_0000_1000_0000_0000_0000,
+        const AFFECTS_COUNTERS = 0b0000_0000_1000_0000_0000_0000;
         #[doc = "Whether this flow's descendants have fragments that affect `counter-reset` or \
                  `counter-increment` styles."]
-        const HAS_COUNTER_AFFECTING_CHILDREN = 0b0000_0001_0000_0000_0000_0000,
+        const HAS_COUNTER_AFFECTING_CHILDREN = 0b0000_0001_0000_0000_0000_0000;
         #[doc = "Whether this flow behaves as though it had `position: static` for the purposes \
                  of positioning in the inline direction. This is set for flows with `position: \
                  static` and `position: relative` as well as absolutely-positioned flows with \
                  unconstrained positions in the inline direction."]
-        const INLINE_POSITION_IS_STATIC = 0b0000_0010_0000_0000_0000_0000,
+        const INLINE_POSITION_IS_STATIC = 0b0000_0010_0000_0000_0000_0000;
         #[doc = "Whether this flow behaves as though it had `position: static` for the purposes \
                  of positioning in the block direction. This is set for flows with `position: \
                  static` and `position: relative` as well as absolutely-positioned flows with \
                  unconstrained positions in the block direction."]
-        const BLOCK_POSITION_IS_STATIC = 0b0000_0100_0000_0000_0000_0000,
+        const BLOCK_POSITION_IS_STATIC = 0b0000_0100_0000_0000_0000_0000;
 
         /// Whether any ancestor is a fragmentation container
-        const CAN_BE_FRAGMENTED = 0b0000_1000_0000_0000_0000_0000,
+        const CAN_BE_FRAGMENTED = 0b0000_1000_0000_0000_0000_0000;
 
         /// Whether this flow contains any text and/or replaced fragments.
-        const CONTAINS_TEXT_OR_REPLACED_FRAGMENTS = 0b0001_0000_0000_0000_0000_0000,
+        const CONTAINS_TEXT_OR_REPLACED_FRAGMENTS = 0b0001_0000_0000_0000_0000_0000;
 
         /// Whether margins are prohibited from collapsing with this flow.
-        const MARGINS_CANNOT_COLLAPSE = 0b0010_0000_0000_0000_0000_0000,
+        const MARGINS_CANNOT_COLLAPSE = 0b0010_0000_0000_0000_0000_0000;
     }
 }
 
 /// The number of bits we must shift off to handle the text alignment field.
 ///
 /// NB: If you update this, update `TEXT_ALIGN` above.
 static TEXT_ALIGN_SHIFT: usize = 11;
 
 impl FlowFlags {
     #[inline]
     pub fn text_align(self) -> text_align::T {
-        text_align::T::from_u32((self & TEXT_ALIGN).bits() >> TEXT_ALIGN_SHIFT).unwrap()
+        text_align::T::from_u32((self & FlowFlags::TEXT_ALIGN).bits() >> TEXT_ALIGN_SHIFT).unwrap()
     }
 
     #[inline]
     pub fn set_text_align(&mut self, value: text_align::T) {
-        *self = (*self & !TEXT_ALIGN) |
+        *self = (*self & !FlowFlags::TEXT_ALIGN) |
                 FlowFlags::from_bits(value.to_u32() << TEXT_ALIGN_SHIFT).unwrap();
     }
 
     #[inline]
     pub fn float_kind(&self) -> float::T {
-        if self.contains(FLOATS_LEFT) {
+        if self.contains(FlowFlags::FLOATS_LEFT) {
             float::T::left
-        } else if self.contains(FLOATS_RIGHT) {
+        } else if self.contains(FlowFlags::FLOATS_RIGHT) {
             float::T::right
         } else {
             float::T::none
         }
     }
 
     #[inline]
     pub fn is_float(&self) -> bool {
-        self.contains(FLOATS_LEFT) || self.contains(FLOATS_RIGHT)
+        self.contains(FlowFlags::FLOATS_LEFT) || self.contains(FlowFlags::FLOATS_RIGHT)
     }
 
     #[inline]
     pub fn clears_floats(&self) -> bool {
-        self.contains(CLEARS_LEFT) || self.contains(CLEARS_RIGHT)
+        self.contains(FlowFlags::CLEARS_LEFT) || self.contains(FlowFlags::CLEARS_RIGHT)
     }
 }
 
 /// Absolutely-positioned descendants of this flow.
 #[derive(Clone)]
 pub struct AbsoluteDescendants {
     /// Links to every descendant. This must be private because it is unsafe to leak `FlowRef`s to
     /// layout.
@@ -942,18 +942,18 @@ impl fmt::Debug for BaseFlow {
             "".to_owned()
         };
 
         write!(f,
                "sc={:?} pos={:?}, {}{} floatspec-in={:?}, floatspec-out={:?}, \
                 overflow={:?}{}{}{}",
                self.stacking_context_id,
                self.position,
-               if self.flags.contains(FLOATS_LEFT) { "FL" } else { "" },
-               if self.flags.contains(FLOATS_RIGHT) { "FR" } else { "" },
+               if self.flags.contains(FlowFlags::FLOATS_LEFT) { "FL" } else { "" },
+               if self.flags.contains(FlowFlags::FLOATS_RIGHT) { "FR" } else { "" },
                self.speculated_float_placement_in,
                self.speculated_float_placement_out,
                self.overflow,
                child_count_string,
                absolute_descendants_string,
                damage_string)
     }
 }
@@ -986,60 +986,60 @@ impl BaseFlow {
                writing_mode: WritingMode,
                force_nonfloated: ForceNonfloatedFlag)
                -> BaseFlow {
         let mut flags = FlowFlags::empty();
         match style {
             Some(style) => {
                 match style.get_box().position {
                     position::T::absolute | position::T::fixed => {
-                        flags.insert(IS_ABSOLUTELY_POSITIONED);
+                        flags.insert(FlowFlags::IS_ABSOLUTELY_POSITIONED);
 
                         let logical_position = style.logical_position();
                         if logical_position.inline_start == LengthOrPercentageOrAuto::Auto &&
                                 logical_position.inline_end == LengthOrPercentageOrAuto::Auto {
-                            flags.insert(INLINE_POSITION_IS_STATIC);
+                            flags.insert(FlowFlags::INLINE_POSITION_IS_STATIC);
                         }
                         if logical_position.block_start == LengthOrPercentageOrAuto::Auto &&
                                 logical_position.block_end == LengthOrPercentageOrAuto::Auto {
-                            flags.insert(BLOCK_POSITION_IS_STATIC);
+                            flags.insert(FlowFlags::BLOCK_POSITION_IS_STATIC);
                         }
                     }
-                    _ => flags.insert(BLOCK_POSITION_IS_STATIC | INLINE_POSITION_IS_STATIC),
+                    _ => flags.insert(FlowFlags::BLOCK_POSITION_IS_STATIC | FlowFlags::INLINE_POSITION_IS_STATIC),
                 }
 
                 if force_nonfloated == ForceNonfloatedFlag::FloatIfNecessary {
                     match style.get_box().float {
                         float::T::none => {}
-                        float::T::left => flags.insert(FLOATS_LEFT),
-                        float::T::right => flags.insert(FLOATS_RIGHT),
+                        float::T::left => flags.insert(FlowFlags::FLOATS_LEFT),
+                        float::T::right => flags.insert(FlowFlags::FLOATS_RIGHT),
                     }
                 }
 
                 match style.get_box().clear {
                     clear::T::none => {}
-                    clear::T::left => flags.insert(CLEARS_LEFT),
-                    clear::T::right => flags.insert(CLEARS_RIGHT),
+                    clear::T::left => flags.insert(FlowFlags::CLEARS_LEFT),
+                    clear::T::right => flags.insert(FlowFlags::CLEARS_RIGHT),
                     clear::T::both => {
-                        flags.insert(CLEARS_LEFT);
-                        flags.insert(CLEARS_RIGHT);
+                        flags.insert(FlowFlags::CLEARS_LEFT);
+                        flags.insert(FlowFlags::CLEARS_RIGHT);
                     }
                 }
 
                 if !style.get_counters().counter_reset.0.is_empty() ||
                         !style.get_counters().counter_increment.0.is_empty() {
-                    flags.insert(AFFECTS_COUNTERS)
+                    flags.insert(FlowFlags::AFFECTS_COUNTERS)
                 }
             }
-            None => flags.insert(BLOCK_POSITION_IS_STATIC | INLINE_POSITION_IS_STATIC),
+            None => flags.insert(FlowFlags::BLOCK_POSITION_IS_STATIC | FlowFlags::INLINE_POSITION_IS_STATIC),
         }
 
         // New flows start out as fully damaged.
         let mut damage = RestyleDamage::rebuild_and_reflow();
-        damage.remove(RECONSTRUCT_FLOW);
+        damage.remove(ServoRestyleDamage::RECONSTRUCT_FLOW);
 
         BaseFlow {
             restyle_damage: damage,
             children: FlowList::new(),
             intrinsic_inline_sizes: IntrinsicISizes::new(),
             position: LogicalRect::zero(writing_mode),
             overflow: Overflow::new(),
             parallel: FlowParallelInfo::new(),
@@ -1066,36 +1066,37 @@ impl BaseFlow {
 
     /// Update the 'flags' field when computed styles have changed.
     ///
     /// These flags are initially set during flow construction.  They only need to be updated here
     /// if they are based on properties that can change without triggering `RECONSTRUCT_FLOW`.
     pub fn update_flags_if_needed(&mut self, style: &ComputedValues) {
         // For absolutely-positioned flows, changes to top/bottom/left/right can cause these flags
         // to get out of date:
-        if self.restyle_damage.contains(REFLOW_OUT_OF_FLOW) {
+        if self.restyle_damage.contains(ServoRestyleDamage::REFLOW_OUT_OF_FLOW) {
             // Note: We don't need to check whether IS_ABSOLUTELY_POSITIONED has changed, because
             // changes to the 'position' property trigger flow reconstruction.
-            if self.flags.contains(IS_ABSOLUTELY_POSITIONED) {
+            if self.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
                 let logical_position = style.logical_position();
-                self.flags.set(INLINE_POSITION_IS_STATIC,
+                self.flags.set(FlowFlags::INLINE_POSITION_IS_STATIC,
                     logical_position.inline_start == LengthOrPercentageOrAuto::Auto &&
                     logical_position.inline_end == LengthOrPercentageOrAuto::Auto);
-                self.flags.set(BLOCK_POSITION_IS_STATIC,
+                self.flags.set(FlowFlags::BLOCK_POSITION_IS_STATIC,
                     logical_position.block_start == LengthOrPercentageOrAuto::Auto &&
                     logical_position.block_end == LengthOrPercentageOrAuto::Auto);
             }
         }
     }
 
     /// Return a new BaseFlow like this one but with the given children list
     pub fn clone_with_children(&self, children: FlowList) -> BaseFlow {
         BaseFlow {
             children: children,
-            restyle_damage: self.restyle_damage | REPAINT | REFLOW_OUT_OF_FLOW | REFLOW,
+            restyle_damage: self.restyle_damage | ServoRestyleDamage::REPAINT |
+                            ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW,
             parallel: FlowParallelInfo::new(),
             floats: self.floats.clone(),
             abs_descendants: self.abs_descendants.clone(),
             absolute_cb: self.absolute_cb.clone(),
             clip: self.clip.clone(),
 
             ..*self
         }
@@ -1283,17 +1284,17 @@ impl<'a> ImmutableFlowUtils for &'a Flow
 
     fn baseline_offset_of_last_line_box_in_flow(self) -> Option<Au> {
         for kid in base(self).children.iter().rev() {
             if kid.is_inline_flow() {
                 if let Some(baseline_offset) = kid.as_inline().baseline_offset_of_last_line() {
                     return Some(base(kid).position.start.b + baseline_offset)
                 }
             }
-            if kid.is_block_like() && !base(kid).flags.contains(IS_ABSOLUTELY_POSITIONED) {
+            if kid.is_block_like() && !base(kid).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
                 if let Some(baseline_offset) = kid.baseline_offset_of_last_line_box_in_flow() {
                     return Some(base(kid).position.start.b + baseline_offset)
                 }
             }
         }
         None
     }
 }
--- a/servo/components/layout/fragment.rs
+++ b/servo/components/layout/fragment.rs
@@ -14,18 +14,18 @@ use euclid::{Transform3D, Point2D, Vecto
 use floats::ClearType;
 use flow::{self, ImmutableFlowUtils};
 use flow_ref::FlowRef;
 use gfx;
 use gfx::display_list::{BLUR_INFLATION_FACTOR, OpaqueNode};
 use gfx::text::glyph::ByteIndex;
 use gfx::text::text_run::{TextRun, TextRunSlice};
 use gfx_traits::StackingContextId;
-use inline::{FIRST_FRAGMENT_OF_ELEMENT, InlineFragmentContext, InlineFragmentNodeInfo};
-use inline::{InlineMetrics, LAST_FRAGMENT_OF_ELEMENT, LineMetrics};
+use inline::{InlineFragmentNodeFlags, InlineFragmentContext, InlineFragmentNodeInfo};
+use inline::{InlineMetrics, LineMetrics};
 use ipc_channel::ipc::IpcSender;
 #[cfg(debug_assertions)]
 use layout_debug;
 use model::{self, IntrinsicISizes, IntrinsicISizesContribution, MaybeAuto, SizeConstraint};
 use model::style_length;
 use msg::constellation_msg::{BrowsingContextId, PipelineId};
 use net_traits::image::base::{Image, ImageMetadata};
 use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder};
@@ -43,17 +43,17 @@ use std::sync::{Arc, Mutex};
 use style::computed_values::{border_collapse, box_sizing, clear, color, display, mix_blend_mode};
 use style::computed_values::{overflow_wrap, overflow_x, position, text_decoration_line};
 use style::computed_values::{transform_style, white_space, word_break};
 use style::computed_values::content::ContentItem;
 use style::logical_geometry::{Direction, LogicalMargin, LogicalRect, LogicalSize, WritingMode};
 use style::properties::ComputedValues;
 use style::properties::longhands::transform::computed_value::T as TransformList;
 use style::selector_parser::RestyleDamage;
-use style::servo::restyle_damage::RECONSTRUCT_FLOW;
+use style::servo::restyle_damage::ServoRestyleDamage;
 use style::str::char_is_whitespace;
 use style::values::{self, Either, Auto};
 use style::values::computed::{Length, LengthOrPercentage, LengthOrPercentageOrAuto};
 use style::values::generics::box_::VerticalAlign;
 use text;
 use text::TextRunScanner;
 use webrender_api;
 use wrapper::ThreadSafeLayoutNodeHelpers;
@@ -528,23 +528,23 @@ pub struct ScannedTextFragmentInfo {
     /// so that we can restore the range to its original value (before line breaking occurred) when
     /// performing incremental reflow.
     pub range_end_including_stripped_whitespace: ByteIndex,
 
     pub flags: ScannedTextFlags,
 }
 
 bitflags! {
-    pub flags ScannedTextFlags: u8 {
+    pub struct ScannedTextFlags: u8 {
         /// Whether a line break is required after this fragment if wrapping on newlines (e.g. if
         /// `white-space: pre` is in effect).
-        const REQUIRES_LINE_BREAK_AFTERWARD_IF_WRAPPING_ON_NEWLINES = 0x01,
+        const REQUIRES_LINE_BREAK_AFTERWARD_IF_WRAPPING_ON_NEWLINES = 0x01;
 
         /// Is this fragment selected?
-        const SELECTED = 0x02,
+        const SELECTED = 0x02;
     }
 }
 
 impl ScannedTextFragmentInfo {
     /// Creates the information specific to a scanned text fragment from a range and a text run.
     pub fn new(run: Arc<TextRun>,
                range: Range<ByteIndex>,
                content_size: LogicalSize<Au>,
@@ -561,21 +561,21 @@ impl ScannedTextFragmentInfo {
         }
     }
 
     pub fn text(&self) -> &str {
         &self.run.text[self.range.begin().to_usize() .. self.range.end().to_usize()]
     }
 
     pub fn requires_line_break_afterward_if_wrapping_on_newlines(&self) -> bool {
-        self.flags.contains(REQUIRES_LINE_BREAK_AFTERWARD_IF_WRAPPING_ON_NEWLINES)
+        self.flags.contains(ScannedTextFlags::REQUIRES_LINE_BREAK_AFTERWARD_IF_WRAPPING_ON_NEWLINES)
     }
 
     pub fn selected(&self) -> bool {
-        self.flags.contains(SELECTED)
+        self.flags.contains(ScannedTextFlags::SELECTED)
     }
 }
 
 /// Describes how to split a fragment. This is used during line breaking as part of the return
 /// value of `find_split_info_for_inline_size()`.
 #[derive(Clone, Debug)]
 pub struct SplitInfo {
     // TODO(bjz): this should only need to be a single character index, but both values are
@@ -666,17 +666,17 @@ pub struct TruncatedFragmentInfo {
 impl Fragment {
     /// Constructs a new `Fragment` instance.
     pub fn new<N: ThreadSafeLayoutNode>(node: &N, specific: SpecificFragmentInfo, ctx: &LayoutContext) -> Fragment {
         let shared_context = ctx.shared_context();
         let style = node.style(shared_context);
         let writing_mode = style.writing_mode;
 
         let mut restyle_damage = node.restyle_damage();
-        restyle_damage.remove(RECONSTRUCT_FLOW);
+        restyle_damage.remove(ServoRestyleDamage::RECONSTRUCT_FLOW);
 
         Fragment {
             node: node.opaque(),
             style: style,
             selected_style: node.selected_style(),
             restyle_damage: restyle_damage,
             border_box: LogicalRect::zero(writing_mode),
             border_padding: LogicalMargin::zero(writing_mode),
@@ -695,17 +695,17 @@ impl Fragment {
                                       pseudo: PseudoElementType<()>,
                                       style: ServoArc<ComputedValues>,
                                       selected_style: ServoArc<ComputedValues>,
                                       mut restyle_damage: RestyleDamage,
                                       specific: SpecificFragmentInfo)
                                       -> Fragment {
         let writing_mode = style.writing_mode;
 
-        restyle_damage.remove(RECONSTRUCT_FLOW);
+        restyle_damage.remove(ServoRestyleDamage::RECONSTRUCT_FLOW);
 
         Fragment {
             node: node,
             style: style,
             selected_style: selected_style,
             restyle_damage: restyle_damage,
             border_box: LogicalRect::zero(writing_mode),
             border_padding: LogicalMargin::zero(writing_mode),
@@ -748,17 +748,17 @@ impl Fragment {
     /// preserving all the other data.
     pub fn transform(&self, size: LogicalSize<Au>, info: SpecificFragmentInfo)
                      -> Fragment {
         let new_border_box = LogicalRect::from_point_size(self.style.writing_mode,
                                                           self.border_box.start,
                                                           size);
 
         let mut restyle_damage = RestyleDamage::rebuild_and_reflow();
-        restyle_damage.remove(RECONSTRUCT_FLOW);
+        restyle_damage.remove(ServoRestyleDamage::RECONSTRUCT_FLOW);
 
         Fragment {
             node: self.node,
             style: self.style.clone(),
             selected_style: self.selected_style.clone(),
             restyle_damage: restyle_damage,
             border_box: new_border_box,
             border_padding: self.border_padding,
@@ -813,17 +813,17 @@ impl Fragment {
             )
         );
         unscanned_ellipsis_fragments.push_back(ellipsis_fragment);
         let ellipsis_fragments = with_thread_local_font_context(layout_context, |font_context| {
             TextRunScanner::new().scan_for_runs(font_context, unscanned_ellipsis_fragments)
         });
         debug_assert!(ellipsis_fragments.len() == 1);
         ellipsis_fragment = ellipsis_fragments.fragments.into_iter().next().unwrap();
-        ellipsis_fragment.flags |= IS_ELLIPSIS;
+        ellipsis_fragment.flags |= FragmentFlags::IS_ELLIPSIS;
         ellipsis_fragment
     }
 
     pub fn restyle_damage(&self) -> RestyleDamage {
         self.restyle_damage | self.specific.restyle_damage()
     }
 
     pub fn contains_node(&self, node_address: OpaqueNode) -> bool {
@@ -853,45 +853,46 @@ impl Fragment {
             SpecificFragmentInfo::Iframe(_) |
             SpecificFragmentInfo::Image(_) |
             SpecificFragmentInfo::InlineAbsolute(_) |
             SpecificFragmentInfo::Multicol |
             SpecificFragmentInfo::Svg(_) => {
                 QuantitiesIncludedInIntrinsicInlineSizes::all()
             }
             SpecificFragmentInfo::Table => {
-                INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED |
-                    INTRINSIC_INLINE_SIZE_INCLUDES_PADDING |
-                    INTRINSIC_INLINE_SIZE_INCLUDES_BORDER
+                QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED |
+                    QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_PADDING |
+                    QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_BORDER
             }
             SpecificFragmentInfo::TableCell => {
-                let base_quantities = INTRINSIC_INLINE_SIZE_INCLUDES_PADDING |
-                    INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED;
+                let base_quantities = QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_PADDING |
+                    QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED;
                 if self.style.get_inheritedtable().border_collapse ==
                         border_collapse::T::separate {
-                    base_quantities | INTRINSIC_INLINE_SIZE_INCLUDES_BORDER
+                    base_quantities | QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_BORDER
                 } else {
                     base_quantities
                 }
             }
             SpecificFragmentInfo::TableWrapper => {
-                let base_quantities = INTRINSIC_INLINE_SIZE_INCLUDES_MARGINS |
-                    INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED;
+                let base_quantities = QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_MARGINS |
+                    QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED;
                 if self.style.get_inheritedtable().border_collapse ==
                         border_collapse::T::separate {
-                    base_quantities | INTRINSIC_INLINE_SIZE_INCLUDES_BORDER
+                    base_quantities | QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_BORDER
                 } else {
                     base_quantities
                 }
             }
             SpecificFragmentInfo::TableRow => {
-                let base_quantities = INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED;
+                let base_quantities =
+                    QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED;
                 if self.style.get_inheritedtable().border_collapse ==
                         border_collapse::T::separate {
-                    base_quantities | INTRINSIC_INLINE_SIZE_INCLUDES_BORDER
+                    base_quantities | QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_BORDER
                 } else {
                     base_quantities
                 }
             }
             SpecificFragmentInfo::TruncatedFragment(_) |
             SpecificFragmentInfo::ScannedText(_) |
             SpecificFragmentInfo::TableColumn(_) |
             SpecificFragmentInfo::UnscannedText(_) |
@@ -909,36 +910,39 @@ impl Fragment {
     /// FIXME(#2261, pcwalton): This won't work well for inlines: is this OK?
     pub fn surrounding_intrinsic_inline_size(&self) -> (Au, Au) {
         let flags = self.quantities_included_in_intrinsic_inline_size();
         let style = self.style();
 
         // FIXME(pcwalton): Percentages should be relative to any definite size per CSS-SIZING.
         // This will likely need to be done by pushing down definite sizes during selector
         // cascading.
-        let margin = if flags.contains(INTRINSIC_INLINE_SIZE_INCLUDES_MARGINS) {
+        let margin = if flags.contains(
+                QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_MARGINS) {
             let margin = style.logical_margin();
             (MaybeAuto::from_style(margin.inline_start, Au(0)).specified_or_zero() +
              MaybeAuto::from_style(margin.inline_end, Au(0)).specified_or_zero())
         } else {
             Au(0)
         };
 
         // FIXME(pcwalton): Percentages should be relative to any definite size per CSS-SIZING.
         // This will likely need to be done by pushing down definite sizes during selector
         // cascading.
-        let padding = if flags.contains(INTRINSIC_INLINE_SIZE_INCLUDES_PADDING) {
+        let padding = if flags.contains(
+                QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_PADDING) {
             let padding = style.logical_padding();
             (padding.inline_start.to_used_value(Au(0)) +
              padding.inline_end.to_used_value(Au(0)))
         } else {
             Au(0)
         };
 
-        let border = if flags.contains(INTRINSIC_INLINE_SIZE_INCLUDES_BORDER) {
+        let border = if flags.contains(
+                QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_BORDER) {
             self.border_width().inline_start_end()
         } else {
             Au(0)
         };
 
         (border + padding, margin)
     }
 
@@ -947,17 +951,17 @@ impl Fragment {
     pub fn style_specified_intrinsic_inline_size(&self) -> IntrinsicISizesContribution {
         let flags = self.quantities_included_in_intrinsic_inline_size();
         let style = self.style();
 
         // FIXME(#2261, pcwalton): This won't work well for inlines: is this OK?
         let (border_padding, margin) = self.surrounding_intrinsic_inline_size();
 
         let mut specified = Au(0);
-        if flags.contains(INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED) {
+        if flags.contains(QuantitiesIncludedInIntrinsicInlineSizes::INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED) {
             specified = MaybeAuto::from_style(style.content_inline_size(),
                                               Au(0)).specified_or_zero();
             specified = max(style.min_inline_size().to_used_value(Au(0)), specified);
             if let Some(max) = style.max_inline_size().to_used_value(Au(0)) {
                 specified = min(specified, max)
             }
 
             if self.style.get_position().box_sizing == box_sizing::T::border_box {
@@ -1198,20 +1202,20 @@ impl Fragment {
         // writing mode to compute the child logical sizes.
         let writing_mode = self.style.writing_mode;
         let context_border = match self.inline_context {
             None => LogicalMargin::zero(writing_mode),
             Some(ref inline_fragment_context) => {
                 inline_fragment_context.nodes.iter().fold(style_border_width, |accumulator, node| {
                     let mut this_border_width =
                         node.style.border_width_for_writing_mode(writing_mode);
-                    if !node.flags.contains(FIRST_FRAGMENT_OF_ELEMENT) {
+                    if !node.flags.contains(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT) {
                         this_border_width.inline_start = Au(0)
                     }
-                    if !node.flags.contains(LAST_FRAGMENT_OF_ELEMENT) {
+                    if !node.flags.contains(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT) {
                         this_border_width.inline_end = Au(0)
                     }
                     accumulator + this_border_width
                 })
             }
         };
         style_border_width + context_border
     }
@@ -1255,23 +1259,25 @@ impl Fragment {
                     MaybeAuto::from_style(margin.inline_end,
                                           containing_block_inline_size).specified_or_zero();
             }
         }
 
         if let Some(ref inline_context) = self.inline_context {
             for node in &inline_context.nodes {
                 let margin = node.style.logical_margin();
-                let this_inline_start_margin = if !node.flags.contains(FIRST_FRAGMENT_OF_ELEMENT) {
+                let this_inline_start_margin = if !node.flags.contains(
+                        InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT) {
                     Au(0)
                 } else {
                     MaybeAuto::from_style(margin.inline_start,
                                           containing_block_inline_size).specified_or_zero()
                 };
-                let this_inline_end_margin = if !node.flags.contains(LAST_FRAGMENT_OF_ELEMENT) {
+                let this_inline_end_margin = if!node.flags.contains(
+                        InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT) {
                     Au(0)
                 } else {
                     MaybeAuto::from_style(margin.inline_end,
                                           containing_block_inline_size).specified_or_zero()
                 };
 
                 self.margin.inline_start += this_inline_start_margin;
                 self.margin.inline_end += this_inline_end_margin;
@@ -1334,20 +1340,20 @@ impl Fragment {
             (&SpecificFragmentInfo::TableWrapper, _) => {
                 LogicalMargin::zero(self.style.writing_mode)
             }
             (_, &Some(ref inline_fragment_context)) => {
                 let writing_mode = self.style.writing_mode;
                 let zero_padding = LogicalMargin::zero(writing_mode);
                 inline_fragment_context.nodes.iter().fold(zero_padding, |accumulator, node| {
                     let mut padding = model::padding_from_style(&*node.style, Au(0), writing_mode);
-                    if !node.flags.contains(FIRST_FRAGMENT_OF_ELEMENT) {
+                    if !node.flags.contains(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT) {
                         padding.inline_start = Au(0)
                     }
-                    if !node.flags.contains(LAST_FRAGMENT_OF_ELEMENT) {
+                    if !node.flags.contains(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT) {
                         padding.inline_end = Au(0)
                     }
                     accumulator + padding
                 })
             }
         };
 
         self.border_padding = border + padding_from_style + padding_from_inline_fragment_context
@@ -1579,22 +1585,22 @@ impl Fragment {
 
         // Take borders and padding for parent inline fragments into account.
         let writing_mode = self.style.writing_mode;
         if let Some(ref context) = self.inline_context {
             for node in &context.nodes {
                 let mut border_width = node.style.logical_border_width();
                 let mut padding = model::padding_from_style(&*node.style, Au(0), writing_mode);
                 let mut margin = model::specified_margin_from_style(&*node.style, writing_mode);
-                if !node.flags.contains(FIRST_FRAGMENT_OF_ELEMENT) {
+                if !node.flags.contains(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT) {
                     border_width.inline_start = Au(0);
                     padding.inline_start = Au(0);
                     margin.inline_start = Au(0);
                 }
-                if !node.flags.contains(LAST_FRAGMENT_OF_ELEMENT) {
+                if !node.flags.contains(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT) {
                     border_width.inline_end = Au(0);
                     padding.inline_end = Au(0);
                     margin.inline_end = Au(0);
                 }
 
                 result.surrounding_size =
                     result.surrounding_size +
                     border_width.inline_start_end() +
@@ -1642,19 +1648,19 @@ impl Fragment {
         let text_fragment_info = match self.specific {
             SpecificFragmentInfo::ScannedText(ref text_fragment_info)
                 => text_fragment_info,
             _   => return None,
         };
 
         let mut flags = SplitOptions::empty();
         if starts_line {
-            flags.insert(STARTS_LINE);
+            flags.insert(SplitOptions::STARTS_LINE);
             if self.style().get_inheritedtext().overflow_wrap == overflow_wrap::T::break_word {
-                flags.insert(RETRY_AT_CHARACTER_BOUNDARIES)
+                flags.insert(SplitOptions::RETRY_AT_CHARACTER_BOUNDARIES)
             }
         }
 
         match self.style().get_inheritedtext().word_break {
             word_break::T::normal | word_break::T::keep_all => {
                 // Break at normal word boundaries. keep-all forbids soft wrap opportunities.
                 let natural_word_breaking_strategy =
                     text_fragment_info.run.natural_word_slices_in_range(&text_fragment_info.range);
@@ -1662,17 +1668,17 @@ impl Fragment {
                     natural_word_breaking_strategy,
                     max_inline_size,
                     flags)
             }
             word_break::T::break_all => {
                 // Break at character boundaries.
                 let character_breaking_strategy =
                     text_fragment_info.run.character_slices_in_range(&text_fragment_info.range);
-                flags.remove(RETRY_AT_CHARACTER_BOUNDARIES);
+                flags.remove(SplitOptions::RETRY_AT_CHARACTER_BOUNDARIES);
                 self.calculate_split_position_using_breaking_strategy(
                     character_breaking_strategy,
                     max_inline_size,
                     flags)
             }
         }
     }
 
@@ -1825,31 +1831,31 @@ impl Fragment {
                        inline_end);
             }
 
             // If we failed to find a suitable split point, we're on the verge of overflowing the
             // line.
             if split_is_empty || overflowing {
                 // If we've been instructed to retry at character boundaries (probably via
                 // `overflow-wrap: break-word`), do so.
-                if flags.contains(RETRY_AT_CHARACTER_BOUNDARIES) {
+                if flags.contains(SplitOptions::RETRY_AT_CHARACTER_BOUNDARIES) {
                     let character_breaking_strategy =
                         text_fragment_info.run
                                           .character_slices_in_range(&text_fragment_info.range);
                     let mut flags = flags;
-                    flags.remove(RETRY_AT_CHARACTER_BOUNDARIES);
+                    flags.remove(SplitOptions::RETRY_AT_CHARACTER_BOUNDARIES);
                     return self.calculate_split_position_using_breaking_strategy(
                         character_breaking_strategy,
                         max_inline_size,
                         flags)
                 }
 
                 // We aren't at the start of the line, so don't overflow. Let inline layout wrap to
                 // the next line instead.
-                if !flags.contains(STARTS_LINE) {
+                if !flags.contains(SplitOptions::STARTS_LINE) {
                     return None
                 }
             }
 
             break
         }
 
         let split_is_empty = inline_start_range.is_empty() &&
@@ -1875,17 +1881,17 @@ impl Fragment {
     pub fn merge_with(&mut self, next_fragment: Fragment) {
         match (&mut self.specific, &next_fragment.specific) {
             (&mut SpecificFragmentInfo::ScannedText(ref mut this_info),
              &SpecificFragmentInfo::ScannedText(ref other_info)) => {
                 debug_assert!(Arc::ptr_eq(&this_info.run, &other_info.run));
                 this_info.range_end_including_stripped_whitespace =
                     other_info.range_end_including_stripped_whitespace;
                 if other_info.requires_line_break_afterward_if_wrapping_on_newlines() {
-                    this_info.flags.insert(REQUIRES_LINE_BREAK_AFTERWARD_IF_WRAPPING_ON_NEWLINES);
+                    this_info.flags.insert(ScannedTextFlags::REQUIRES_LINE_BREAK_AFTERWARD_IF_WRAPPING_ON_NEWLINES);
                 }
                 if other_info.insertion_point.is_some() {
                     this_info.insertion_point = other_info.insertion_point;
                 }
                 self.border_padding.inline_end = next_fragment.border_padding.inline_end;
                 self.margin.inline_end = next_fragment.margin.inline_end;
             }
             _ => panic!("Can only merge two scanned-text fragments!"),
@@ -2335,17 +2341,17 @@ impl Fragment {
                 if first_unscanned_text.text.ends_with('\n') {
                     return false
                 }
 
                 // If this node has any styles that have border/padding/margins on the following
                 // side, then we can't merge with the next fragment.
                 if let Some(ref inline_context) = self.inline_context {
                     for inline_context_node in inline_context.nodes.iter() {
-                        if !inline_context_node.flags.contains(LAST_FRAGMENT_OF_ELEMENT) {
+                        if !inline_context_node.flags.contains(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT) {
                             continue
                         }
                         if inline_context_node.style.logical_margin().inline_end !=
                                 LengthOrPercentageOrAuto::Length(Length::new(0.)) {
                             return false
                         }
                         if inline_context_node.style.logical_padding().inline_end !=
                                 LengthOrPercentage::Length(Length::new(0.)) {
@@ -2356,17 +2362,17 @@ impl Fragment {
                         }
                     }
                 }
 
                 // If the next fragment has any styles that have border/padding/margins on the
                 // preceding side, then it can't merge with us.
                 if let Some(ref inline_context) = other.inline_context {
                     for inline_context_node in inline_context.nodes.iter() {
-                        if !inline_context_node.flags.contains(FIRST_FRAGMENT_OF_ELEMENT) {
+                        if !inline_context_node.flags.contains(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT) {
                             continue
                         }
                         if inline_context_node.style.logical_margin().inline_start !=
                                 LengthOrPercentageOrAuto::Length(Length::new(0.)) {
                             return false
                         }
                         if inline_context_node.style.logical_padding().inline_start !=
                                 LengthOrPercentage::Length(Length::new(0.)) {
@@ -2802,47 +2808,48 @@ impl Fragment {
         if let Some(ref mut inline_context_of_this_fragment) = self.inline_context {
             if let Some(ref inline_context_of_next_fragment) = next_fragment.inline_context {
                 for (inline_context_node_from_this_fragment,
                      inline_context_node_from_next_fragment)
                     in inline_context_of_this_fragment.nodes.iter_mut().rev()
                         .zip(inline_context_of_next_fragment.nodes.iter().rev())
                 {
                     if !inline_context_node_from_next_fragment.flags.contains(
-                            LAST_FRAGMENT_OF_ELEMENT) {
+                            InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT) {
                         continue
                     }
                     if inline_context_node_from_next_fragment.address !=
                             inline_context_node_from_this_fragment.address {
                         continue
                     }
-                    inline_context_node_from_this_fragment.flags.insert(LAST_FRAGMENT_OF_ELEMENT);
+                    inline_context_node_from_this_fragment.flags.insert(
+                        InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT);
                 }
             }
         }
     }
 
     pub fn meld_with_prev_inline_fragment(&mut self, prev_fragment: &Fragment) {
         if let Some(ref mut inline_context_of_this_fragment) = self.inline_context {
             if let Some(ref inline_context_of_prev_fragment) = prev_fragment.inline_context {
                 for (inline_context_node_from_prev_fragment,
                      inline_context_node_from_this_fragment)
                     in inline_context_of_prev_fragment.nodes.iter().rev().zip(
                             inline_context_of_this_fragment.nodes.iter_mut().rev())
                 {
                     if !inline_context_node_from_prev_fragment.flags.contains(
-                            FIRST_FRAGMENT_OF_ELEMENT) {
+                            InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT) {
                         continue
                     }
                     if inline_context_node_from_prev_fragment.address !=
                             inline_context_node_from_this_fragment.address {
                         continue
                     }
                     inline_context_node_from_this_fragment.flags.insert(
-                        FIRST_FRAGMENT_OF_ELEMENT);
+                        InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT);
                 }
             }
         }
     }
 
     /// Returns true if any of the inline styles associated with this fragment have
     /// `vertical-align` set to `top` or `bottom`.
     pub fn is_vertically_aligned_to_top_or_bottom(&self) -> bool {
@@ -2970,33 +2977,33 @@ impl fmt::Debug for Fragment {
             self.border_box,
             border_padding_string,
             margin_string,
             damage_string)
     }
 }
 
 bitflags! {
-    flags QuantitiesIncludedInIntrinsicInlineSizes: u8 {
-        const INTRINSIC_INLINE_SIZE_INCLUDES_MARGINS = 0x01,
-        const INTRINSIC_INLINE_SIZE_INCLUDES_PADDING = 0x02,
-        const INTRINSIC_INLINE_SIZE_INCLUDES_BORDER = 0x04,
-        const INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED = 0x08,
+    struct QuantitiesIncludedInIntrinsicInlineSizes: u8 {
+        const INTRINSIC_INLINE_SIZE_INCLUDES_MARGINS = 0x01;
+        const INTRINSIC_INLINE_SIZE_INCLUDES_PADDING = 0x02;
+        const INTRINSIC_INLINE_SIZE_INCLUDES_BORDER = 0x04;
+        const INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED = 0x08;
     }
 }
 
 bitflags! {
     // Various flags we can use when splitting fragments. See
     // `calculate_split_position_using_breaking_strategy()`.
-    flags SplitOptions: u8 {
+    struct SplitOptions: u8 {
         #[doc = "True if this is the first fragment on the line."]
-        const STARTS_LINE = 0x01,
+        const STARTS_LINE = 0x01;
         #[doc = "True if we should attempt to split at character boundaries if this split fails. \
                  This is used to implement `overflow-wrap: break-word`."]
-        const RETRY_AT_CHARACTER_BOUNDARIES = 0x02,
+        const RETRY_AT_CHARACTER_BOUNDARIES = 0x02;
     }
 }
 
 /// A top-down fragment border box iteration handler.
 pub trait FragmentBorderBoxIterator {
     /// The operation to perform.
     fn process(&mut self, fragment: &Fragment, level: i32, overflow: &Rect<Au>);
 
@@ -3099,24 +3106,24 @@ impl Overflow {
 
     pub fn translate(&mut self, by: &Vector2D<Au>) {
         self.scroll = self.scroll.translate(by);
         self.paint = self.paint.translate(by);
     }
 }
 
 bitflags! {
-    pub flags FragmentFlags: u8 {
+    pub struct FragmentFlags: u8 {
         // TODO(stshine): find a better name since these flags can also be used for grid item.
         /// Whether this fragment represents a child in a row flex container.
-        const IS_INLINE_FLEX_ITEM = 0b0000_0001,
+        const IS_INLINE_FLEX_ITEM = 0b0000_0001;
         /// Whether this fragment represents a child in a column flex container.
-        const IS_BLOCK_FLEX_ITEM = 0b0000_0010,
+        const IS_BLOCK_FLEX_ITEM = 0b0000_0010;
         /// Whether this fragment represents the generated text from a text-overflow clip.
-        const IS_ELLIPSIS = 0b0000_0100,
+        const IS_ELLIPSIS = 0b0000_0100;
     }
 }
 
 /// Specified distances from the margin edge of a block to its content in the inline direction.
 /// These are returned by `guess_inline_content_edge_offsets()` and are used in the float placement
 /// speculation logic.
 #[derive(Clone, Copy, Debug)]
 pub struct SpeculatedInlineContentEdgeOffsets {
--- a/servo/components/layout/generated_content.rs
+++ b/servo/components/layout/generated_content.rs
@@ -4,27 +4,27 @@
 
 //! The generated content assignment phase.
 //!
 //! This phase handles CSS counters, quotes, and ordered lists per CSS § 12.3-12.5. It cannot be
 //! done in parallel and is therefore a sequential pass that runs on as little of the flow tree
 //! as possible.
 
 use context::{LayoutContext, with_thread_local_font_context};
-use flow::{self, AFFECTS_COUNTERS, Flow, HAS_COUNTER_AFFECTING_CHILDREN, ImmutableFlowUtils};
+use flow::{self, Flow, FlowFlags, ImmutableFlowUtils};
 use fragment::{Fragment, GeneratedContentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo};
 use gfx::display_list::OpaqueNode;
 use script_layout_interface::wrapper_traits::PseudoElementType;
 use smallvec::SmallVec;
 use std::collections::{HashMap, LinkedList};
 use style::computed_values::{display, list_style_type};
 use style::computed_values::content::ContentItem;
 use style::properties::ComputedValues;
 use style::selector_parser::RestyleDamage;
-use style::servo::restyle_damage::RESOLVE_GENERATED_CONTENT;
+use style::servo::restyle_damage::ServoRestyleDamage;
 use text::TextRunScanner;
 use traversal::InorderFlowTraversal;
 
 // Decimal styles per CSS-COUNTER-STYLES § 6.1:
 static DECIMAL: [char; 10] = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ];
 // TODO(pcwalton): `decimal-leading-zero`
 static ARABIC_INDIC: [char; 10] = [ '٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩' ];
 // TODO(pcwalton): `armenian`, `upper-armenian`, `lower-armenian`
@@ -126,18 +126,18 @@ impl<'a> InorderFlowTraversal for Resolv
             is_block: flow.is_block_like(),
             incremented: false,
         };
         flow.mutate_fragments(&mut |fragment| mutator.mutate_fragment(fragment))
     }
 
     #[inline]
     fn should_process_subtree(&mut self, flow: &mut Flow) -> bool {
-        flow::base(flow).restyle_damage.intersects(RESOLVE_GENERATED_CONTENT) ||
-            flow::base(flow).flags.intersects(AFFECTS_COUNTERS | HAS_COUNTER_AFFECTING_CHILDREN)
+        flow::base(flow).restyle_damage.intersects(ServoRestyleDamage::RESOLVE_GENERATED_CONTENT) ||
+            flow::base(flow).flags.intersects(FlowFlags::AFFECTS_COUNTERS | FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN)
     }
 }
 
 /// The object that mutates the generated content fragments.
 struct ResolveGeneratedContentFragmentMutator<'a, 'b: 'a> {
     /// The traversal.
     traversal: &'a mut ResolveGeneratedContent<'b>,
     /// The level we're at in the flow tree.
--- a/servo/components/layout/incremental.rs
+++ b/servo/components/layout/incremental.rs
@@ -1,86 +1,86 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-use flow::{self, AFFECTS_COUNTERS, Flow, HAS_COUNTER_AFFECTING_CHILDREN, IS_ABSOLUTELY_POSITIONED};
+use flow::{self, FlowFlags, Flow};
 use style::computed_values::float;
 use style::selector_parser::RestyleDamage;
-use style::servo::restyle_damage::{REFLOW, RECONSTRUCT_FLOW};
+use style::servo::restyle_damage::ServoRestyleDamage;
 
 /// Used in a flow traversal to indicate whether this re-layout should be incremental or not.
 #[derive(Clone, Copy, PartialEq)]
 pub enum RelayoutMode {
     Incremental,
     Force
 }
 
 bitflags! {
-    pub flags SpecialRestyleDamage: u8 {
+    pub struct SpecialRestyleDamage: u8 {
         #[doc = "If this flag is set, we need to reflow the entire document. This is more or less a \
                  temporary hack to deal with cases that we don't handle incrementally yet."]
-        const REFLOW_ENTIRE_DOCUMENT = 0x01,
+        const REFLOW_ENTIRE_DOCUMENT = 0x01;
     }
 }
 
 pub trait LayoutDamageComputation {
     fn compute_layout_damage(self) -> SpecialRestyleDamage;
     fn reflow_entire_document(self);
 }
 
 impl<'a> LayoutDamageComputation for &'a mut Flow {
     fn compute_layout_damage(self) -> SpecialRestyleDamage {
         let mut special_damage = SpecialRestyleDamage::empty();
-        let is_absolutely_positioned = flow::base(self).flags.contains(IS_ABSOLUTELY_POSITIONED);
+        let is_absolutely_positioned = flow::base(self).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED);
 
         // In addition to damage, we use this phase to compute whether nodes affect CSS counters.
         let mut has_counter_affecting_children = false;
 
         {
             let self_base = flow::mut_base(self);
             // Take a snapshot of the parent damage before updating it with damage from children.
             let parent_damage = self_base.restyle_damage;
 
             for kid in self_base.children.iter_mut() {
                 let child_is_absolutely_positioned =
-                    flow::base(kid).flags.contains(IS_ABSOLUTELY_POSITIONED);
+                    flow::base(kid).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED);
                 flow::mut_base(kid).restyle_damage.insert(
                     parent_damage.damage_for_child(is_absolutely_positioned,
                                                    child_is_absolutely_positioned));
                 {
                     let kid: &mut Flow = kid;
                     special_damage.insert(kid.compute_layout_damage());
                 }
                 self_base.restyle_damage
                          .insert(flow::base(kid).restyle_damage.damage_for_parent(
                                  child_is_absolutely_positioned));
 
                 has_counter_affecting_children = has_counter_affecting_children ||
-                    flow::base(kid).flags.intersects(AFFECTS_COUNTERS |
-                                                     HAS_COUNTER_AFFECTING_CHILDREN);
+                    flow::base(kid).flags.intersects(FlowFlags::AFFECTS_COUNTERS |
+                                                     FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN);
             }
         }
 
         let self_base = flow::mut_base(self);
         if self_base.flags.float_kind() != float::T::none &&
-                self_base.restyle_damage.intersects(REFLOW) {
-            special_damage.insert(REFLOW_ENTIRE_DOCUMENT);
+                self_base.restyle_damage.intersects(ServoRestyleDamage::REFLOW) {
+            special_damage.insert(SpecialRestyleDamage::REFLOW_ENTIRE_DOCUMENT);
         }
 
         if has_counter_affecting_children {
-            self_base.flags.insert(HAS_COUNTER_AFFECTING_CHILDREN)
+            self_base.flags.insert(FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN)
         } else {
-            self_base.flags.remove(HAS_COUNTER_AFFECTING_CHILDREN)
+            self_base.flags.remove(FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN)
         }
 
         special_damage
     }
 
     fn reflow_entire_document(self) {
         let self_base = flow::mut_base(self);
         self_base.restyle_damage.insert(RestyleDamage::rebuild_and_reflow());
-        self_base.restyle_damage.remove(RECONSTRUCT_FLOW);
+        self_base.restyle_damage.remove(ServoRestyleDamage::RECONSTRUCT_FLOW);
         for kid in self_base.children.iter_mut() {
             kid.reflow_entire_document();
         }
     }
 }
--- a/servo/components/layout/inline.rs
+++ b/servo/components/layout/inline.rs
@@ -8,20 +8,20 @@ use ServoArc;
 use app_units::{Au, MIN_AU};
 use block::AbsoluteAssignBSizesTraversal;
 use context::LayoutContext;
 use display_list_builder::{DisplayListBuildState, InlineFlowDisplayListBuilding};
 use display_list_builder::StackingContextCollectionState;
 use euclid::{Point2D, Size2D};
 use floats::{FloatKind, Floats, PlacementInfo};
 use flow::{self, BaseFlow, Flow, FlowClass, ForceNonfloatedFlag};
-use flow::{CONTAINS_TEXT_OR_REPLACED_FRAGMENTS, EarlyAbsolutePositionInfo, OpaqueFlow};
+use flow::{FlowFlags, EarlyAbsolutePositionInfo, OpaqueFlow};
 use flow_ref::FlowRef;
 use fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, Overflow};
-use fragment::IS_ELLIPSIS;
+use fragment::FragmentFlags;
 use fragment::SpecificFragmentInfo;
 use gfx::display_list::OpaqueNode;
 use gfx::font::FontMetrics;
 use gfx::font_context::FontContext;
 use gfx_traits::print_tree::PrintTree;
 use layout_debug;
 use model::IntrinsicISizesContribution;
 use range::{Range, RangeIndex};
@@ -29,17 +29,17 @@ use script_layout_interface::wrapper_tra
 use std::{fmt, i32, isize, mem};
 use std::cmp::max;
 use std::collections::VecDeque;
 use std::sync::Arc;
 use style::computed_values::{display, overflow_x, position, text_align, text_justify};
 use style::computed_values::{vertical_align, white_space};
 use style::logical_geometry::{LogicalRect, LogicalSize, WritingMode};
 use style::properties::ComputedValues;
-use style::servo::restyle_damage::{BUBBLE_ISIZES, REFLOW, REFLOW_OUT_OF_FLOW, RESOLVE_GENERATED_CONTENT};
+use style::servo::restyle_damage::ServoRestyleDamage;
 use style::values::generics::box_::VerticalAlign;
 use style::values::specified::text::TextOverflowSide;
 use text;
 use traversal::PreorderFlowTraversal;
 use unicode_bidi as bidi;
 
 /// `Line`s are represented as offsets into the child list, rather than
 /// as an object that "owns" fragments. Choosing a different set of line
@@ -340,17 +340,17 @@ impl LineBreaker {
             // Acquire the next fragment to lay out from the work list or fragment list, as
             // appropriate.
             let fragment = match self.next_unbroken_fragment(&mut old_fragment_iter) {
                 None => break,
                 Some(fragment) => fragment,
             };
 
             // Do not reflow truncated fragments. Reflow the original fragment only.
-            let fragment = if fragment.flags.contains(IS_ELLIPSIS) {
+            let fragment = if fragment.flags.contains(FragmentFlags::IS_ELLIPSIS) {
                 continue
             } else if let SpecificFragmentInfo::TruncatedFragment(info) = fragment.specific {
                 info.full
             } else {
                 fragment
             };
 
             // Try to append the fragment.
@@ -660,25 +660,25 @@ impl LineBreaker {
 
         // Push the first fragment onto the line we're working on and start off the next line with
         // the second fragment. If there's no second fragment, the next line will start off empty.
         match (inline_start_fragment, inline_end_fragment) {
             (Some(mut inline_start_fragment), Some(mut inline_end_fragment)) => {
                 inline_start_fragment.border_padding.inline_end = Au(0);
                 if let Some(ref mut inline_context) = inline_start_fragment.inline_context {
                     for node in &mut inline_context.nodes {
-                        node.flags.remove(LAST_FRAGMENT_OF_ELEMENT);
+                        node.flags.remove(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT);
                     }
                 }
                 inline_start_fragment.border_box.size.inline += inline_start_fragment.border_padding.inline_start;
 
                 inline_end_fragment.border_padding.inline_start = Au(0);
                 if let Some(ref mut inline_context) = inline_end_fragment.inline_context {
                     for node in &mut inline_context.nodes {
-                        node.flags.remove(FIRST_FRAGMENT_OF_ELEMENT);
+                        node.flags.remove(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT);
                     }
                 }
                 inline_end_fragment.border_box.size.inline += inline_end_fragment.border_padding.inline_end;
 
                 self.push_fragment_to_line(layout_context,
                                            inline_start_fragment,
                                            LineFlushMode::Flush);
                 self.work_list.push_front(inline_end_fragment)
@@ -892,17 +892,17 @@ impl InlineFlow {
             base: BaseFlow::new(None, writing_mode, ForceNonfloatedFlag::ForceNonfloated),
             fragments: fragments,
             lines: Vec::new(),
             minimum_line_metrics: LineMetrics::new(Au(0), Au(0)),
             first_line_indentation: Au(0),
         };
 
         if flow.fragments.fragments.iter().any(Fragment::is_unscanned_generated_content) {
-            flow.base.restyle_damage.insert(RESOLVE_GENERATED_CONTENT);
+            flow.base.restyle_damage.insert(ServoRestyleDamage::RESOLVE_GENERATED_CONTENT);
         }
 
         flow
     }
 
     /// Sets fragment positions in the inline direction based on alignment for one line. This
     /// performs text justification if mandated by the style.
     fn set_inline_fragment_positions(fragments: &mut InlineFragments,
@@ -1308,17 +1308,17 @@ impl Flow for InlineFlow {
         let _scope = layout_debug_scope!("inline::bubble_inline_sizes {:x}",
                                          self.base.debug_id());
 
         let writing_mode = self.base.writing_mode;
         for kid in self.base.child_iter_mut() {
             flow::mut_base(kid).floats = Floats::new(writing_mode);
         }
 
-        self.base.flags.remove(CONTAINS_TEXT_OR_REPLACED_FRAGMENTS);
+        self.base.flags.remove(FlowFlags::CONTAINS_TEXT_OR_REPLACED_FRAGMENTS);
 
         let mut intrinsic_sizes_for_flow = IntrinsicISizesContribution::new();
         let mut intrinsic_sizes_for_inline_run = IntrinsicISizesContribution::new();
         let mut intrinsic_sizes_for_nonbroken_run = IntrinsicISizesContribution::new();
         for fragment in &mut self.fragments.fragments {
             let intrinsic_sizes_for_fragment = fragment.compute_intrinsic_inline_sizes().finish();
             match fragment.style.get_inheritedtext().white_space {
                 white_space::T::nowrap => {
@@ -1367,20 +1367,20 @@ impl Flow for InlineFlow {
                     intrinsic_sizes_for_inline_run.union_inline(
                         &intrinsic_sizes_for_nonbroken_run.finish());
                     intrinsic_sizes_for_nonbroken_run = IntrinsicISizesContribution::new();
 
                     intrinsic_sizes_for_nonbroken_run.union_inline(&intrinsic_sizes_for_fragment);
                 }
             }
 
-            fragment.restyle_damage.remove(BUBBLE_ISIZES);
+            fragment.restyle_damage.remove(ServoRestyleDamage::BUBBLE_ISIZES);
 
             if fragment.is_text_or_replaced() {
-                self.base.flags.insert(CONTAINS_TEXT_OR_REPLACED_FRAGMENTS);
+                self.base.flags.insert(FlowFlags::CONTAINS_TEXT_OR_REPLACED_FRAGMENTS);
             }
         }
 
         // Flush any remaining nonbroken-run and inline-run intrinsic sizes.
         intrinsic_sizes_for_inline_run.union_inline(&intrinsic_sizes_for_nonbroken_run.finish());
         intrinsic_sizes_for_flow.union_block(&intrinsic_sizes_for_inline_run.finish());
 
         // Finish up the computation.
@@ -1530,19 +1530,19 @@ impl Flow for InlineFlow {
                         relative_containing_block_size: containing_block_size,
                         relative_containing_block_mode: writing_mode,
                     };
                 }
                 _ => (),
             }
         });
 
-        self.base.restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW);
+        self.base.restyle_damage.remove(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW);
         for fragment in &mut self.fragments.fragments {
-            fragment.restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW);
+            fragment.restyle_damage.remove(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW);
         }
     }
 
     fn compute_stacking_relative_position(&mut self, _: &LayoutContext) {
         // First, gather up the positions of all the containing blocks (if any).
         //
         // FIXME(pcwalton): This will get the absolute containing blocks inside `...` wrong in the
         // case of something like:
@@ -1761,19 +1761,19 @@ pub struct InlineFragmentNodeInfo {
     pub address: OpaqueNode,
     pub style: ServoArc<ComputedValues>,
     pub selected_style: ServoArc<ComputedValues>,
     pub pseudo: PseudoElementType<()>,
     pub flags: InlineFragmentNodeFlags,
 }
 
 bitflags! {
-    pub flags InlineFragmentNodeFlags: u8 {
-        const FIRST_FRAGMENT_OF_ELEMENT = 0x01,
-        const LAST_FRAGMENT_OF_ELEMENT = 0x02,
+    pub struct InlineFragmentNodeFlags: u8 {
+        const FIRST_FRAGMENT_OF_ELEMENT = 0x01;
+        const LAST_FRAGMENT_OF_ELEMENT = 0x02;
     }
 }
 
 impl fmt::Debug for InlineFragmentNodeInfo {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         write!(f, "{:?}", self.flags.bits())
     }
 }
--- a/servo/components/layout/list_item.rs
+++ b/servo/components/layout/list_item.rs
@@ -17,17 +17,17 @@ use floats::FloatKind;
 use flow::{Flow, FlowClass, OpaqueFlow};
 use fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, GeneratedContentInfo};
 use fragment::Overflow;
 use generated_content;
 use inline::InlineFlow;
 use style::computed_values::{list_style_type, position};
 use style::logical_geometry::LogicalSize;
 use style::properties::ComputedValues;
-use style::servo::restyle_damage::RESOLVE_GENERATED_CONTENT;
+use style::servo::restyle_damage::ServoRestyleDamage;
 
 #[allow(unsafe_code)]
 unsafe impl ::flow::HasBaseFlow for ListItemFlow {}
 
 /// A block with the CSS `display` property equal to `list-item`.
 #[derive(Debug)]
 #[repr(C)]
 pub struct ListItemFlow {
@@ -51,17 +51,17 @@ impl ListItemFlow {
         if let Some(ref marker) = this.marker_fragments.first() {
             match marker.style().get_list().list_style_type {
                 list_style_type::T::disc |
                 list_style_type::T::none |
                 list_style_type::T::circle |
                 list_style_type::T::square |
                 list_style_type::T::disclosure_open |
                 list_style_type::T::disclosure_closed => {}
-                _ => this.block_flow.base.restyle_damage.insert(RESOLVE_GENERATED_CONTENT),
+                _ => this.block_flow.base.restyle_damage.insert(ServoRestyleDamage::RESOLVE_GENERATED_CONTENT),
             }
         }
 
         this
     }
 }
 
 impl Flow for ListItemFlow {
--- a/servo/components/layout/query.rs
+++ b/servo/components/layout/query.rs
@@ -6,17 +6,17 @@
 
 use app_units::Au;
 use construct::ConstructionResult;
 use context::LayoutContext;
 use euclid::{Point2D, Vector2D, Rect, Size2D};
 use flow::{self, Flow};
 use fragment::{Fragment, FragmentBorderBoxIterator, SpecificFragmentInfo};
 use gfx::display_list::{DisplayList, OpaqueNode, ScrollOffsetMap};
-use inline::LAST_FRAGMENT_OF_ELEMENT;
+use inline::InlineFragmentNodeFlags;
 use ipc_channel::ipc::IpcSender;
 use msg::constellation_msg::PipelineId;
 use opaque_node::OpaqueNodeMethods;
 use script_layout_interface::rpc::{ContentBoxResponse, ContentBoxesResponse, LayoutRPC};
 use script_layout_interface::rpc::{MarginStyleResponse, NodeGeometryResponse};
 use script_layout_interface::rpc::{NodeOverflowResponse, NodeScrollRootIdResponse};
 use script_layout_interface::rpc::{OffsetParentResponse, ResolvedStyleResponse, TextIndexResponse};
 use script_layout_interface::wrapper_traits::{LayoutNode, ThreadSafeLayoutElement, ThreadSafeLayoutNode};
@@ -557,17 +557,17 @@ impl FragmentBorderBoxIterator for Paren
 
                     self.node_offset_box = Some(NodeOffsetBoxInfo {
                         offset: border_box.origin,
                         rectangle: *border_box,
                     });
                 },
             }
 
-            if node.flags.contains(LAST_FRAGMENT_OF_ELEMENT) {
+            if node.flags.contains(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT) {
                 self.has_processed_node = true;
             }
         } else if self.node_offset_box.is_none() {
             // TODO(gw): Is there a less fragile way of checking whether this
             // fragment is the body element, rather than just checking that
             // it's at level 1 (below the root node)?
             let is_body_element = level == 1;
 
--- a/servo/components/layout/sequential.rs
+++ b/servo/components/layout/sequential.rs
@@ -4,22 +4,22 @@
 
 //! Implements sequential traversals over the DOM and flow trees.
 
 use app_units::Au;
 use context::LayoutContext;
 use display_list_builder::{DisplayListBuildState, StackingContextCollectionState};
 use euclid::{Point2D, Vector2D};
 use floats::SpeculatedFloatPlacement;
-use flow::{self, Flow, ImmutableFlowUtils, IS_ABSOLUTELY_POSITIONED};
+use flow::{self, Flow, ImmutableFlowUtils, FlowFlags};
 use fragment::{FragmentBorderBoxIterator, CoordinateSystem};
 use generated_content::ResolveGeneratedContent;
 use incremental::RelayoutMode;
 use servo_config::opts;
-use style::servo::restyle_damage::{REFLOW, REFLOW_OUT_OF_FLOW, STORE_OVERFLOW};
+use style::servo::restyle_damage::ServoRestyleDamage;
 use traversal::{AssignBSizes, AssignISizes, BubbleISizes, BuildDisplayList};
 use traversal::{InorderFlowTraversal, PostorderFlowTraversal, PreorderFlowTraversal};
 
 pub fn resolve_generated_content(root: &mut Flow, layout_context: &LayoutContext) {
     ResolveGeneratedContent::new(&layout_context).traverse(root, 0);
 }
 
 /// Run the main layout passes sequentially.
@@ -28,17 +28,17 @@ pub fn reflow(root: &mut Flow, layout_co
             assign_inline_sizes: AssignISizes,
             assign_block_sizes: AssignBSizes,
             relayout_mode: RelayoutMode) {
         // Force reflow children during this traversal. This is needed when we failed
         // the float speculation of a block formatting context and need to fix it.
         if relayout_mode == RelayoutMode::Force {
             flow::mut_base(flow)
                 .restyle_damage
-                .insert(REFLOW_OUT_OF_FLOW | REFLOW);
+                .insert(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW);
         }
 
         if assign_inline_sizes.should_process(flow) {
             assign_inline_sizes.process(flow);
         }
 
         for kid in flow::child_iter_mut(flow) {
             doit(kid, assign_inline_sizes, assign_block_sizes, relayout_mode);
@@ -107,42 +107,42 @@ pub fn iterate_through_flow_tree_fragmen
             doit(kid, level + 1, iterator, &stacking_context_position);
         }
     }
 
     doit(root, 0, iterator, &Point2D::zero());
 }
 
 pub fn store_overflow(layout_context: &LayoutContext, flow: &mut Flow) {
-    if !flow::base(flow).restyle_damage.contains(STORE_OVERFLOW) {
+    if !flow::base(flow).restyle_damage.contains(ServoRestyleDamage::STORE_OVERFLOW) {
         return;
     }
 
     for kid in flow::mut_base(flow).child_iter_mut() {
         store_overflow(layout_context, kid);
     }
 
     flow.store_overflow(layout_context);
 
     flow::mut_base(flow)
         .restyle_damage
-        .remove(STORE_OVERFLOW);
+        .remove(ServoRestyleDamage::STORE_OVERFLOW);
 }
 
 /// Guesses how much inline size will be taken up by floats on the left and right sides of the
 /// given flow. This is needed to speculatively calculate the inline sizes of block formatting
 /// contexts. The speculation typically succeeds, but if it doesn't we have to lay it out again.
 pub fn guess_float_placement(flow: &mut Flow) {
-    if !flow::base(flow).restyle_damage.intersects(REFLOW) {
+    if !flow::base(flow).restyle_damage.intersects(ServoRestyleDamage::REFLOW) {
         return;
     }
 
     let mut floats_in = SpeculatedFloatPlacement::compute_floats_in_for_first_child(flow);
     for kid in flow::mut_base(flow).child_iter_mut() {
-        if flow::base(kid).flags.contains(IS_ABSOLUTELY_POSITIONED) {
+        if flow::base(kid).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
             // Do not propagate floats in or out, but do propogate between kids.
             guess_float_placement(kid);
         } else {
             floats_in.compute_floats_in(kid);
             flow::mut_base(kid).speculated_float_placement_in = floats_in;
             guess_float_placement(kid);
             floats_in = flow::base(kid).speculated_float_placement_out;
         }
--- a/servo/components/layout/table.rs
+++ b/servo/components/layout/table.rs
@@ -6,33 +6,32 @@
 
 #![deny(unsafe_code)]
 
 use app_units::Au;
 use block::{BlockFlow, CandidateBSizeIterator, ISizeAndMarginsComputer};
 use block::{ISizeConstraintInput, ISizeConstraintSolution};
 use context::LayoutContext;
 use display_list_builder::{BlockFlowDisplayListBuilding, BorderPaintingMode};
-use display_list_builder::{DisplayListBuildState, NEVER_CREATES_STACKING_CONTEXT};
-use display_list_builder::StackingContextCollectionState;
+use display_list_builder::{DisplayListBuildState, StackingContextCollectionFlags, StackingContextCollectionState};
 use euclid::Point2D;
 use flow;
 use flow::{BaseFlow, EarlyAbsolutePositionInfo, Flow, FlowClass, ImmutableFlowUtils, OpaqueFlow};
 use flow_list::MutFlowListIterator;
 use fragment::{Fragment, FragmentBorderBoxIterator, Overflow};
 use gfx_traits::print_tree::PrintTree;
 use layout_debug;
 use model::{IntrinsicISizes, IntrinsicISizesContribution, MaybeAuto};
 use std::cmp;
 use std::fmt;
 use style::computed_values::{border_collapse, border_spacing, table_layout};
 use style::context::SharedStyleContext;
 use style::logical_geometry::LogicalSize;
 use style::properties::ComputedValues;
-use style::servo::restyle_damage::{REFLOW, REFLOW_OUT_OF_FLOW};
+use style::servo::restyle_damage::ServoRestyleDamage;
 use style::values::CSSFloat;
 use style::values::computed::LengthOrPercentageOrAuto;
 use table_row::{self, CellIntrinsicInlineSize, CollapsedBorder, CollapsedBorderProvenance};
 use table_row::TableRowFlow;
 use table_wrapper::TableLayout;
 
 #[allow(unsafe_code)]
 unsafe impl ::flow::HasBaseFlow for TableFlow {}
@@ -500,17 +499,18 @@ impl Flow for TableFlow {
             border_collapse::T::collapse => BorderPaintingMode::Hidden,
         };
 
         self.block_flow.build_display_list_for_block(state, border_painting_mode);
     }
 
     fn collect_stacking_contexts(&mut self, state: &mut StackingContextCollectionState) {
         // Stacking contexts are collected by the table wrapper.
-        self.block_flow.collect_stacking_contexts_for_block(state, NEVER_CREATES_STACKING_CONTEXT);
+        self.block_flow.collect_stacking_contexts_for_block(state,
+            StackingContextCollectionFlags::NEVER_CREATES_STACKING_CONTEXT);
     }
 
     fn repair_style(&mut self, new_style: &::ServoArc<ComputedValues>) {
         self.block_flow.repair_style(new_style)
     }
 
     fn compute_overflow(&self) -> Overflow {
         self.block_flow.compute_overflow()
@@ -730,17 +730,17 @@ pub trait TableLikeFlow {
     fn assign_block_size_for_table_like_flow(&mut self, block_direction_spacing: Au);
 }
 
 impl TableLikeFlow for BlockFlow {
     fn assign_block_size_for_table_like_flow(&mut self, block_direction_spacing: Au) {
         debug_assert!(self.fragment.style.get_inheritedtable().border_collapse ==
                       border_collapse::T::separate || block_direction_spacing == Au(0));
 
-        if self.base.restyle_damage.contains(REFLOW) {
+        if self.base.restyle_damage.contains(ServoRestyleDamage::REFLOW) {
             // Our current border-box position.
             let block_start_border_padding = self.fragment.border_padding.block_start;
             let mut current_block_offset = block_start_border_padding;
             let mut has_rows = false;
 
             // At this point, `current_block_offset` is at the content edge of our box. Now iterate
             // over children.
             for kid in self.base.child_iter_mut() {
@@ -804,17 +804,17 @@ impl TableLikeFlow for BlockFlow {
             for kid in self.base.child_iter_mut() {
                 flow::mut_base(kid).early_absolute_position_info = EarlyAbsolutePositionInfo {
                     relative_containing_block_size: self.fragment.content_box().size,
                     relative_containing_block_mode: self.fragment.style().writing_mode,
                 };
             }
         }
 
-        self.base.restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW);
+        self.base.restyle_damage.remove(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW);
     }
 }
 
 /// Inline collapsed borders for the table itself.
 #[derive(Debug)]
 struct TableInlineCollapsedBorders {
     /// The table border at the start of the inline direction.
     start: CollapsedBorder,
--- a/servo/components/layout/table_cell.rs
+++ b/servo/components/layout/table_cell.rs
@@ -8,17 +8,17 @@
 
 use app_units::Au;
 use block::{BlockFlow, ISizeAndMarginsComputer, MarginsMayCollapseFlag};
 use context::LayoutContext;
 use display_list_builder::{BlockFlowDisplayListBuilding, BorderPaintingMode};
 use display_list_builder::{DisplayListBuildState, StackingContextCollectionFlags};
 use display_list_builder::StackingContextCollectionState;
 use euclid::{Point2D, Rect, SideOffsets2D, Size2D};
-use flow::{self, Flow, FlowClass, IS_ABSOLUTELY_POSITIONED, OpaqueFlow};
+use flow::{self, Flow, FlowClass, FlowFlags, OpaqueFlow};
 use fragment::{Fragment, FragmentBorderBoxIterator, Overflow};
 use gfx_traits::print_tree::PrintTree;
 use layout_debug;
 use model::MaybeAuto;
 use script_layout_interface::wrapper_traits::ThreadSafeLayoutNode;
 use std::fmt;
 use style::computed_values::{border_collapse, border_top_style};
 use style::logical_geometry::{LogicalMargin, LogicalRect, LogicalSize, WritingMode};
@@ -97,17 +97,17 @@ impl TableCellFlow {
 
     /// Position this cell's children according to vertical-align.
     pub fn valign_children(&mut self) {
         // Note to the reader: this code has been tested with negative margins.
         // We end up with a "end" that's before the "start," but the math still works out.
         let mut extents = None;
         for kid in flow::base(self).children.iter() {
             let kid_base = flow::base(kid);
-            if kid_base.flags.contains(IS_ABSOLUTELY_POSITIONED) {
+            if kid_base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
                 continue
             }
             let start = kid_base.position.start.b -
                 kid_base.collapsible_margins.block_start_margin_for_noncollapsible_context();
             let end = kid_base.position.start.b + kid_base.position.size.block +
                 kid_base.collapsible_margins.block_end_margin_for_noncollapsible_context();
             match extents {
                 Some((ref mut first_start, ref mut last_end)) => {
@@ -139,17 +139,17 @@ impl TableCellFlow {
             _ => Au(0),
         };
         if offset == Au(0) {
             return
         }
 
         for kid in flow::mut_base(self).children.iter_mut() {
             let kid_base = flow::mut_base(kid);
-            if !kid_base.flags.contains(IS_ABSOLUTELY_POSITIONED) {
+            if !kid_base.flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) {
                 kid_base.position.start.b += offset
             }
         }
     }
 }
 
 impl Flow for TableCellFlow {
     fn class(&self) -> FlowClass {
--- a/servo/components/layout/table_row.rs
+++ b/servo/components/layout/table_row.rs
@@ -21,17 +21,17 @@ use layout_debug;
 use model::MaybeAuto;
 use serde::{Serialize, Serializer};
 use std::cmp::max;
 use std::fmt;
 use std::iter::{Enumerate, IntoIterator, Peekable};
 use style::computed_values::{border_collapse, border_spacing, border_top_style};
 use style::logical_geometry::{LogicalSize, PhysicalSide, WritingMode};
 use style::properties::ComputedValues;
-use style::servo::restyle_damage::{REFLOW, REFLOW_OUT_OF_FLOW};
+use style::servo::restyle_damage::ServoRestyleDamage;
 use style::values::computed::{Color, LengthOrPercentageOrAuto};
 use table::{ColumnComputedInlineSize, ColumnIntrinsicInlineSize, InternalTable, VecExt};
 use table_cell::{CollapsedBordersForCell, TableCellFlow};
 
 #[allow(unsafe_code)]
 unsafe impl ::flow::HasBaseFlow for TableRowFlow {}
 
 /// A single row of a table.
@@ -109,17 +109,17 @@ impl TableRowFlow {
     /// Assign block-size for table-row flow.
     ///
     /// TODO(pcwalton): This doesn't handle floats and positioned elements right.
     ///
     /// inline(always) because this is only ever called by in-order or non-in-order top-level
     /// methods
     #[inline(always)]
     fn assign_block_size_table_row_base(&mut self, layout_context: &LayoutContext) {
-        if self.block_flow.base.restyle_damage.contains(REFLOW) {
+        if self.block_flow.base.restyle_damage.contains(ServoRestyleDamage::REFLOW) {
             // Per CSS 2.1 § 17.5.3, find max_y = max(computed `block-size`, minimum block-size of
             // all cells).
             let mut max_block_size = Au(0);
             let thread_id = self.block_flow.base.thread_id;
             let content_box = self.block_flow.base.position
                 - self.block_flow.fragment.border_padding
                 - self.block_flow.fragment.margin;
             for kid in self.block_flow.base.child_iter_mut() {
@@ -190,17 +190,17 @@ impl TableRowFlow {
                         relative_containing_block_mode: self.block_flow
                                                             .fragment
                                                             .style()
                                                             .writing_mode,
                     };
             }
         }
 
-        self.block_flow.base.restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW);
+        self.block_flow.base.restyle_damage.remove(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW);
     }
 
     pub fn populate_collapsed_border_spacing<'a, I>(
             &mut self,
             collapsed_inline_direction_border_widths_for_table: &[Au],
             collapsed_block_direction_border_widths_for_table: &mut Peekable<I>)
             where I: Iterator<Item=&'a Au> {
         self.collapsed_border_spacing.inline.clear();
--- a/servo/components/layout/table_rowgroup.rs
+++ b/servo/components/layout/table_rowgroup.rs
@@ -5,17 +5,17 @@
 //! CSS table formatting contexts.
 
 #![deny(unsafe_code)]
 
 use app_units::Au;
 use block::{BlockFlow, ISizeAndMarginsComputer};
 use context::LayoutContext;
 use display_list_builder::{BlockFlowDisplayListBuilding, DisplayListBuildState};
-use display_list_builder::{NEVER_CREATES_CONTAINING_BLOCK, StackingContextCollectionState};
+use display_list_builder::{StackingContextCollectionFlags, StackingContextCollectionState};
 use euclid::Point2D;
 use flow::{Flow, FlowClass, OpaqueFlow};
 use fragment::{Fragment, FragmentBorderBoxIterator, Overflow};
 use gfx_traits::print_tree::PrintTree;
 use layout_debug;
 use serde::{Serialize, Serializer};
 use std::fmt;
 use std::iter::{IntoIterator, Iterator, Peekable};
@@ -179,17 +179,18 @@ impl Flow for TableRowGroupFlow {
     }
 
     fn build_display_list(&mut self, state: &mut DisplayListBuildState) {
         debug!("build_display_list_table_rowgroup: same process as block flow");
         self.block_flow.build_display_list(state);
     }
 
     fn collect_stacking_contexts(&mut self, state: &mut StackingContextCollectionState) {
-        self.block_flow.collect_stacking_contexts_for_block(state, NEVER_CREATES_CONTAINING_BLOCK);
+        self.block_flow.collect_stacking_contexts_for_block(state,
+            StackingContextCollectionFlags::NEVER_CREATES_CONTAINING_BLOCK);
     }
 
     fn repair_style(&mut self, new_style: &::ServoArc<ComputedValues>) {
         self.block_flow.repair_style(new_style)
     }
 
     fn compute_overflow(&self) -> Overflow {
         self.block_flow.compute_overflow()
--- a/servo/components/layout/table_wrapper.rs
+++ b/servo/components/layout/table_wrapper.rs
@@ -12,22 +12,21 @@
 //! Hereafter this document is referred to as INTRINSIC.
 
 #![deny(unsafe_code)]
 
 use app_units::Au;
 use block::{AbsoluteNonReplaced, BlockFlow, FloatNonReplaced, ISizeAndMarginsComputer, ISizeConstraintInput};
 use block::{ISizeConstraintSolution, MarginsMayCollapseFlag};
 use context::LayoutContext;
-use display_list_builder::{BlockFlowDisplayListBuilding, DisplayListBuildState};
-use display_list_builder::{NEVER_CREATES_CLIP_SCROLL_NODE, NEVER_CREATES_CONTAINING_BLOCK};
+use display_list_builder::{BlockFlowDisplayListBuilding, DisplayListBuildState, StackingContextCollectionFlags};
 use display_list_builder::StackingContextCollectionState;
 use euclid::Point2D;
 use floats::FloatKind;
-use flow::{Flow, FlowClass, ImmutableFlowUtils, INLINE_POSITION_IS_STATIC, OpaqueFlow};
+use flow::{Flow, FlowClass, ImmutableFlowUtils, FlowFlags, OpaqueFlow};
 use fragment::{Fragment, FragmentBorderBoxIterator, Overflow};
 use gfx_traits::print_tree::PrintTree;
 use model::MaybeAuto;
 use std::cmp::{max, min};
 use std::fmt;
 use std::ops::Add;
 use style::computed_values::{position, table_layout};
 use style::context::SharedStyleContext;
@@ -251,17 +250,17 @@ impl TableWrapperFlow {
                                                                               &input);
             inline_size_computer.set_inline_size_constraint_solutions(&mut self.block_flow,
                                                                       solution);
             inline_size_computer.set_inline_position_of_flow_if_necessary(&mut self.block_flow,
                                                                           solution);
             return
         }
 
-        if !self.block_flow.base.flags.contains(INLINE_POSITION_IS_STATIC) {
+        if !self.block_flow.base.flags.contains(FlowFlags::INLINE_POSITION_IS_STATIC) {
             let inline_size_computer = AbsoluteTable {
                 minimum_width_of_all_columns: minimum_width_of_all_columns,
                 preferred_width_of_all_columns: preferred_width_of_all_columns,
                 table_border_padding: border_padding,
             };
             let input =
                 inline_size_computer.compute_inline_size_constraint_inputs(&mut self.block_flow,
                                                                            parent_flow_inline_size,
@@ -459,17 +458,19 @@ impl Flow for TableWrapperFlow {
     }
 
     fn build_display_list(&mut self, state: &mut DisplayListBuildState) {
         self.block_flow.build_display_list(state);
     }
 
     fn collect_stacking_contexts(&mut self, state: &mut StackingContextCollectionState) {
         self.block_flow.collect_stacking_contexts_for_block(
-            state, NEVER_CREATES_CONTAINING_BLOCK | NEVER_CREATES_CLIP_SCROLL_NODE);
+            state,
+            StackingContextCollectionFlags::NEVER_CREATES_CONTAINING_BLOCK |
+            StackingContextCollectionFlags::NEVER_CREATES_CLIP_SCROLL_NODE);
     }
 
     fn repair_style(&mut self, new_style: &::ServoArc<ComputedValues>) {
         self.block_flow.repair_style(new_style)
     }
 
     fn compute_overflow(&self) -> Overflow {
         self.block_flow.compute_overflow()
--- a/servo/components/layout/text.rs
+++ b/servo/components/layout/text.rs
@@ -2,25 +2,24 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 //! Text layout.
 
 #![deny(unsafe_code)]
 
 use app_units::Au;
-use fragment::{Fragment, REQUIRES_LINE_BREAK_AFTERWARD_IF_WRAPPING_ON_NEWLINES, ScannedTextFlags};
-use fragment::{SELECTED, ScannedTextFragmentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo};
-use gfx::font::{DISABLE_KERNING_SHAPING_FLAG, FontMetrics, IGNORE_LIGATURES_SHAPING_FLAG};
-use gfx::font::{KEEP_ALL_FLAG, RTL_FLAG, RunMetrics, ShapingFlags, ShapingOptions};
+use fragment::{Fragment, ScannedTextFlags};
+use fragment::{ScannedTextFragmentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo};
+use gfx::font::{FontMetrics, RunMetrics, ShapingFlags, ShapingOptions};
 use gfx::font_context::FontContext;
 use gfx::text::glyph::ByteIndex;
 use gfx::text::text_run::TextRun;
 use gfx::text::util::{self, CompressionMode};
-use inline::{FIRST_FRAGMENT_OF_ELEMENT, InlineFragments, LAST_FRAGMENT_OF_ELEMENT};
+use inline::{InlineFragmentNodeFlags, InlineFragments};
 use linked_list::split_off_head;
 use ordered_float::NotNaN;
 use range::Range;
 use std::borrow::ToOwned;
 use std::collections::LinkedList;
 use std::mem;
 use std::sync::Arc;
 use style::computed_values::{text_rendering, text_transform};
@@ -286,39 +285,39 @@ impl TextRunScanner {
 
             // Per CSS 2.1 § 16.4, "when the resultant space between two characters is not the same
             // as the default space, user agents should not use ligatures." This ensures that, for
             // example, `finally` with a wide `letter-spacing` renders as `f i n a l l y` and not
             // `fi n a l l y`.
             let mut flags = ShapingFlags::empty();
             if let Some(v) = letter_spacing.value() {
                 if v.px() != 0. {
-                    flags.insert(IGNORE_LIGATURES_SHAPING_FLAG);
+                    flags.insert(ShapingFlags::IGNORE_LIGATURES_SHAPING_FLAG);
                 }
             }
             if text_rendering == text_rendering::T::optimizespeed {
-                flags.insert(IGNORE_LIGATURES_SHAPING_FLAG);
-                flags.insert(DISABLE_KERNING_SHAPING_FLAG)
+                flags.insert(ShapingFlags::IGNORE_LIGATURES_SHAPING_FLAG);
+                flags.insert(ShapingFlags::DISABLE_KERNING_SHAPING_FLAG)
             }
             if word_break == word_break::T::keep_all {
-                flags.insert(KEEP_ALL_FLAG);
+                flags.insert(ShapingFlags::KEEP_ALL_FLAG);
             }
             let options = ShapingOptions {
                 letter_spacing: letter_spacing.value().cloned().map(Au::from),
                 word_spacing: word_spacing,
                 script: Script::Common,
                 flags: flags,
             };
 
             // FIXME(https://github.com/rust-lang/rust/issues/23338)
             run_info_list.into_iter().map(|run_info| {
                 let mut options = options;
                 options.script = run_info.script;
                 if run_info.bidi_level.is_rtl() {
-                    options.flags.insert(RTL_FLAG);
+                    options.flags.insert(ShapingFlags::RTL_FLAG);
                 }
                 let mut font = fontgroup.fonts.get(run_info.font_index).unwrap().borrow_mut();
                 ScannedTextRun {
                     run: Arc::new(TextRun::new(&mut *font,
                                                run_info.text,
                                                &options,
                                                run_info.bidi_level)),
                     insertion_point: run_info.insertion_point,
@@ -359,21 +358,21 @@ impl TextRunScanner {
                 let text_size = old_fragment.border_box.size;
 
                 let requires_line_break_afterward_if_wrapping_on_newlines =
                     scanned_run.run.text[mapping.byte_range.begin()..mapping.byte_range.end()]
                     .ends_with('\n');
 
                 if requires_line_break_afterward_if_wrapping_on_newlines {
                     byte_range.extend_by(ByteIndex(-1)); // Trim the '\n'
-                    flags.insert(REQUIRES_LINE_BREAK_AFTERWARD_IF_WRAPPING_ON_NEWLINES);
+                    flags.insert(ScannedTextFlags::REQUIRES_LINE_BREAK_AFTERWARD_IF_WRAPPING_ON_NEWLINES);
                 }
 
                 if mapping.selected {
-                    flags.insert(SELECTED);
+                    flags.insert(ScannedTextFlags::SELECTED);
                 }
 
                 let insertion_point = if mapping.contains_insertion_point(scanned_run.insertion_point) {
                     scanned_run.insertion_point
                 } else {
                     None
                 };
 
@@ -397,20 +396,20 @@ impl TextRunScanner {
                 let is_last_mapping_of_this_old_fragment = match mappings.peek() {
                     Some(mapping) if mapping.old_fragment_index == logical_offset => false,
                     _ => true
                 };
 
                 if let Some(ref mut context) = new_fragment.inline_context {
                     for node in &mut context.nodes {
                         if !is_last_mapping_of_this_old_fragment {
-                            node.flags.remove(LAST_FRAGMENT_OF_ELEMENT);
+                            node.flags.remove(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT);
                         }
                         if !is_first_mapping_of_this_old_fragment {
-                            node.flags.remove(FIRST_FRAGMENT_OF_ELEMENT);
+                            node.flags.remove(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT);
                         }
                     }
                 }
 
                 for prev_fragment in prev_fragments_to_meld.drain(..) {
                     new_fragment.meld_with_prev_inline_fragment(&prev_fragment);
                 }
 
--- a/servo/components/layout/traversal.rs
+++ b/servo/components/layout/traversal.rs
@@ -2,24 +2,24 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 //! Traversals over the DOM and flow trees, running the layout computations.
 
 use construct::FlowConstructor;
 use context::LayoutContext;
 use display_list_builder::DisplayListBuildState;
-use flow::{self, CAN_BE_FRAGMENTED, Flow, ImmutableFlowUtils};
+use flow::{self, FlowFlags, Flow, ImmutableFlowUtils};
 use script_layout_interface::wrapper_traits::{LayoutNode, ThreadSafeLayoutNode};
 use servo_config::opts;
 use style::context::{SharedStyleContext, StyleContext};
 use style::data::ElementData;
 use style::dom::{NodeInfo, TElement, TNode};
 use style::selector_parser::RestyleDamage;
-use style::servo::restyle_damage::{BUBBLE_ISIZES, REFLOW, REFLOW_OUT_OF_FLOW, REPAINT, REPOSITION};
+use style::servo::restyle_damage::ServoRestyleDamage;
 use style::traversal::{DomTraversal, recalc_style_at};
 use style::traversal::PerLevelTraversalData;
 use wrapper::{GetRawData, LayoutNodeLayoutData};
 use wrapper::ThreadSafeLayoutNodeHelpers;
 
 pub struct RecalcStyleAndConstructFlows<'a> {
     context: LayoutContext<'a>,
 }
@@ -204,17 +204,17 @@ fn construct_flows_at<N>(context: &Layou
             if nonincremental_layout || !flow_constructor.repair_if_possible(&tnode) {
                 flow_constructor.process(&tnode);
                 debug!("Constructed flow for {:?}: {:x}",
                        tnode,
                        tnode.flow_debug_id());
             }
         }
 
-        tnode.mutate_layout_data().unwrap().flags.insert(::data::HAS_BEEN_TRAVERSED);
+        tnode.mutate_layout_data().unwrap().flags.insert(::data::LayoutDataFlags::HAS_BEEN_TRAVERSED);
     }
 
     if let Some(el) = node.as_element() {
         unsafe { el.unset_dirty_descendants(); }
     }
 }
 
 /// The bubble-inline-sizes traversal, the first part of layout computation. This computes
@@ -222,22 +222,22 @@ fn construct_flows_at<N>(context: &Layou
 pub struct BubbleISizes<'a> {
     pub layout_context: &'a LayoutContext<'a>,
 }
 
 impl<'a> PostorderFlowTraversal for BubbleISizes<'a> {
     #[inline]
     fn process(&self, flow: &mut Flow) {
         flow.bubble_inline_sizes();
-        flow::mut_base(flow).restyle_damage.remove(BUBBLE_ISIZES);
+        flow::mut_base(flow).restyle_damage.remove(ServoRestyleDamage::BUBBLE_ISIZES);
     }
 
     #[inline]
     fn should_process(&self, flow: &mut Flow) -> bool {
-        flow::base(flow).restyle_damage.contains(BUBBLE_ISIZES)
+        flow::base(flow).restyle_damage.contains(ServoRestyleDamage::BUBBLE_ISIZES)
     }
 }
 
 /// The assign-inline-sizes traversal. In Gecko this corresponds to `Reflow`.
 #[derive(Clone, Copy)]
 pub struct AssignISizes<'a> {
     pub layout_context: &'a LayoutContext<'a>,
 }
@@ -245,17 +245,17 @@ pub struct AssignISizes<'a> {
 impl<'a> PreorderFlowTraversal for AssignISizes<'a> {
     #[inline]
     fn process(&self, flow: &mut Flow) {
         flow.assign_inline_sizes(self.layout_context);
     }
 
     #[inline]
     fn should_process(&self, flow: &mut Flow) -> bool {
-        flow::base(flow).restyle_damage.intersects(REFLOW_OUT_OF_FLOW | REFLOW)
+        flow::base(flow).restyle_damage.intersects(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW)
     }
 }
 
 /// The assign-block-sizes-and-store-overflow traversal, the last (and most expensive) part of
 /// layout computation. Determines the final block-sizes for all layout objects and computes
 /// positions. In Gecko this corresponds to `Reflow`.
 #[derive(Clone, Copy)]
 pub struct AssignBSizes<'a> {
@@ -275,36 +275,36 @@ impl<'a> PostorderFlowTraversal for Assi
         }
 
         flow.assign_block_size(self.layout_context);
     }
 
     #[inline]
     fn should_process(&self, flow: &mut Flow) -> bool {
         let base = flow::base(flow);
-        base.restyle_damage.intersects(REFLOW_OUT_OF_FLOW | REFLOW) &&
+        base.restyle_damage.intersects(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW) &&
         // The fragmentation countainer is responsible for calling Flow::fragment recursively
-        !base.flags.contains(CAN_BE_FRAGMENTED)
+        !base.flags.contains(FlowFlags::CAN_BE_FRAGMENTED)
     }
 }
 
 pub struct ComputeStackingRelativePositions<'a> {
     pub layout_context: &'a LayoutContext<'a>,
 }
 
 impl<'a> PreorderFlowTraversal for ComputeStackingRelativePositions<'a> {
     #[inline]
     fn should_process_subtree(&self, flow: &mut Flow) -> bool {
-        flow::base(flow).restyle_damage.contains(REPOSITION)
+        flow::base(flow).restyle_damage.contains(ServoRestyleDamage::REPOSITION)
     }
 
     #[inline]
     fn process(&self, flow: &mut Flow) {
         flow.compute_stacking_relative_position(self.layout_context);
-        flow::mut_base(flow).restyle_damage.remove(REPOSITION)
+        flow::mut_base(flow).restyle_damage.remove(ServoRestyleDamage::REPOSITION)
     }
 }
 
 pub struct BuildDisplayList<'a> {
     pub state: DisplayListBuildState<'a>,
 }
 
 impl<'a> BuildDisplayList<'a> {
@@ -312,17 +312,17 @@ impl<'a> BuildDisplayList<'a> {
     pub fn traverse(&mut self, flow: &mut Flow) {
         let parent_stacking_context_id = self.state.current_stacking_context_id;
         self.state.current_stacking_context_id = flow::base(flow).stacking_context_id;
 
         let parent_clipping_and_scrolling = self.state.current_clipping_and_scrolling;
         self.state.current_clipping_and_scrolling = flow.clipping_and_scrolling();
 
         flow.build_display_list(&mut self.state);
-        flow::mut_base(flow).restyle_damage.remove(REPAINT);
+        flow::mut_base(flow).restyle_damage.remove(ServoRestyleDamage::REPAINT);
 
         for kid in flow::child_iter_mut(flow) {
             self.traverse(kid);
         }
 
         self.state.current_stacking_context_id = parent_stacking_context_id;
         self.state.current_clipping_and_scrolling = parent_clipping_and_scrolling;
     }
--- a/servo/components/layout/wrapper.rs
+++ b/servo/components/layout/wrapper.rs
@@ -135,17 +135,17 @@ impl<T: ThreadSafeLayoutNode> ThreadSafe
         if node.is_text_node() {
             node = node.parent_node().unwrap();
             debug_assert!(node.is_element());
         }
 
         let damage = {
             let data = node.get_raw_data().unwrap();
 
-            if !data.layout_data.borrow().flags.contains(::data::HAS_BEEN_TRAVERSED) {
+            if !data.layout_data.borrow().flags.contains(::data::LayoutDataFlags::HAS_BEEN_TRAVERSED) {
                 // We're reflowing a node that was styled for the first time and
                 // has never been visited by layout. Return rebuild_and_reflow,
                 // because that's what the code expects.
                 RestyleDamage::rebuild_and_reflow()
             } else {
                 data.style_data.element_data.borrow().damage
             }
         };
--- a/servo/components/layout_thread/dom_wrapper.rs
+++ b/servo/components/layout_thread/dom_wrapper.rs
@@ -33,23 +33,21 @@
 use atomic_refcell::{AtomicRef, AtomicRefMut, AtomicRefCell};
 use gfx_traits::ByteIndex;
 use html5ever::{LocalName, Namespace};
 use layout::data::StyleAndLayoutData;
 use layout::wrapper::GetRawData;
 use msg::constellation_msg::{BrowsingContextId, PipelineId};
 use nonzero::NonZero;
 use range::Range;
-use script::layout_exports::{CAN_BE_FRAGMENTED, HAS_DIRTY_DESCENDANTS, IS_IN_DOC};
 use script::layout_exports::{CharacterDataTypeId, ElementTypeId, HTMLElementTypeId, NodeTypeId};
 use script::layout_exports::{Document, Element, Node, Text};
-use script::layout_exports::{HANDLED_SNAPSHOT, HAS_SNAPSHOT};
 use script::layout_exports::{LayoutCharacterDataHelpers, LayoutDocumentHelpers};
-use script::layout_exports::{LayoutElementHelpers, LayoutNodeHelpers, RawLayoutElementHelpers};
-use script::layout_exports::LayoutDom;
+use script::layout_exports::{LayoutElementHelpers, LayoutNodeHelpers, LayoutDom, RawLayoutElementHelpers};
+use script::layout_exports::NodeFlags;
 use script::layout_exports::PendingRestyle;
 use script_layout_interface::{HTMLCanvasData, LayoutNodeType, SVGSVGData, TrustedNodeAddress};
 use script_layout_interface::{OpaqueStyleAndLayoutData, StyleData};
 use script_layout_interface::wrapper_traits::{DangerousThreadSafeLayoutNode, GetLayoutData, LayoutNode};
 use script_layout_interface::wrapper_traits::{PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode};
 use selectors::attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivity};
 use selectors::matching::{ElementSelectorFlags, MatchingContext, QuirksMode, RelevantLinkStatus};
 use selectors::matching::VisitedHandlingMode;
@@ -207,21 +205,21 @@ impl<'ln> TNode for ServoLayoutNode<'ln>
         as_element(self.node)
     }
 
     fn as_document(&self) -> Option<ServoLayoutDocument<'ln>> {
         self.node.downcast().map(ServoLayoutDocument::from_layout_js)
     }
 
     fn can_be_fragmented(&self) -> bool {
-        unsafe { self.node.get_flag(CAN_BE_FRAGMENTED) }
+        unsafe { self.node.get_flag(NodeFlags::CAN_BE_FRAGMENTED) }
     }
 
     unsafe fn set_can_be_fragmented(&self, value: bool) {
-        self.node.set_flag(CAN_BE_FRAGMENTED, value)
+        self.node.set_flag(NodeFlags::CAN_BE_FRAGMENTED, value)
     }
 }
 
 impl<'ln> LayoutNode for ServoLayoutNode<'ln> {
     type ConcreteThreadSafeLayoutNode = ServoThreadSafeLayoutNode<'ln>;
 
     fn to_threadsafe(&self) -> Self::ConcreteThreadSafeLayoutNode {
         ServoThreadSafeLayoutNode::new(self)
@@ -398,38 +396,38 @@ impl<'le> TElement for ServoLayoutElemen
                 for class in *classes {
                     callback(class)
                 }
             }
         }
     }
 
     fn has_dirty_descendants(&self) -> bool {
-        unsafe { self.as_node().node.get_flag(HAS_DIRTY_DESCENDANTS) }
+        unsafe { self.as_node().node.get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS) }
     }
 
     fn has_snapshot(&self) -> bool {
-        unsafe { self.as_node().node.get_flag(HAS_SNAPSHOT) }
+        unsafe { self.as_node().node.get_flag(NodeFlags::HAS_SNAPSHOT) }
     }
 
     fn handled_snapshot(&self) -> bool {
-        unsafe { self.as_node().node.get_flag(HANDLED_SNAPSHOT) }
+        unsafe { self.as_node().node.get_flag(NodeFlags::HANDLED_SNAPSHOT) }
     }
 
     unsafe fn set_handled_snapshot(&self) {
-        self.as_node().node.set_flag(HANDLED_SNAPSHOT, true);
+        self.as_node().node.set_flag(NodeFlags::HANDLED_SNAPSHOT, true);
     }
 
     unsafe fn set_dirty_descendants(&self) {
-        debug_assert!(self.as_node().node.get_flag(IS_IN_DOC));
-        self.as_node().node.set_flag(HAS_DIRTY_DESCENDANTS, true)
+        debug_assert!(self.as_node().node.get_flag(NodeFlags::IS_IN_DOC));
+        self.as_node().node.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, true)
     }
 
     unsafe fn unset_dirty_descendants(&self) {
-        self.as_node().node.set_flag(HAS_DIRTY_DESCENDANTS, false)
+        self.as_node().node.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, false)
     }
 
     fn store_children_to_process(&self, n: isize) {
         let data = self.get_style_data().unwrap();
         data.parallel.children_to_process.store(n, Ordering::Relaxed);
     }
 
     fn did_process_child(&self) -> isize {
@@ -578,21 +576,21 @@ impl<'le> ServoLayoutElement<'le> {
 
     fn get_style_data(&self) -> Option<&StyleData> {
         unsafe {
             self.get_style_and_layout_data().map(|d| &*(d.ptr.get() as *mut StyleData))
         }
     }
 
     pub unsafe fn unset_snapshot_flags(&self) {
-        self.as_node().node.set_flag(HAS_SNAPSHOT | HANDLED_SNAPSHOT, false);
+        self.as_node().node.set_flag(NodeFlags::HAS_SNAPSHOT | NodeFlags::HANDLED_SNAPSHOT, false);
     }
 
     pub unsafe fn set_has_snapshot(&self) {
-        self.as_node().node.set_flag(HAS_SNAPSHOT, true);
+        self.as_node().node.set_flag(NodeFlags::HAS_SNAPSHOT, true);
     }
 
     pub unsafe fn note_dirty_descendant(&self) {
         use ::selectors::Element;
 
         let mut current = Some(*self);
         while let Some(el) = current {
             // FIXME(bholley): Ideally we'd have the invariant that any element
--- a/servo/components/layout_thread/lib.rs
+++ b/servo/components/layout_thread/lib.rs
@@ -67,17 +67,17 @@ use layout::animation;
 use layout::construct::ConstructionResult;
 use layout::context::LayoutContext;
 use layout::context::RegisteredPainter;
 use layout::context::RegisteredPainters;
 use layout::context::malloc_size_of_persistent_local_context;
 use layout::display_list_builder::ToGfxColor;
 use layout::flow::{self, Flow, ImmutableFlowUtils, MutableOwnedFlowUtils};
 use layout::flow_ref::FlowRef;
-use layout::incremental::{LayoutDamageComputation, REFLOW_ENTIRE_DOCUMENT, RelayoutMode};
+use layout::incremental::{LayoutDamageComputation, RelayoutMode, SpecialRestyleDamage};
 use layout::layout_debug;
 use layout::parallel;
 use layout::query::{LayoutRPCImpl, LayoutThreadData, process_content_box_request, process_content_boxes_request};
 use layout::query::{process_margin_style_query, process_node_overflow_request, process_resolved_style_request};
 use layout::query::{process_node_geometry_request, process_node_scroll_area_request};
 use layout::query::{process_node_scroll_root_id_request, process_offset_parent_query};
 use layout::sequential;
 use layout::traversal::{ComputeStackingRelativePositions, PreorderFlowTraversal, RecalcStyleAndConstructFlows};
@@ -127,21 +127,21 @@ use style::context::{SharedStyleContext,
 use style::dom::{ShowSubtree, ShowSubtreeDataAndPrimaryValues, TElement, TNode};
 use style::driver;
 use style::error_reporting::{NullReporter, RustLogReporter};
 use style::invalidation::element::restyle_hints::RestyleHint;
 use style::logical_geometry::LogicalPoint;
 use style::media_queries::{Device, MediaList, MediaType};
 use style::properties::PropertyId;
 use style::selector_parser::SnapshotMap;
-use style::servo::restyle_damage::{REFLOW, REFLOW_OUT_OF_FLOW, REPAINT, REPOSITION, STORE_OVERFLOW};
+use style::servo::restyle_damage::ServoRestyleDamage;
 use style::shared_lock::{SharedRwLock, SharedRwLockReadGuard, StylesheetGuards};
 use style::stylesheets::{Origin, Stylesheet, DocumentStyleSheet, StylesheetInDocument, UserAgentStylesheets};
 use style::stylist::Stylist;
-use style::thread_state;
+use style::thread_state::{self, ThreadState};
 use style::timer::Timer;
 use style::traversal::DomTraversal;
 use style::traversal_flags::TraversalFlags;
 use style_traits::CSSPixel;
 use style_traits::DevicePixel;
 use style_traits::SpeculativePainter;
 
 /// Information needed by the layout thread.
@@ -280,17 +280,17 @@ impl LayoutThreadFactory for LayoutThrea
               time_profiler_chan: time::ProfilerChan,
               mem_profiler_chan: mem::ProfilerChan,
               content_process_shutdown_chan: Option<IpcSender<()>>,
               webrender_api_sender: webrender_api::RenderApiSender,
               webrender_document: webrender_api::DocumentId,
               layout_threads: usize,
               paint_time_metrics: PaintTimeMetrics) {
         thread::Builder::new().name(format!("LayoutThread {:?}", id)).spawn(move || {
-            thread_state::initialize(thread_state::LAYOUT);
+            thread_state::initialize(ThreadState::LAYOUT);
 
             // In order to get accurate crash reports, we install the top-level bc id.
             TopLevelBrowsingContextId::install(top_level_browsing_context_id);
 
             { // Ensures layout thread is destroyed before we send shutdown message
                 let sender = chan.0;
                 let layout = LayoutThread::new(id,
                                                top_level_browsing_context_id,
@@ -966,17 +966,17 @@ impl LayoutThread {
                 LogicalPoint::zero(writing_mode).to_physical(writing_mode,
                                                              self.viewport_size).to_vector();
 
             flow::mut_base(layout_root).clip = data.page_clip_rect;
 
             let traversal = ComputeStackingRelativePositions { layout_context: layout_context };
             traversal.traverse(layout_root);
 
-            if flow::base(layout_root).restyle_damage.contains(REPAINT) ||
+            if flow::base(layout_root).restyle_damage.contains(ServoRestyleDamage::REPAINT) ||
                     rw_data.display_list.is_none() {
                 if reflow_goal.needs_display_list() {
                     let mut build_state =
                         sequential::build_display_list_for_subtree(layout_root, layout_context);
 
                     debug!("Done building display list.");
 
                     let root_size = {
@@ -1536,17 +1536,17 @@ impl LayoutThread {
         profile(time::ProfilerCategory::LayoutRestyleDamagePropagation,
                 self.profiler_metadata(),
                 self.time_profiler_chan.clone(),
                 || {
             // Call `compute_layout_damage` even in non-incremental mode, because it sets flags
             // that are needed in both incremental and non-incremental traversals.
             let damage = FlowRef::deref_mut(root_flow).compute_layout_damage();
 
-            if opts::get().nonincremental_layout || damage.contains(REFLOW_ENTIRE_DOCUMENT) {
+            if opts::get().nonincremental_layout || damage.contains(SpecialRestyleDamage::REFLOW_ENTIRE_DOCUMENT) {
                 FlowRef::deref_mut(root_flow).reflow_entire_document()
             }
         });
 
         if opts::get().trace_layout {
             layout_debug::begin_trace(root_flow.clone());
         }
 
@@ -1559,17 +1559,18 @@ impl LayoutThread {
         // Guess float placement.
         profile(time::ProfilerCategory::LayoutFloatPlacementSpeculation,
                 self.profiler_metadata(),
                 self.time_profiler_chan.clone(),
                 || sequential::guess_float_placement(FlowRef::deref_mut(root_flow)));
 
         // Perform the primary layout passes over the flow tree to compute the locations of all
         // the boxes.
-        if flow::base(&**root_flow).restyle_damage.intersects(REFLOW | REFLOW_OUT_OF_FLOW) {
+        if flow::base(&**root_flow).restyle_damage.intersects(ServoRestyleDamage::REFLOW |
+                                                              ServoRestyleDamage::REFLOW_OUT_OF_FLOW) {
             profile(time::ProfilerCategory::LayoutMain,
                     self.profiler_metadata(),
                     self.time_profiler_chan.clone(),
                     || {
                 let profiler_metadata = self.profiler_metadata();
 
                 if let (true, Some(traversal)) = (self.parallel_flag, self.parallel_traversal.as_ref()) {
                     // Parallel mode.
@@ -1626,17 +1627,18 @@ impl LayoutThread {
 
         self.generation.set(self.generation.get() + 1);
     }
 
     fn reflow_all_nodes(flow: &mut Flow) {
         debug!("reflowing all nodes!");
         flow::mut_base(flow)
             .restyle_damage
-            .insert(REPAINT | STORE_OVERFLOW | REFLOW | REPOSITION);
+            .insert(ServoRestyleDamage::REPAINT | ServoRestyleDamage::STORE_OVERFLOW |
+                    ServoRestyleDamage::REFLOW | ServoRestyleDamage::REPOSITION);
 
         for child in flow::child_iter_mut(flow) {
             LayoutThread::reflow_all_nodes(child);
         }
     }
 
     /// Returns profiling information which is passed to the time profiler.
     fn profiler_metadata(&self) -> Option<TimerMetadata> {
--- a/servo/components/msg/Cargo.toml
+++ b/servo/components/msg/Cargo.toml
@@ -8,14 +8,14 @@ publish = false
 [lib]
 name = "msg"
 path = "lib.rs"
 
 [features]
 unstable = ["nonzero/unstable"]
 
 [dependencies]
-bitflags = "0.7"
+bitflags = "1.0"
 malloc_size_of = { path = "../malloc_size_of" }
 malloc_size_of_derive = { path = "../malloc_size_of_derive" }
 nonzero = {path = "../nonzero"}
 serde = "1.0.14"
 webrender_api = {git = "https://github.com/servo/webrender", features = ["ipc"]}
--- a/servo/components/msg/constellation_msg.rs
+++ b/servo/components/msg/constellation_msg.rs
@@ -143,22 +143,22 @@ pub enum Key {
     Menu,
 
     NavigateBackward,
     NavigateForward,
 }
 
 bitflags! {
     #[derive(Deserialize, Serialize)]
-    pub flags KeyModifiers: u8 {
-        const NONE = 0x00,
-        const SHIFT = 0x01,
-        const CONTROL = 0x02,
-        const ALT = 0x04,
-        const SUPER = 0x08,
+    pub struct KeyModifiers: u8 {
+        const NONE = 0x00;
+        const SHIFT = 0x01;
+        const CONTROL = 0x02;
+        const ALT = 0x04;
+        const SUPER = 0x08;
     }
 }
 
 #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
 pub enum TraversalDirection {
     Forward(usize),
     Back(usize),
 }
--- a/servo/components/script/Cargo.toml
+++ b/servo/components/script/Cargo.toml
@@ -23,17 +23,17 @@ serde_json = "1.0"
 
 [target.'cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))'.dependencies]
 tinyfiledialogs = "2.5.9"
 
 [dependencies]
 app_units = "0.5"
 audio-video-metadata = "0.1.4"
 base64 = "0.6"
-bitflags = "0.7"
+bitflags = "1.0"
 bluetooth_traits = {path = "../bluetooth_traits"}
 byteorder = "1.0"
 canvas_traits = {path = "../canvas_traits"}
 caseless = "0.1.0"
 cookie = "0.6"
 cssparser = "0.22.0"
 deny_public_fields = {path = "../deny_public_fields"}
 devtools_traits = {path = "../devtools_traits"}
--- a/servo/components/script/devtools.rs
+++ b/servo/components/script/devtools.rs
@@ -1,15 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-use devtools_traits::{AutoMargins, CONSOLE_API, CachedConsoleMessage, CachedConsoleMessageTypes};
+use devtools_traits::{AutoMargins, CachedConsoleMessage, CachedConsoleMessageTypes};
 use devtools_traits::{ComputedNodeLayout, ConsoleAPI, PageError};
-use devtools_traits::{EvaluateJSReply, Modification, NodeInfo, PAGE_ERROR, TimelineMarker};
+use devtools_traits::{EvaluateJSReply, Modification, NodeInfo, TimelineMarker};
 use devtools_traits::TimelineMarkerType;
 use dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
 use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods;
 use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
 use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
 use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
 use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, jsstring_to_str};
 use dom::bindings::inheritance::Castable;
@@ -163,17 +163,17 @@ fn determine_auto_margins(window: &Windo
     }
 }
 
 pub fn handle_get_cached_messages(_pipeline_id: PipelineId,
                                   message_types: CachedConsoleMessageTypes,
                                   reply: IpcSender<Vec<CachedConsoleMessage>>) {
     // TODO: check the messageTypes against a global Cache for console messages and page exceptions
     let mut messages = Vec::new();
-    if message_types.contains(PAGE_ERROR) {
+    if message_types.contains(CachedConsoleMessageTypes::PAGE_ERROR) {
         // TODO: make script error reporter pass all reported errors
         //      to devtools and cache them for returning here.
         let msg = PageError {
             type_: "PageError".to_owned(),
             errorMessage: "page error test".to_owned(),
             sourceName: String::new(),
             lineText: String::new(),
             lineNumber: 0,
@@ -183,17 +183,17 @@ pub fn handle_get_cached_messages(_pipel
             error: false,
             warning: false,
             exception: false,
             strict: false,
             private: false,
         };
         messages.push(CachedConsoleMessage::PageError(msg));
     }
-    if message_types.contains(CONSOLE_API) {
+    if message_types.contains(CachedConsoleMessageTypes::CONSOLE_API) {
         // TODO: do for real
         let msg = ConsoleAPI {
             type_: "ConsoleAPI".to_owned(),
             level: "error".to_owned(),
             filename: "http://localhost/~mihai/mozilla/test.html".to_owned(),
             lineNumber: 0,
             functionName: String::new(),
             timeStamp: 0,
--- a/servo/components/script/dom/bindings/cell.rs
+++ b/servo/components/script/dom/bindings/cell.rs
@@ -1,16 +1,16 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 //! A shareable mutable container for the DOM.
 
 use std::cell::{BorrowError, BorrowMutError, Ref, RefCell, RefMut};
-use style::thread_state;
+use style::thread_state::{self, ThreadState};
 
 /// A mutable field in the DOM.
 ///
 /// This extends the API of `std::cell::RefCell` to allow unsafe access in
 /// certain situations, with dynamic checking in debug builds.
 #[derive(Clone, Debug, Default, MallocSizeOf, PartialEq)]
 pub struct DomRefCell<T> {
     value: RefCell<T>,
@@ -40,17 +40,17 @@ impl<T> DomRefCell<T> {
         // debug_assert!(thread_state::get().contains(SCRIPT | IN_GC));
         &*self.value.as_ptr()
     }
 
     /// Borrow the contents for the purpose of script deallocation.
     ///
     #[allow(unsafe_code)]
     pub unsafe fn borrow_for_script_deallocation(&self) -> &mut T {
-        debug_assert!(thread_state::get().contains(thread_state::SCRIPT));
+        debug_assert!(thread_state::get().contains(ThreadState::SCRIPT));
         &mut *self.value.as_ptr()
     }
 
     /// Version of the above that we use during restyle while the script thread
     /// is blocked.
     pub fn borrow_mut_for_layout(&self) -> RefMut<T> {
         debug_assert!(thread_state::get().is_layout());
         self.value.borrow_mut()
--- a/servo/components/script/dom/bindings/codegen/CodegenRust.py
+++ b/servo/components/script/dom/bindings/codegen/CodegenRust.py
@@ -2034,17 +2034,17 @@ def DOMClass(descriptor):
         globals_ = camel_to_upper_snake(descriptor.name)
     else:
         globals_ = 'EMPTY'
     return """\
 DOMClass {
     interface_chain: [ %s ],
     type_id: %s,
     malloc_size_of: %s as unsafe fn(&mut _, _) -> _,
-    global: InterfaceObjectMap::%s,
+    global: InterfaceObjectMap::Globals::%s,
 }""" % (prototypeChainString, DOMClassTypeId(descriptor), mallocSizeOf, globals_)
 
 
 class CGDOMJSClass(CGThing):
     """
     Generate a DOMJSClass for a given descriptor
     """
     def __init__(self, descriptor):
@@ -2440,17 +2440,17 @@ class CGConstructorEnabled(CGAbstractMet
                                    Argument("HandleObject", "aObj")],
                                   unsafe=True)
 
     def definition_body(self):
         conditions = []
         iface = self.descriptor.interface
 
         bits = " | ".join(sorted(
-            "InterfaceObjectMap::" + camel_to_upper_snake(i) for i in iface.exposureSet
+            "InterfaceObjectMap::Globals::" + camel_to_upper_snake(i) for i in iface.exposureSet
         ))
         conditions.append("is_exposed_in(aObj, %s)" % bits)
 
         pref = iface.getExtendedAttribute("Pref")
         if pref:
             assert isinstance(pref, list) and len(pref) == 1
             conditions.append('PREFS.get("%s").as_boolean().unwrap_or(false)' % pref[0])
 
@@ -7097,19 +7097,19 @@ class GlobalGenRoots():
 
         global_descriptors = config.getDescriptors(isGlobal=True)
         flags = [("EMPTY", 0)]
         flags.extend(
             (camel_to_upper_snake(d.name), 2 ** idx)
             for (idx, d) in enumerate(global_descriptors)
         )
         global_flags = CGWrapper(CGIndenter(CGList([
-            CGGeneric("const %s = %#x," % args)
+            CGGeneric("const %s = %#x;" % args)
             for args in flags
-        ], "\n")), pre="pub flags Globals: u8 {\n", post="\n}")
+        ], "\n")), pre="pub struct Globals: u8 {\n", post="\n}")
         globals_ = CGWrapper(CGIndenter(global_flags), pre="bitflags! {\n", post="\n}")
 
         phf = CGGeneric("include!(concat!(env!(\"OUT_DIR\"), \"/InterfaceObjectMapPhf.rs\"));")
 
         return CGList([
             CGGeneric(AUTOGENERATED_WARNING_COMMENT),
             CGList([imports, globals_, phf], "\n\n")
         ])
--- a/servo/components/script/dom/css.rs
+++ b/servo/components/script/dom/css.rs
@@ -8,17 +8,17 @@ use dom::bindings::error::Fallible;
 use dom::bindings::reflector::Reflector;
 use dom::bindings::str::DOMString;
 use dom::window::Window;
 use dom_struct::dom_struct;
 use style::context::QuirksMode;
 use style::parser::ParserContext;
 use style::stylesheets::CssRuleType;
 use style::stylesheets::supports_rule::{Declaration, parse_condition_or_declaration};
-use style_traits::PARSING_MODE_DEFAULT;
+use style_traits::ParsingMode;
 
 #[dom_struct]
 pub struct CSS {
     reflector_: Reflector,
 }
 
 impl CSS {
     /// <http://dev.w3.org/csswg/cssom/#serialize-an-identifier>
@@ -34,33 +34,33 @@ impl CSS {
         serialize_identifier(&property, &mut decl).unwrap();
         decl.push_str(": ");
         decl.push_str(&value);
         let decl = Declaration(decl);
         let url = win.Document().url();
         let context = ParserContext::new_for_cssom(
             &url,
             Some(CssRuleType::Style),
-            PARSING_MODE_DEFAULT,
+            ParsingMode::DEFAULT,
             QuirksMode::NoQuirks
         );
         decl.eval(&context)
     }
 
     /// <https://drafts.csswg.org/css-conditional/#dom-css-supports>
     pub fn Supports_(win: &Window, condition: DOMString) -> bool {
         let mut input = ParserInput::new(&condition);
         let mut input = Parser::new(&mut input);
         let cond = parse_condition_or_declaration(&mut input);
         if let Ok(cond) = cond {
             let url = win.Document().url();
             let context = ParserContext::new_for_cssom(
                 &url,
                 Some(CssRuleType::Style),
-                PARSING_MODE_DEFAULT,
+                ParsingMode::DEFAULT,
                 QuirksMode::NoQuirks
             );
             cond.eval(&context)
         } else {
             false
         }
     }
 }
--- a/servo/components/script/dom/cssmediarule.rs
+++ b/servo/components/script/dom/cssmediarule.rs
@@ -15,17 +15,17 @@ use dom::cssstylesheet::CSSStyleSheet;
 use dom::medialist::MediaList;
 use dom::window::Window;
 use dom_struct::dom_struct;
 use servo_arc::Arc;
 use style::media_queries::parse_media_query_list;
 use style::parser::ParserContext;
 use style::shared_lock::{Locked, ToCssWithGuard};
 use style::stylesheets::{CssRuleType, MediaRule};
-use style_traits::{PARSING_MODE_DEFAULT, ToCss};
+use style_traits::{ParsingMode, ToCss};
 
 #[dom_struct]
 pub struct CSSMediaRule {
     cssconditionrule: CSSConditionRule,
     #[ignore_malloc_size_of = "Arc"]
     mediarule: Arc<Locked<MediaRule>>,
     medialist: MutNullableDom<MediaList>,
 }
@@ -71,17 +71,17 @@ impl CSSMediaRule {
     pub fn set_condition_text(&self, text: DOMString) {
         let mut input = ParserInput::new(&text);
         let mut input = Parser::new(&mut input);
         let global = self.global();
         let window = global.as_window();
         let url = window.get_url();
         let quirks_mode = window.Document().quirks_mode();
         let context = ParserContext::new_for_cssom(&url, Some(CssRuleType::Media),
-                                                   PARSING_MODE_DEFAULT,
+                                                   ParsingMode::DEFAULT,
                                                    quirks_mode);
 
         let new_medialist = parse_media_query_list(&context, &mut input,
                                                    window.css_error_reporter());
         let mut guard = self.cssconditionrule.shared_lock().write();
 
         // Clone an Arc because we can’t borrow `guard` twice at the same time.
 
--- a/servo/components/script/dom/cssstyledeclaration.rs
+++ b/servo/components/script/dom/cssstyledeclaration.rs
@@ -17,17 +17,17 @@ use dom_struct::dom_struct;
 use servo_arc::Arc;
 use servo_url::ServoUrl;
 use std::ascii::AsciiExt;
 use style::attr::AttrValue;
 use style::properties::{DeclarationSource, Importance, PropertyDeclarationBlock, PropertyId, LonghandId, ShorthandId};
 use style::properties::{parse_one_declaration_into, parse_style_attribute, SourcePropertyDeclaration};
 use style::selector_parser::PseudoElement;
 use style::shared_lock::Locked;
-use style_traits::{PARSING_MODE_DEFAULT, ToCss};
+use style_traits::{ParsingMode, ToCss};
 
 // http://dev.w3.org/csswg/cssom/#the-cssstyledeclaration-interface
 #[dom_struct]
 pub struct CSSStyleDeclaration {
     reflector_: Reflector,
     owner: CSSStyleOwner,
     readonly: bool,
     pseudo: Option<PseudoElement>,
@@ -256,17 +256,17 @@ impl CSSStyleDeclaration {
             };
 
             // Step 5
             let window = self.owner.window();
             let quirks_mode = window.Document().quirks_mode();
             let mut declarations = SourcePropertyDeclaration::new();
             let result = parse_one_declaration_into(
                 &mut declarations, id, &value, &self.owner.base_url(),
-                window.css_error_reporter(), PARSING_MODE_DEFAULT, quirks_mode);
+                window.css_error_reporter(), ParsingMode::DEFAULT, quirks_mode);
 
             // Step 6
             match result {
                 Ok(()) => {},
                 Err(_) => {
                     *changed = false;
                     return Ok(());
                 }
--- a/servo/components/script/dom/csssupportsrule.rs
+++ b/servo/components/script/dom/csssupportsrule.rs
@@ -13,17 +13,17 @@ use dom::cssrule::SpecificCSSRule;
 use dom::cssstylesheet::CSSStyleSheet;
 use dom::window::Window;
 use dom_struct::dom_struct;
 use servo_arc::Arc;
 use style::parser::ParserContext;
 use style::shared_lock::{Locked, ToCssWithGuard};
 use style::stylesheets::{CssRuleType, SupportsRule};
 use style::stylesheets::supports_rule::SupportsCondition;
-use style_traits::{PARSING_MODE_DEFAULT, ToCss};
+use style_traits::{ParsingMode, ToCss};
 
 #[dom_struct]
 pub struct CSSSupportsRule {
     cssconditionrule: CSSConditionRule,
     #[ignore_malloc_size_of = "Arc"]
     supportsrule: Arc<Locked<SupportsRule>>,
 }
 
@@ -59,17 +59,17 @@ impl CSSSupportsRule {
         let mut input = Parser::new(&mut input);
         let cond = SupportsCondition::parse(&mut input);
         if let Ok(cond) = cond {
             let global = self.global();
             let win = global.as_window();
             let url = win.Document().url();
             let quirks_mode = win.Document().quirks_mode();
             let context = ParserContext::new_for_cssom(&url, Some(CssRuleType::Supports),
-                                                       PARSING_MODE_DEFAULT,
+                                                       ParsingMode::DEFAULT,
                                                        quirks_mode);
             let enabled = cond.eval(&context);
             let mut guard = self.cssconditionrule.shared_lock().write();
             let rule = self.supportsrule.write_with(&mut guard);
             rule.condition = cond;
             rule.enabled = enabled;
         }
     }
--- a/servo/components/script/dom/dedicatedworkerglobalscope.rs
+++ b/servo/components/script/dom/dedicatedworkerglobalscope.rs
@@ -36,17 +36,17 @@ use script_runtime::ScriptThreadEventCat
 use script_traits::{TimerEvent, TimerSource, WorkerGlobalScopeInit, WorkerScriptLoadOrigin};
 use servo_rand::random;
 use servo_url::ServoUrl;
 use std::mem::replace;
 use std::sync::{Arc, Mutex};
 use std::sync::atomic::AtomicBool;
 use std::sync::mpsc::{Receiver, RecvError, Select, Sender, channel};
 use std::thread;
-use style::thread_state;
+use style::thread_state::{self, ThreadState};
 
 /// Set the `worker` field of a related DedicatedWorkerGlobalScope object to a particular
 /// value for the duration of this object's lifetime. This ensures that the related Worker
 /// object only lives as long as necessary (ie. while events are being executed), while
 /// providing a reference that can be cloned freely.
 struct AutoWorkerReset<'a> {
     workerscope: &'a DedicatedWorkerGlobalScope,
     old_worker: Option<TrustedWorkerAddress>,
@@ -161,17 +161,17 @@ impl DedicatedWorkerGlobalScope {
                             worker_load_origin: WorkerScriptLoadOrigin,
                             closing: Arc<AtomicBool>) {
         let serialized_worker_url = worker_url.to_string();
         let name = format!("WebWorker for {}", serialized_worker_url);
         let top_level_browsing_context_id = TopLevelBrowsingContextId::installed();
         let origin = GlobalScope::current().expect("No current global object").origin().immutable().clone();
 
         thread::Builder::new().name(name).spawn(move || {
-            thread_state::initialize(thread_state::SCRIPT | thread_state::IN_WORKER);
+            thread_state::initialize(ThreadState::SCRIPT | ThreadState::IN_WORKER);
 
             if let Some(top_level_browsing_context_id) = top_level_browsing_context_id {
                 TopLevelBrowsingContextId::install(top_level_browsing_context_id);
             }
 
             let roots = RootCollection::new();
             let _stack_roots = ThreadLocalStackRoots::new(&roots);
 
--- a/servo/components/script/dom/document.rs
+++ b/servo/components/script/dom/document.rs
@@ -61,17 +61,17 @@ use dom::htmliframeelement::HTMLIFrameEl
 use dom::htmlimageelement::HTMLImageElement;
 use dom::htmlmetaelement::HTMLMetaElement;
 use dom::htmlscriptelement::{HTMLScriptElement, ScriptResult};
 use dom::htmltitleelement::HTMLTitleElement;
 use dom::keyboardevent::KeyboardEvent;
 use dom::location::Location;
 use dom::messageevent::MessageEvent;
 use dom::mouseevent::MouseEvent;
-use dom::node::{self, CloneChildrenFlag, Node, NodeDamage, window_from_node, IS_IN_DOC, LayoutNodeHelpers};
+use dom::node::{self, CloneChildrenFlag, Node, NodeDamage, window_from_node, NodeFlags, LayoutNodeHelpers};
 use dom::node::VecPreOrderInsertionHelper;
 use dom::nodeiterator::NodeIterator;
 use dom::nodelist::NodeList;
 use dom::pagetransitionevent::PageTransitionEvent;
 use dom::popstateevent::PopStateEvent;
 use dom::processinginstruction::ProcessingInstruction;
 use dom::progressevent::ProgressEvent;
 use dom::promise::Promise;
@@ -95,17 +95,16 @@ use encoding::all::UTF_8;
 use euclid::Point2D;
 use html5ever::{LocalName, Namespace, QualName};
 use hyper::header::{Header, SetCookie};
 use hyper_serde::Serde;
 use ipc_channel::ipc::{self, IpcSender};
 use js::jsapi::{JSContext, JSRuntime};
 use js::jsapi::JS_GetRuntime;
 use metrics::{InteractiveFlag, InteractiveMetrics, InteractiveWindow, ProfilerMetadataFactory};
-use msg::constellation_msg::{ALT, CONTROL, SHIFT, SUPER};
 use msg::constellation_msg::{BrowsingContextId, Key, KeyModifiers, KeyState, TopLevelBrowsingContextId};
 use net_traits::{FetchResponseMsg, IpcSend, ReferrerPolicy};
 use net_traits::CookieSource::NonHTTP;
 use net_traits::CoreResourceMsg::{GetCookiesForUrl, SetCookiesForUrl};
 use net_traits::pub_domains::is_pub_domain;
 use net_traits::request::RequestInit;
 use net_traits::response::HttpsState;
 use num_traits::ToPrimitive;
@@ -127,17 +126,17 @@ use std::collections::{HashMap, HashSet,
 use std::collections::hash_map::Entry::{Occupied, Vacant};
 use std::default::Default;
 use std::iter::once;
 use std::mem;
 use std::rc::Rc;
 use std::time::{Duration, Instant};
 use style::attr::AttrValue;
 use style::context::QuirksMode;
-use style::invalidation::element::restyle_hints::{RestyleHint, RESTYLE_SELF, RESTYLE_STYLE_ATTRIBUTE};
+use style::invalidation::element::restyle_hints::RestyleHint;
 use style::media_queries::{Device, MediaList, MediaType};
 use style::selector_parser::{RestyleDamage, Snapshot};
 use style::shared_lock::{SharedRwLock as StyleSharedRwLock, SharedRwLockReadGuard};
 use style::str::{HTML_SPACE_CHARACTERS, split_html_space_chars, str_join};
 use style::stylesheet_set::StylesheetSet;
 use style::stylesheets::{Stylesheet, StylesheetContents, Origin, OriginSet};
 use task_source::TaskSource;
 use time;
@@ -1291,20 +1290,20 @@ impl Document {
         let body = self.GetBody();
 
         let target = match (&focused, &body) {
             (&Some(ref focused), _) => focused.upcast(),
             (&None, &Some(ref body)) => body.upcast(),
             (&None, &None) => self.window.upcast(),
         };
 
-        let ctrl = modifiers.contains(CONTROL);
-        let alt = modifiers.contains(ALT);
-        let shift = modifiers.contains(SHIFT);
-        let meta = modifiers.contains(SUPER);
+        let ctrl = modifiers.contains(KeyModifiers::CONTROL);
+        let alt = modifiers.contains(KeyModifiers::ALT);
+        let shift = modifiers.contains(KeyModifiers::SHIFT);
+        let meta = modifiers.contains(KeyModifiers::SUPER);
 
         let is_composing = false;
         let is_repeating = state == KeyState::Repeated;
         let ev_type = DOMString::from(match state {
                                           KeyState::Pressed | KeyState::Repeated => "keydown",
                                           KeyState::Released => "keyup",
                                       }
                                       .to_owned());
@@ -2061,17 +2060,17 @@ impl LayoutDocumentHelpers for LayoutDom
     #[inline]
     #[allow(unrooted_must_root)]
     unsafe fn drain_pending_restyles(&self) -> Vec<(LayoutDom<Element>, PendingRestyle)> {
         let mut elements = (*self.unsafe_get()).pending_restyles.borrow_mut_for_layout();
         // Elements were in a document when they were adding to this list, but that
         // may no longer be true when the next layout occurs.
         let result = elements.drain()
             .map(|(k, v)| (k.to_layout(), v))
-            .filter(|&(ref k, _)| k.upcast::<Node>().get_flag(IS_IN_DOC))
+            .filter(|&(ref k, _)| k.upcast::<Node>().get_flag(NodeFlags::IS_IN_DOC))
             .collect();
         result
     }
 
     #[inline]
     unsafe fn needs_paint_from_layout(&self) {
         (*self.unsafe_get()).needs_paint.set(true)
     }
@@ -2507,21 +2506,21 @@ impl Document {
         // I'm getting rid of the whole hashtable soon anyway, since all it does
         // right now is populate the element restyle data in layout, and we
         // could in theory do it in the DOM I think.
         let mut entry = self.ensure_pending_restyle(el);
         if entry.snapshot.is_none() {
             entry.snapshot = Some(Snapshot::new(el.html_element_in_html_document()));
         }
         if attr.local_name() == &local_name!("style") {
-            entry.hint.insert(RESTYLE_STYLE_ATTRIBUTE);
+            entry.hint.insert(RestyleHint::RESTYLE_STYLE_ATTRIBUTE);
         }
 
         if vtable_for(el.upcast()).attribute_affects_presentational_hints(attr) {
-            entry.hint.insert(RESTYLE_SELF);
+            entry.hint.insert(RestyleHint::RESTYLE_SELF);
         }
 
         let snapshot = entry.snapshot.as_mut().unwrap();
         if attr.local_name() == &local_name!("id") {
             snapshot.id_changed = true;
         } else if attr.local_name() == &local_name!("class") {
             snapshot.class_changed = true;
         } else {
--- a/servo/components/script/dom/element.rs
+++ b/servo/components/script/dom/element.rs
@@ -60,18 +60,18 @@ use dom::htmlstyleelement::HTMLStyleElem
 use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementLayoutHelpers};
 use dom::htmltableelement::{HTMLTableElement, HTMLTableElementLayoutHelpers};
 use dom::htmltablerowelement::{HTMLTableRowElement, HTMLTableRowElementLayoutHelpers};
 use dom::htmltablesectionelement::{HTMLTableSectionElement, HTMLTableSectionElementLayoutHelpers};
 use dom::htmltemplateelement::HTMLTemplateElement;
 use dom::htmltextareaelement::{HTMLTextAreaElement, LayoutHTMLTextAreaElementHelpers};
 use dom::mutationobserver::{Mutation, MutationObserver};
 use dom::namednodemap::NamedNodeMap;
-use dom::node::{CLICK_IN_PROGRESS, ChildrenMutation, LayoutNodeHelpers, Node};
-use dom::node::{NodeDamage, SEQUENTIALLY_FOCUSABLE, UnbindContext};
+use dom::node::{ChildrenMutation, LayoutNodeHelpers, Node};
+use dom::node::{NodeDamage, NodeFlags, UnbindContext};
 use dom::node::{document_from_node, window_from_node};
 use dom::nodelist::NodeList;
 use dom::promise::Promise;
 use dom::servoparser::ServoParser;
 use dom::text::Text;
 use dom::validation::Validatable;
 use dom::virtualmethods::{VirtualMethods, vtable_for};
 use dom::window::ReflowReason;
@@ -85,35 +85,34 @@ use js::jsapi::Heap;
 use js::jsval::JSVal;
 use net_traits::request::CorsSettings;
 use ref_filter_map::ref_filter_map;
 use script_layout_interface::message::ReflowGoal;
 use script_thread::ScriptThread;
 use selectors::Element as SelectorsElement;
 use selectors::attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivity};
 use selectors::matching::{ElementSelectorFlags, MatchingContext, RelevantLinkStatus};
-use selectors::matching::{HAS_EDGE_CHILD_SELECTOR, HAS_SLOW_SELECTOR, HAS_SLOW_SELECTOR_LATER_SIBLINGS};
 use selectors::sink::Push;
 use servo_arc::Arc;
 use servo_atoms::Atom;
 use std::ascii::AsciiExt;
 use std::borrow::Cow;
 use std::cell::{Cell, Ref};
 use std::default::Default;
 use std::fmt;
 use std::mem;
 use std::rc::Rc;
 use std::str::FromStr;
 use style::CaseSensitivityExt;
 use style::applicable_declarations::ApplicableDeclarationBlock;
 use style::attr::{AttrValue, LengthOrPercentageOrAuto};
 use style::context::QuirksMode;
 use style::dom_apis;
-use style::element_state::*;
-use style::invalidation::element::restyle_hints::RESTYLE_SELF;
+use style::element_state::ElementState;
+use style::invalidation::element::restyle_hints::RestyleHint;
 use style::properties::{Importance, PropertyDeclaration, PropertyDeclarationBlock, parse_style_attribute};
 use style::properties::longhands::{self, background_image, border_spacing, font_family, font_size, overflow_x};
 use style::rule_tree::CascadeLevel;
 use style::selector_parser::{NonTSPseudoClass, PseudoElement, RestyleDamage, SelectorImpl, SelectorParser};
 use style::selector_parser::extended_filtering;
 use style::shared_lock::{SharedRwLock, Locked};
 use style::thread_state;
 use style::values::{CSSFloat, Either};
@@ -287,17 +286,17 @@ impl Element {
     }
 
     pub fn restyle(&self, damage: NodeDamage) {
         let doc = self.node.owner_doc();
         let mut restyle = doc.ensure_pending_restyle(self);
 
         // FIXME(bholley): I think we should probably only do this for
         // NodeStyleDamaged, but I'm preserving existing behavior.
-        restyle.hint.insert(RESTYLE_SELF);
+        restyle.hint.insert(RestyleHint::RESTYLE_SELF);
 
         if damage == NodeDamage::OtherNodeDamage {
             restyle.damage = RestyleDamage::rebuild_and_reflow();
         }
     }
 
     pub fn set_is(&self, is: LocalName) {
         *self.is.borrow_mut() = Some(is);
@@ -1057,17 +1056,17 @@ impl Element {
     }
 
     pub fn is_focusable_area(&self) -> bool {
         if self.is_actually_disabled() {
             return false;
         }
         // TODO: Check whether the element is being rendered (i.e. not hidden).
         let node = self.upcast::<Node>();
-        if node.get_flag(SEQUENTIALLY_FOCUSABLE) {
+        if node.get_flag(NodeFlags::SEQUENTIALLY_FOCUSABLE) {
             return true;
         }
         // https://html.spec.whatwg.org/multipage/#specially-focusable
         match node.type_id() {
             NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) |
             NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) |
             NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) |
             NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => {
@@ -2475,30 +2474,30 @@ impl VirtualMethods for Element {
     }
 
     fn children_changed(&self, mutation: &ChildrenMutation) {
         if let Some(ref s) = self.super_type() {
             s.children_changed(mutation);
         }
 
         let flags = self.selector_flags.get();
-        if flags.intersects(HAS_SLOW_SELECTOR) {
+        if flags.intersects(ElementSelectorFlags::HAS_SLOW_SELECTOR) {
             // All children of this node need to be restyled when any child changes.
             self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
         } else {
-            if flags.intersects(HAS_SLOW_SELECTOR_LATER_SIBLINGS) {
+            if flags.intersects(ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS) {
                 if let Some(next_child) = mutation.next_child() {
                     for child in next_child.inclusively_following_siblings() {
                         if child.is::<Element>() {
                             child.dirty(NodeDamage::OtherNodeDamage);
                         }
                     }
                 }
             }
-            if flags.intersects(HAS_EDGE_CHILD_SELECTOR) {
+            if flags.intersects(ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR) {
                 if let Some(child) = mutation.modified_edge_element() {
                     child.dirty(NodeDamage::OtherNodeDamage);
                 }
             }
         }
     }
 
     fn adopting_steps(&self, old_doc: &Document) {
@@ -2742,21 +2741,21 @@ impl Element {
             _ => {
                 None
             }
         };
         element
     }
 
     pub fn click_in_progress(&self) -> bool {
-        self.upcast::<Node>().get_flag(CLICK_IN_PROGRESS)
+        self.upcast::<Node>().get_flag(NodeFlags::CLICK_IN_PROGRESS)
     }
 
     pub fn set_click_in_progress(&self, click: bool) {
-        self.upcast::<Node>().set_flag(CLICK_IN_PROGRESS, click)
+        self.upcast::<Node>().set_flag(NodeFlags::CLICK_IN_PROGRESS, click)
     }
 
     // https://html.spec.whatwg.org/multipage/#nearest-activatable-element
     pub fn nearest_activable_element(&self) -> Option<DomRoot<Element>> {
         match self.as_maybe_activatable() {
             Some(el) => Some(DomRoot::from_ref(el.as_element())),
             None => {
                 let node = self.upcast::<Node>();
@@ -2846,94 +2845,94 @@ impl Element {
             state.insert(which);
         } else {
             state.remove(which);
         }
         self.state.set(state);
     }
 
     pub fn active_state(&self) -> bool {
-        self.state.get().contains(IN_ACTIVE_STATE)
+        self.state.get().contains(ElementState::IN_ACTIVE_STATE)
     }
 
     /// <https://html.spec.whatwg.org/multipage/#concept-selector-active>
     pub fn set_active_state(&self, value: bool) {
-        self.set_state(IN_ACTIVE_STATE, value);
+        self.set_state(ElementState::IN_ACTIVE_STATE, value);
 
         if let Some(parent) = self.upcast::<Node>().GetParentElement() {
             parent.set_active_state(value);
         }
     }
 
     pub fn focus_state(&self) -> bool {
-        self.state.get().contains(IN_FOCUS_STATE)
+        self.state.get().contains(ElementState::IN_FOCUS_STATE)
     }
 
     pub fn set_focus_state(&self, value: bool) {
-        self.set_state(IN_FOCUS_STATE, value);
+        self.set_state(ElementState::IN_FOCUS_STATE, value);
         self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
     }
 
     pub fn hover_state(&self) -> bool {
-        self.state.get().contains(IN_HOVER_STATE)
+        self.state.get().contains(ElementState::IN_HOVER_STATE)
     }
 
     pub fn set_hover_state(&self, value: bool) {
-        self.set_state(IN_HOVER_STATE, value)
+        self.set_state(ElementState::IN_HOVER_STATE, value)
     }
 
     pub fn enabled_state(&self) -> bool {
-        self.state.get().contains(IN_ENABLED_STATE)
+        self.state.get().contains(ElementState::IN_ENABLED_STATE)
     }
 
     pub fn set_enabled_state(&self, value: bool) {
-        self.set_state(IN_ENABLED_STATE, value)
+        self.set_state(ElementState::IN_ENABLED_STATE, value)
     }
 
     pub fn disabled_state(&self) -> bool {
-        self.state.get().contains(IN_DISABLED_STATE)
+        self.state.get().contains(ElementState::IN_DISABLED_STATE)
     }
 
     pub fn set_disabled_state(&self, value: bool) {
-        self.set_state(IN_DISABLED_STATE, value)
+        self.set_state(ElementState::IN_DISABLED_STATE, value)
     }
 
     pub fn read_write_state(&self) -> bool {
-        self.state.get().contains(IN_READ_WRITE_STATE)
+        self.state.get().contains(ElementState::IN_READ_WRITE_STATE)
     }
 
     pub fn set_read_write_state(&self, value: bool) {
-        self.set_state(IN_READ_WRITE_STATE, value)
+        self.set_state(ElementState::IN_READ_WRITE_STATE, value)
     }
 
     pub fn placeholder_shown_state(&self) -> bool {
-        self.state.get().contains(IN_PLACEHOLDER_SHOWN_STATE)
+        self.state.get().contains(ElementState::IN_PLACEHOLDER_SHOWN_STATE)
     }
 
     pub fn set_placeholder_shown_state(&self, value: bool) {
         if self.placeholder_shown_state() != value {
-            self.set_state(IN_PLACEHOLDER_SHOWN_STATE, value);
+            self.set_state(ElementState::IN_PLACEHOLDER_SHOWN_STATE, value);
             self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
         }
     }
 
     pub fn target_state(&self) -> bool {
-        self.state.get().contains(IN_TARGET_STATE)
+        self.state.get().contains(ElementState::IN_TARGET_STATE)
     }
 
     pub fn set_target_state(&self, value: bool) {
-        self.set_state(IN_TARGET_STATE, value)
+        self.set_state(ElementState::IN_TARGET_STATE, value)
     }
 
     pub fn fullscreen_state(&self) -> bool {
-        self.state.get().contains(IN_FULLSCREEN_STATE)
+        self.state.get().contains(ElementState::IN_FULLSCREEN_STATE)
     }
 
     pub fn set_fullscreen_state(&self, value: bool) {
-        self.set_state(IN_FULLSCREEN_STATE, value)
+        self.set_state(ElementState::IN_FULLSCREEN_STATE, value)
     }
 
     /// <https://dom.spec.whatwg.org/#connected>
     pub fn is_connected(&self) -> bool {
         let node = self.upcast::<Node>();
         let root = node.GetRootNode();
         root.is::<Document>()
     }
--- a/servo/components/script/dom/htmlbuttonelement.rs
+++ b/servo/components/script/dom/htmlbuttonelement.rs
@@ -22,17 +22,17 @@ use dom::node::{Node, UnbindContext, doc
 use dom::nodelist::NodeList;
 use dom::validation::Validatable;
 use dom::validitystate::{ValidityState, ValidationFlags};
 use dom::virtualmethods::VirtualMethods;
 use dom_struct::dom_struct;
 use html5ever::{LocalName, Prefix};
 use std::cell::Cell;
 use std::default::Default;
-use style::element_state::*;
+use style::element_state::ElementState;
 
 #[derive(Clone, Copy, JSTraceable, PartialEq)]
 #[derive(MallocSizeOf)]
 enum ButtonType {
     Submit,
     Reset,
     Button,
     Menu
@@ -46,17 +46,17 @@ pub struct HTMLButtonElement {
 }
 
 impl HTMLButtonElement {
     fn new_inherited(local_name: LocalName,
                      prefix: Option<Prefix>,
                      document: &Document) -> HTMLButtonElement {
         HTMLButtonElement {
             htmlelement:
-                HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
+                HTMLElement::new_inherited_with_state(ElementState::IN_ENABLED_STATE,
                                                       local_name, prefix, document),
             button_type: Cell::new(ButtonType::Submit),
             form_owner: Default::default(),
         }
     }
 
     #[allow(unrooted_must_root)]
     pub fn new(local_name: LocalName,
--- a/servo/components/script/dom/htmlelement.rs
+++ b/servo/components/script/dom/htmlelement.rs
@@ -19,17 +19,17 @@ use dom::document::{Document, FocusType}
 use dom::domstringmap::DOMStringMap;
 use dom::element::{AttributeMutation, Element};
 use dom::eventtarget::EventTarget;
 use dom::htmlbodyelement::HTMLBodyElement;
 use dom::htmlframesetelement::HTMLFrameSetElement;
 use dom::htmlhtmlelement::HTMLHtmlElement;
 use dom::htmlinputelement::HTMLInputElement;
 use dom::htmllabelelement::HTMLLabelElement;
-use dom::node::{Node, SEQUENTIALLY_FOCUSABLE};
+use dom::node::{Node, NodeFlags};
 use dom::node::{document_from_node, window_from_node};
 use dom::nodelist::NodeList;
 use dom::virtualmethods::VirtualMethods;
 use dom_struct::dom_struct;
 use html5ever::{LocalName, Prefix};
 use std::ascii::AsciiExt;
 use std::default::Default;
 use std::rc::Rc;
@@ -71,40 +71,40 @@ impl HTMLElement {
         let eventtarget = self.upcast::<EventTarget>();
         eventtarget.is::<HTMLBodyElement>() || eventtarget.is::<HTMLFrameSetElement>()
     }
 
     fn update_sequentially_focusable_status(&self) {
         let element = self.upcast::<Element>();
         let node = self.upcast::<Node>();
         if element.has_attribute(&local_name!("tabindex")) {
-            node.set_flag(SEQUENTIALLY_FOCUSABLE, true);
+            node.set_flag(NodeFlags::SEQUENTIALLY_FOCUSABLE, true);
         } else {
             match node.type_id() {
                 NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) |
                 NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) |
                 NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLIFrameElement)) |
                 NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement))
-                    => node.set_flag(SEQUENTIALLY_FOCUSABLE, true),
+                    => node.set_flag(NodeFlags::SEQUENTIALLY_FOCUSABLE, true),
                 NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLinkElement)) |
                 NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) => {
                     if element.has_attribute(&local_name!("href")) {
-                        node.set_flag(SEQUENTIALLY_FOCUSABLE, true);
+                        node.set_flag(NodeFlags::SEQUENTIALLY_FOCUSABLE, true);
                     }
                 },
                 _ => {
                     if let Some(attr) = element.get_attribute(&ns!(), &local_name!("draggable")) {
                         let value = attr.value();
                         let is_true = match *value {
                             AttrValue::String(ref string) => string == "true",
                             _ => false,
                         };
-                        node.set_flag(SEQUENTIALLY_FOCUSABLE, is_true);
+                        node.set_flag(NodeFlags::SEQUENTIALLY_FOCUSABLE, is_true);
                     } else {
-                        node.set_flag(SEQUENTIALLY_FOCUSABLE, false);
+                        node.set_flag(NodeFlags::SEQUENTIALLY_FOCUSABLE, false);
                     }
                     //TODO set SEQUENTIALLY_FOCUSABLE flag if editing host
                     //TODO set SEQUENTIALLY_FOCUSABLE flag if "sorting interface th elements"
                 },
             }
         }
     }
 }
--- a/servo/components/script/dom/htmlfieldsetelement.rs
+++ b/servo/components/script/dom/htmlfieldsetelement.rs
@@ -14,31 +14,31 @@ use dom::htmlelement::HTMLElement;
 use dom::htmlformelement::{FormControl, HTMLFormElement};
 use dom::htmllegendelement::HTMLLegendElement;
 use dom::node::{Node, window_from_node};
 use dom::validitystate::ValidityState;
 use dom::virtualmethods::VirtualMethods;
 use dom_struct::dom_struct;
 use html5ever::{LocalName, Prefix};
 use std::default::Default;
-use style::element_state::*;
+use style::element_state::ElementState;
 
 #[dom_struct]
 pub struct HTMLFieldSetElement {
     htmlelement: HTMLElement,
     form_owner: MutNullableDom<HTMLFormElement>,
 }
 
 impl HTMLFieldSetElement {
     fn new_inherited(local_name: LocalName,
                      prefix: Option<Prefix>,
                      document: &Document) -> HTMLFieldSetElement {
         HTMLFieldSetElement {
             htmlelement:
-                HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
+                HTMLElement::new_inherited_with_state(ElementState::IN_ENABLED_STATE,
                                                       local_name, prefix, document),
             form_owner: Default::default(),
         }
     }
 
     #[allow(unrooted_must_root)]
     pub fn new(local_name: LocalName,
                prefix: Option<Prefix>,
--- a/servo/components/script/dom/htmlformelement.rs
+++ b/servo/components/script/dom/htmlformelement.rs
@@ -32,17 +32,17 @@ use dom::htmlformcontrolscollection::HTM
 use dom::htmlimageelement::HTMLImageElement;
 use dom::htmlinputelement::HTMLInputElement;
 use dom::htmllabelelement::HTMLLabelElement;
 use dom::htmllegendelement::HTMLLegendElement;
 use dom::htmlobjectelement::HTMLObjectElement;
 use dom::htmloutputelement::HTMLOutputElement;
 use dom::htmlselectelement::HTMLSelectElement;
 use dom::htmltextareaelement::HTMLTextAreaElement;
-use dom::node::{Node, PARSER_ASSOCIATED_FORM_OWNER, UnbindContext, VecPreOrderInsertionHelper};
+use dom::node::{Node, NodeFlags, UnbindContext, VecPreOrderInsertionHelper};
 use dom::node::{document_from_node, window_from_node};
 use dom::validitystate::ValidationFlags;
 use dom::virtualmethods::VirtualMethods;
 use dom_struct::dom_struct;
 use encoding::EncodingRef;
 use encoding::all::UTF_8;
 use encoding::label::encoding_from_whatwg_label;
 use html5ever::{LocalName, Prefix};
@@ -874,17 +874,17 @@ pub trait FormControl: DomObject {
 
     // https://html.spec.whatwg.org/multipage/#create-an-element-for-the-token
     // Part of step 12.
     // '..suppress the running of the reset the form owner algorithm
     // when the parser subsequently attempts to insert the element..'
     fn set_form_owner_from_parser(&self, form: &HTMLFormElement) {
         let elem = self.to_element();
         let node = elem.upcast::<Node>();
-        node.set_flag(PARSER_ASSOCIATED_FORM_OWNER, true);
+        node.set_flag(NodeFlags::PARSER_ASSOCIATED_FORM_OWNER, true);
         form.add_control(self);
         self.set_form_owner(Some(form));
     }
 
     // https://html.spec.whatwg.org/multipage/#reset-the-form-owner
     fn reset_form_owner(&self) {
         let elem = self.to_element();
         let node = elem.upcast::<Node>();
@@ -963,18 +963,18 @@ pub trait FormControl: DomObject {
     fn bind_form_control_to_tree(&self) {
         let elem = self.to_element();
         let node = elem.upcast::<Node>();
 
         // https://html.spec.whatwg.org/multipage/#create-an-element-for-the-token
         // Part of step 12.
         // '..suppress the running of the reset the form owner algorithm
         // when the parser subsequently attempts to insert the element..'
-        let must_skip_reset = node.get_flag(PARSER_ASSOCIATED_FORM_OWNER);
-        node.set_flag(PARSER_ASSOCIATED_FORM_OWNER, false);
+        let must_skip_reset = node.get_flag(NodeFlags::PARSER_ASSOCIATED_FORM_OWNER);
+        node.set_flag(NodeFlags::PARSER_ASSOCIATED_FORM_OWNER, false);
 
         if !must_skip_reset {
             self.form_attribute_mutated(AttributeMutation::Set(None));
         }
     }
 
     // https://html.spec.whatwg.org/multipage/#association-of-controls-and-forms
     fn unbind_form_control_from_tree(&self) {
--- a/servo/components/script/dom/htmliframeelement.rs
+++ b/servo/components/script/dom/htmliframeelement.rs
@@ -52,24 +52,24 @@ use servo_config::prefs::PREFS;
 use servo_config::servo_version;
 use servo_url::ServoUrl;
 use std::cell::Cell;
 use style::attr::{AttrValue, LengthOrPercentageOrAuto};
 use task_source::TaskSource;
 
 bitflags! {
     #[derive(JSTraceable, MallocSizeOf)]
-    flags SandboxAllowance: u8 {
-        const ALLOW_NOTHING = 0x00,
-        const ALLOW_SAME_ORIGIN = 0x01,
-        const ALLOW_TOP_NAVIGATION = 0x02,
-        const ALLOW_FORMS = 0x04,
-        const ALLOW_SCRIPTS = 0x08,
-        const ALLOW_POINTER_LOCK = 0x10,
-        const ALLOW_POPUPS = 0x20
+    struct SandboxAllowance: u8 {
+        const ALLOW_NOTHING = 0x00;
+        const ALLOW_SAME_ORIGIN = 0x01;
+        const ALLOW_TOP_NAVIGATION = 0x02;
+        const ALLOW_FORMS = 0x04;
+        const ALLOW_SCRIPTS = 0x08;
+        const ALLOW_POINTER_LOCK = 0x10;
+        const ALLOW_POPUPS = 0x20;
     }
 }
 
 #[derive(PartialEq)]
 pub enum NavigationType {
     InitialAboutBlank,
     Regular,
 }
@@ -717,26 +717,26 @@ impl VirtualMethods for HTMLIFrameElemen
         Some(self.upcast::<HTMLElement>() as &VirtualMethods)
     }
 
     fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
         self.super_type().unwrap().attribute_mutated(attr, mutation);
         match attr.local_name() {
             &local_name!("sandbox") => {
                 self.sandbox_allowance.set(mutation.new_value(attr).map(|value| {
-                    let mut modes = ALLOW_NOTHING;
+                    let mut modes = SandboxAllowance::ALLOW_NOTHING;
                     for token in value.as_tokens() {
                         modes |= match &*token.to_ascii_lowercase() {
-                            "allow-same-origin" => ALLOW_SAME_ORIGIN,
-                            "allow-forms" => ALLOW_FORMS,
-                            "allow-pointer-lock" => ALLOW_POINTER_LOCK,
-                            "allow-popups" => ALLOW_POPUPS,
-                            "allow-scripts" => ALLOW_SCRIPTS,
-                            "allow-top-navigation" => ALLOW_TOP_NAVIGATION,
-                            _ => ALLOW_NOTHING
+                            "allow-same-origin" => SandboxAllowance::ALLOW_SAME_ORIGIN,
+                            "allow-forms" => SandboxAllowance::ALLOW_FORMS,
+                            "allow-pointer-lock" => SandboxAllowance::ALLOW_POINTER_LOCK,
+                            "allow-popups" => SandboxAllowance::ALLOW_POPUPS,
+                            "allow-scripts" => SandboxAllowance::ALLOW_SCRIPTS,
+                            "allow-top-navigation" => SandboxAllowance::ALLOW_TOP_NAVIGATION,
+                            _ => SandboxAllowance::ALLOW_NOTHING
                         };
                     }
                     modes
                 }));
             },
             &local_name!("src") => {
                 // https://html.spec.whatwg.org/multipage/#the-iframe-element
                 // "Similarly, whenever an iframe element with a non-null nested browsing context
--- a/servo/components/script/dom/htmlinputelement.rs
+++ b/servo/components/script/dom/htmlinputelement.rs
@@ -43,17 +43,17 @@ use net_traits::blob_url_store::get_blob
 use net_traits::filemanager_thread::{FileManagerThreadMsg, FilterPattern};
 use script_layout_interface::rpc::TextIndexResponse;
 use script_traits::ScriptToConstellationChan;
 use servo_atoms::Atom;
 use std::borrow::ToOwned;
 use std::cell::Cell;
 use std::ops::Range;
 use style::attr::AttrValue;
-use style::element_state::*;
+use style::element_state::ElementState;
 use style::str::split_commas;
 use textinput::{SelectionDirection, TextInput};
 use textinput::KeyReaction::{DispatchInput, Nothing, RedrawSelection, TriggerDefaultAction};
 use textinput::Lines::Single;
 
 const DEFAULT_SUBMIT_VALUE: &'static str = "Submit";
 const DEFAULT_RESET_VALUE: &'static str = "Reset";
 const PASSWORD_REPLACEMENT_CHAR: char = '●';
@@ -132,17 +132,18 @@ static DEFAULT_INPUT_SIZE: u32 = 20;
 static DEFAULT_MAX_LENGTH: i32 = -1;
 static DEFAULT_MIN_LENGTH: i32 = -1;
 
 impl HTMLInputElement {
     fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLInputElement {
         let chan = document.window().upcast::<GlobalScope>().script_to_constellation_chan().clone();
         HTMLInputElement {
             htmlelement:
-                HTMLElement::new_inherited_with_state(IN_ENABLED_STATE | IN_READ_WRITE_STATE,
+                HTMLElement::new_inherited_with_state(ElementState::IN_ENABLED_STATE |
+                                                      ElementState::IN_READ_WRITE_STATE,
                                                       local_name, prefix, document),
             input_type: Cell::new(InputType::InputText),
             placeholder: DomRefCell::new(DOMString::new()),
             checked_changed: Cell::new(false),
             value_changed: Cell::new(false),
             maxlength: Cell::new(DEFAULT_MAX_LENGTH),
             minlength: Cell::new(DEFAULT_MIN_LENGTH),
             size: Cell::new(DEFAULT_INPUT_SIZE),
@@ -275,23 +276,23 @@ impl LayoutHTMLInputElementHelpers for L
             InputType::InputText => Some(textinput.get_absolute_selection_range()),
             _ => None
         }
     }
 
     #[allow(unrooted_must_root)]
     #[allow(unsafe_code)]
     unsafe fn checked_state_for_layout(self) -> bool {
-        self.upcast::<Element>().get_state_for_layout().contains(IN_CHECKED_STATE)
+        self.upcast::<Element>().get_state_for_layout().contains(ElementState::IN_CHECKED_STATE)
     }
 
     #[allow(unrooted_must_root)]
     #[allow(unsafe_code)]
     unsafe fn indeterminate_state_for_layout(self) -> bool {
-        self.upcast::<Element>().get_state_for_layout().contains(IN_INDETERMINATE_STATE)
+        self.upcast::<Element>().get_state_for_layout().contains(ElementState::IN_INDETERMINATE_STATE)
     }
 }
 
 impl HTMLInputElementMethods for HTMLInputElement {
     // https://html.spec.whatwg.org/multipage/#dom-input-accept
     make_getter!(Accept, "accept");
 
     // https://html.spec.whatwg.org/multipage/#dom-input-accept
@@ -331,17 +332,17 @@ impl HTMLInputElementMethods for HTMLInp
     // https://html.spec.whatwg.org/multipage/#dom-input-defaultchecked
     make_bool_getter!(DefaultChecked, "checked");
 
     // https://html.spec.whatwg.org/multipage/#dom-input-defaultchecked
     make_bool_setter!(SetDefaultChecked, "checked");
 
     // https://html.spec.whatwg.org/multipage/#dom-input-checked
     fn Checked(&self) -> bool {
-        self.upcast::<Element>().state().contains(IN_CHECKED_STATE)
+        self.upcast::<Element>().state().contains(ElementState::IN_CHECKED_STATE)
     }
 
     // https://html.spec.whatwg.org/multipage/#dom-input-checked
     fn SetChecked(&self, checked: bool) {
         self.update_checked_state(checked, true);
     }
 
     // https://html.spec.whatwg.org/multipage/#dom-input-readonly
@@ -533,22 +534,22 @@ impl HTMLInputElementMethods for HTMLInp
     // https://html.spec.whatwg.org/multipage/#dom-input-step
     make_getter!(Step, "step");
 
     // https://html.spec.whatwg.org/multipage/#dom-input-step
     make_setter!(SetStep, "step");
 
     // https://html.spec.whatwg.org/multipage/#dom-input-indeterminate
     fn Indeterminate(&self) -> bool {
-        self.upcast::<Element>().state().contains(IN_INDETERMINATE_STATE)
+        self.upcast::<Element>().state().contains(ElementState::IN_INDETERMINATE_STATE)
     }
 
     // https://html.spec.whatwg.org/multipage/#dom-input-indeterminate
     fn SetIndeterminate(&self, val: bool) {
-        self.upcast::<Element>().set_state(IN_INDETERMINATE_STATE, val)
+        self.upcast::<Element>().set_state(ElementState::IN_INDETERMINATE_STATE, val)
     }
 
     // https://html.spec.whatwg.org/multipage/#dom-lfe-labels
     fn Labels(&self) -> DomRoot<NodeList> {
         if self.type_() == atom!("hidden") {
             let window = window_from_node(self);
             NodeList::empty(&window)
         } else {
@@ -740,17 +741,17 @@ impl HTMLInputElement {
     fn radio_group_name(&self) -> Option<Atom> {
         //TODO: determine form owner
         self.upcast::<Element>()
             .get_attribute(&ns!(), &local_name!("name"))
             .map(|name| name.value().as_atom().clone())
     }
 
     fn update_checked_state(&self, checked: bool, dirty: bool) {
-        self.upcast::<Element>().set_state(IN_CHECKED_STATE, checked);
+        self.upcast::<Element>().set_state(ElementState::IN_CHECKED_STATE, checked);
 
         if dirty {
             self.checked_changed.set(true);
         }
 
         if self.input_type.get() == InputType::InputRadio && checked {
             broadcast_radio_checked(self,
                                     self.radio_group_name().as_ref());
--- a/servo/components/script/dom/htmllinkelement.rs
+++ b/servo/components/script/dom/htmllinkelement.rs
@@ -30,17 +30,17 @@ use std::ascii::AsciiExt;
 use std::borrow::ToOwned;
 use std::cell::Cell;
 use std::default::Default;
 use style::attr::AttrValue;
 use style::media_queries::parse_media_query_list;
 use style::parser::ParserContext as CssParserContext;
 use style::str::HTML_SPACE_CHARACTERS;
 use style::stylesheets::{CssRuleType, Stylesheet};
-use style_traits::PARSING_MODE_DEFAULT;
+use style_traits::ParsingMode;
 use stylesheet_loader::{StylesheetLoader, StylesheetContextSource, StylesheetOwner};
 
 #[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
 pub struct RequestGenerationId(u32);
 
 impl RequestGenerationId {
     fn increment(self) -> RequestGenerationId {
         RequestGenerationId(self.0 + 1)
@@ -282,17 +282,17 @@ impl HTMLLinkElement {
             Some(ref value) => &***value,
             None => "",
         };
 
         let mut input = ParserInput::new(&mq_str);
         let mut css_parser = CssParser::new(&mut input);
         let doc_url = document.url();
         let context = CssParserContext::new_for_cssom(&doc_url, Some(CssRuleType::Media),
-                                                      PARSING_MODE_DEFAULT,
+                                                      ParsingMode::DEFAULT,
                                                       document.quirks_mode());
         let window = document.window();
         let media = parse_media_query_list(&context, &mut css_parser,
                                            window.css_error_reporter());
 
         let im_attribute = element.get_attribute(&ns!(), &local_name!("integrity"));
         let integrity_val = im_attribute.r().map(|a| a.value());
         let integrity_metadata = match integrity_val {
--- a/servo/components/script/dom/htmloptgroupelement.rs
+++ b/servo/components/script/dom/htmloptgroupelement.rs
@@ -10,30 +10,30 @@ use dom::bindings::root::DomRoot;
 use dom::document::Document;
 use dom::element::{AttributeMutation, Element};
 use dom::htmlelement::HTMLElement;
 use dom::htmloptionelement::HTMLOptionElement;
 use dom::node::Node;
 use dom::virtualmethods::VirtualMethods;
 use dom_struct::dom_struct;
 use html5ever::{LocalName, Prefix};
-use style::element_state::*;
+use style::element_state::ElementState;
 
 #[dom_struct]
 pub struct HTMLOptGroupElement {
     htmlelement: HTMLElement
 }
 
 impl HTMLOptGroupElement {
     fn new_inherited(local_name: LocalName,
                      prefix: Option<Prefix>,
                      document: &Document) -> HTMLOptGroupElement {
         HTMLOptGroupElement {
             htmlelement:
-                HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
+                HTMLElement::new_inherited_with_state(ElementState::IN_ENABLED_STATE,
                                                       local_name, prefix, document)
         }
     }
 
     #[allow(unrooted_must_root)]
     pub fn new(local_name: LocalName,
                prefix: Option<Prefix>,
                document: &Document) -> DomRoot<HTMLOptGroupElement> {
--- a/servo/components/script/dom/htmloptionelement.rs
+++ b/servo/components/script/dom/htmloptionelement.rs
@@ -20,17 +20,17 @@ use dom::htmloptgroupelement::HTMLOptGro
 use dom::htmlscriptelement::HTMLScriptElement;
 use dom::htmlselectelement::HTMLSelectElement;
 use dom::node::{Node, UnbindContext};
 use dom::text::Text;
 use dom::virtualmethods::VirtualMethods;
 use dom_struct::dom_struct;
 use html5ever::{LocalName, Prefix};
 use std::cell::Cell;
-use style::element_state::*;
+use style::element_state::ElementState;
 use style::str::{split_html_space_chars, str_join};
 
 #[dom_struct]
 pub struct HTMLOptionElement {
     htmlelement: HTMLElement,
 
     /// <https://html.spec.whatwg.org/multipage/#attr-option-selected>
     selectedness: Cell<bool>,
@@ -40,17 +40,17 @@ pub struct HTMLOptionElement {
 }
 
 impl HTMLOptionElement {
     fn new_inherited(local_name: LocalName,
                      prefix: Option<Prefix>,
                      document: &Document) -> HTMLOptionElement {
         HTMLOptionElement {
             htmlelement:
-                HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
+                HTMLElement::new_inherited_with_state(ElementState::IN_ENABLED_STATE,
                                                       local_name, prefix, document),
             selectedness: Cell::new(false),
             dirtiness: Cell::new(false),
         }
     }
 
     #[allow(unrooted_must_root)]
     pub fn new(local_name: LocalName,
--- a/servo/components/script/dom/htmlselectelement.rs
+++ b/servo/components/script/dom/htmlselectelement.rs
@@ -30,17 +30,17 @@ use dom::nodelist::NodeList;
 use dom::validation::Validatable;
 use dom::validitystate::{ValidityState, ValidationFlags};
 use dom::virtualmethods::VirtualMethods;
 use dom_struct::dom_struct;
 use html5ever::{LocalName, Prefix};
 use std::default::Default;
 use std::iter;
 use style::attr::AttrValue;
-use style::element_state::*;
+use style::element_state::ElementState;
 
 #[derive(JSTraceable, MallocSizeOf)]
 struct OptionsFilter;
 impl CollectionFilter for OptionsFilter {
     fn filter<'a>(&self, elem: &'a Element, root: &'a Node) -> bool {
         if !elem.is::<HTMLOptionElement>() {
             return false;
         }
@@ -68,17 +68,17 @@ pub struct HTMLSelectElement {
 static DEFAULT_SELECT_SIZE: u32 = 0;
 
 impl HTMLSelectElement {
     fn new_inherited(local_name: LocalName,
                      prefix: Option<Prefix>,
                      document: &Document) -> HTMLSelectElement {
         HTMLSelectElement {
             htmlelement:
-                HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
+                HTMLElement::new_inherited_with_state(ElementState::IN_ENABLED_STATE,
                                                       local_name, prefix, document),
                 options: Default::default(),
                 form_owner: Default::default(),
         }
     }
 
     #[allow(unrooted_must_root)]
     pub fn new(local_name: LocalName,
--- a/servo/components/script/dom/htmlstyleelement.rs
+++ b/servo/components/script/dom/htmlstyleelement.rs
@@ -20,17 +20,17 @@ use dom::virtualmethods::VirtualMethods;
 use dom_struct::dom_struct;
 use html5ever::{LocalName, Prefix};
 use net_traits::ReferrerPolicy;
 use servo_arc::Arc;
 use std::cell::Cell;
 use style::media_queries::parse_media_query_list;
 use style::parser::ParserContext as CssParserContext;
 use style::stylesheets::{CssRuleType, Stylesheet, Origin};
-use style_traits::PARSING_MODE_DEFAULT;
+use style_traits::ParsingMode;
 use stylesheet_loader::{StylesheetLoader, StylesheetOwner};
 
 #[dom_struct]
 pub struct HTMLStyleElement {
     htmlelement: HTMLElement,
     #[ignore_malloc_size_of = "Arc"]
     stylesheet: DomRefCell<Option<Arc<Stylesheet>>>,
     cssom_stylesheet: MutNullableDom<CSSStyleSheet>,
@@ -82,17 +82,17 @@ impl HTMLStyleElement {
             Some(a) => String::from(&**a.value()),
             None => String::new(),
         };
 
         let data = node.GetTextContent().expect("Element.textContent must be a string");
         let url = window.get_url();
         let context = CssParserContext::new_for_cssom(&url,
                                                       Some(CssRuleType::Media),
-                                                      PARSING_MODE_DEFAULT,
+                                                      ParsingMode::DEFAULT,
                                                       doc.quirks_mode());
         let shared_lock = node.owner_doc().style_shared_lock().clone();
         let mut input = ParserInput::new(&mq_str);
         let css_error_reporter = window.css_error_reporter();
         let mq = Arc::new(shared_lock.wrap(parse_media_query_list(&context,
                                                                   &mut CssParser::new(&mut input),
                                                                   css_error_reporter)));
         let loader = StylesheetLoader::for_element(self.upcast());
--- a/servo/components/script/dom/htmltextareaelement.rs
+++ b/servo/components/script/dom/htmltextareaelement.rs
@@ -27,17 +27,17 @@ use dom::validation::Validatable;
 use dom::virtualmethods::VirtualMethods;
 use dom_struct::dom_struct;
 use html5ever::{LocalName, Prefix};
 use script_traits::ScriptToConstellationChan;
 use std::cell::Cell;
 use std::default::Default;
 use std::ops::Range;
 use style::attr::AttrValue;
-use style::element_state::*;
+use style::element_state::ElementState;
 use textinput::{KeyReaction, Lines, SelectionDirection, TextInput};
 
 #[dom_struct]
 pub struct HTMLTextAreaElement {
     htmlelement: HTMLElement,
     #[ignore_malloc_size_of = "#7193"]
     textinput: DomRefCell<TextInput<ScriptToConstellationChan>>,
     placeholder: DomRefCell<DOMString>,
@@ -106,17 +106,18 @@ static DEFAULT_ROWS: u32 = 2;
 
 impl HTMLTextAreaElement {
     fn new_inherited(local_name: LocalName,
                      prefix: Option<Prefix>,
                      document: &Document) -> HTMLTextAreaElement {
         let chan = document.window().upcast::<GlobalScope>().script_to_constellation_chan().clone();
         HTMLTextAreaElement {
             htmlelement:
-                HTMLElement::new_inherited_with_state(IN_ENABLED_STATE | IN_READ_WRITE_STATE,
+                HTMLElement::new_inherited_with_state(ElementState::IN_ENABLED_STATE |
+                                                      ElementState::IN_READ_WRITE_STATE,
                                                       local_name, prefix, document),
             placeholder: DomRefCell::new(DOMString::new()),
             textinput: DomRefCell::new(TextInput::new(
                     Lines::Multiple, DOMString::new(), chan, None, None, SelectionDirection::None)),
             value_changed: Cell::new(false),
             form_owner: Default::default(),
         }
     }
--- a/servo/components/script/dom/keyboardevent.rs
+++ b/servo/components/script/dom/keyboardevent.rs
@@ -10,17 +10,16 @@ use dom::bindings::error::Fallible;
 use dom::bindings::inheritance::Castable;
 use dom::bindings::reflector::reflect_dom_object;
 use dom::bindings::root::{DomRoot, RootedReference};
 use dom::bindings::str::DOMString;
 use dom::event::Event;
 use dom::uievent::UIEvent;
 use dom::window::Window;
 use dom_struct::dom_struct;
-use msg::constellation_msg;
 use msg::constellation_msg::{Key, KeyModifiers};
 use std::borrow::Cow;
 use std::cell::Cell;
 
 unsafe_no_jsmanaged_fields!(Key);
 
 #[dom_struct]
 pub struct KeyboardEvent {
@@ -139,38 +138,38 @@ impl KeyboardEvent {
 
     pub fn get_key(&self) -> Option<Key> {
         self.key.get().clone()
     }
 
     pub fn get_key_modifiers(&self) -> KeyModifiers {
         let mut result = KeyModifiers::empty();
         if self.shift.get() {
-            result = result | constellation_msg::SHIFT;
+            result = result | KeyModifiers::SHIFT;
         }
         if self.ctrl.get() {
-            result = result | constellation_msg::CONTROL;
+            result = result | KeyModifiers::CONTROL;
         }
         if self.alt.get() {
-            result = result | constellation_msg::ALT;
+            result = result | KeyModifiers::ALT;
         }
         if self.meta.get() {
-            result = result | constellation_msg::SUPER;
+            result = result | KeyModifiers::SUPER;
         }
         result
     }
 }
 
 // https://w3c.github.io/uievents-key/#key-value-tables
 pub fn key_value(ch: Option<char>, key: Key, mods: KeyModifiers) -> Cow<'static, str> {
     if let Some(ch) = ch {
         return Cow::from(format!("{}", ch));
     }
 
-    let shift = mods.contains(constellation_msg::SHIFT);
+    let shift = mods.contains(KeyModifiers::SHIFT);
     Cow::from(match key {
         Key::Space => " ",
         Key::Apostrophe if shift => "\"",
         Key::Apostrophe => "'",
         Key::Comma if shift => "<",
         Key::Comma => ",",
         Key::Minus if shift => "_",
         Key::Minus => "-",
--- a/servo/components/script/dom/medialist.rs
+++ b/servo/components/script/dom/medialist.rs
@@ -13,17 +13,17 @@ use dom::cssstylesheet::CSSStyleSheet;
 use dom::window::Window;
 use dom_struct::dom_struct;
 use servo_arc::Arc;
 use style::media_queries::{MediaQuery, parse_media_query_list};
 use style::media_queries::MediaList as StyleMediaList;
 use style::parser::ParserContext;
 use style::shared_lock::{SharedRwLock, Locked};
 use style::stylesheets::CssRuleType;
-use style_traits::{PARSING_MODE_DEFAULT, ToCss};
+use style_traits::{ParsingMode, ToCss};
 
 #[dom_struct]
 pub struct MediaList {
     reflector_: Reflector,
     parent_stylesheet: Dom<CSSStyleSheet>,
     #[ignore_malloc_size_of = "Arc"]
     media_queries: Arc<Locked<StyleMediaList>>,
 }
@@ -73,17 +73,17 @@ impl MediaListMethods for MediaList {
         // Step 3
         let mut input = ParserInput::new(&value);
         let mut parser = Parser::new(&mut input);
         let global = self.global();
         let window = global.as_window();
         let url = window.get_url();
         let quirks_mode = window.Document().quirks_mode();
         let context = ParserContext::new_for_cssom(&url, Some(CssRuleType::Media),
-                                                   PARSING_MODE_DEFAULT,
+                                                   ParsingMode::DEFAULT,
                                                    quirks_mode);
         *media_queries = parse_media_query_list(&context, &mut parser,
                                                 window.css_error_reporter());
     }
 
     // https://drafts.csswg.org/cssom/#dom-medialist-length
     fn Length(&self) -> u32 {
         let guard = self.shared_lock().read();
@@ -111,17 +111,17 @@ impl MediaListMethods for MediaList {
         // Step 1
         let mut input = ParserInput::new(&medium);
         let mut parser = Parser::new(&mut input);
         let global = self.global();
         let win = global.as_window();
         let url = win.get_url();
         let quirks_mode = win.Document().quirks_mode();
         let context = ParserContext::new_for_cssom(&url, Some(CssRuleType::Media),
-                                                   PARSING_MODE_DEFAULT,
+                                                   ParsingMode::DEFAULT,
                                                    quirks_mode);
         let m = MediaQuery::parse(&context, &mut parser);
         // Step 2
         if let Err(_) = m {
             return;
         }
         // Step 3
         let m_serialized = m.clone().unwrap().to_css_string();
@@ -140,17 +140,17 @@ impl MediaListMethods for MediaList {
         // Step 1
         let mut input = ParserInput::new(&medium);
         let mut parser = Parser::new(&mut input);
         let global = self.global();
         let win = global.as_window();
         let url = win.get_url();
         let quirks_mode = win.Document().quirks_mode();
         let context = ParserContext::new_for_cssom(&url, Some(CssRuleType::Media),
-                                                   PARSING_MODE_DEFAULT,
+                                                   ParsingMode::DEFAULT,
                                                    quirks_mode);
         let m = MediaQuery::parse(&context, &mut parser);
         // Step 2
         if let Err(_) = m {
             return;
         }
         // Step 3
         let m_serialized = m.unwrap().to_css_string();
--- a/servo/components/script/dom/node.rs
+++ b/servo/components/script/dom/node.rs
@@ -143,49 +143,49 @@ pub struct Node {
     mutation_observers: DomRefCell<Vec<RegisteredObserver>>,
 
     unique_id: UniqueId,
 }
 
 bitflags! {
     #[doc = "Flags for node items."]
     #[derive(JSTraceable, MallocSizeOf)]
-    pub flags NodeFlags: u16 {
+    pub struct NodeFlags: u16 {
         #[doc = "Specifies whether this node is in a document."]
-        const IS_IN_DOC = 1 << 0,
+        const IS_IN_DOC = 1 << 0;
 
         #[doc = "Specifies whether this node needs style recalc on next reflow."]
-        const HAS_DIRTY_DESCENDANTS = 1 << 1,
+        const HAS_DIRTY_DESCENDANTS = 1 << 1;
         // TODO: find a better place to keep this (#4105)
         // https://critic.hoppipolla.co.uk/showcomment?chain=8873
         // Perhaps using a Set in Document?
         #[doc = "Specifies whether or not there is an authentic click in progress on \
                  this element."]
-        const CLICK_IN_PROGRESS = 1 << 2,
+        const CLICK_IN_PROGRESS = 1 << 2;
         #[doc = "Specifies whether this node is focusable and whether it is supposed \
                  to be reachable with using sequential focus navigation."]
-        const SEQUENTIALLY_FOCUSABLE = 1 << 3,
+        const SEQUENTIALLY_FOCUSABLE = 1 << 3;
 
         /// Whether any ancestor is a fragmentation container
-        const CAN_BE_FRAGMENTED = 1 << 4,
+        const CAN_BE_FRAGMENTED = 1 << 4;
 
         // There's a free bit here.
 
         #[doc = "Specifies whether the parser has set an associated form owner for \
                  this element. Only applicable for form-associatable elements."]
-        const PARSER_ASSOCIATED_FORM_OWNER = 1 << 6,
+        const PARSER_ASSOCIATED_FORM_OWNER = 1 << 6;
 
         /// Whether this element has a snapshot stored due to a style or
         /// attribute change.
         ///
         /// See the `style::restyle_hints` module.
-        const HAS_SNAPSHOT = 1 << 7,
+        const HAS_SNAPSHOT = 1 << 7;
 
         /// Whether this element has already handled the stored snapshot.
-        const HANDLED_SNAPSHOT = 1 << 8,
+        const HANDLED_SNAPSHOT = 1 << 8;
     }
 }
 
 impl NodeFlags {
     pub fn new() -> NodeFlags {
         NodeFlags::empty()
     }
 }
@@ -256,19 +256,19 @@ impl Node {
             },
         }
 
         new_child.parent_node.set(Some(self));
         self.children_count.set(self.children_count.get() + 1);
 
         let parent_in_doc = self.is_in_doc();
         for node in new_child.traverse_preorder() {
-            node.set_flag(IS_IN_DOC, parent_in_doc);
+            node.set_flag(NodeFlags::IS_IN_DOC, parent_in_doc);
             // Out-of-document elements never have the descendants flag set.
-            debug_assert!(!node.get_flag(HAS_DIRTY_DESCENDANTS));
+            debug_assert!(!node.get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS));
             vtable_for(&&*node).bind_to_tree(parent_in_doc);
         }
         let document = new_child.owner_doc();
         document.content_and_heritage_changed(new_child, NodeDamage::OtherNodeDamage);
     }
 
     /// Removes the given child from this node's list of children.
     ///
@@ -298,18 +298,18 @@ impl Node {
 
         child.prev_sibling.set(None);
         child.next_sibling.set(None);
         child.parent_node.set(None);
         self.children_count.set(self.children_count.get() - 1);
 
         for node in child.traverse_preorder() {
             // Out-of-document elements never have the descendants flag set.
-            node.set_flag(IS_IN_DOC | HAS_DIRTY_DESCENDANTS |
-                          HAS_SNAPSHOT | HANDLED_SNAPSHOT,
+            node.set_flag(NodeFlags::IS_IN_DOC | NodeFlags::HAS_DIRTY_DESCENDANTS |
+                          NodeFlags::HAS_SNAPSHOT | NodeFlags::HANDLED_SNAPSHOT,
                           false);
         }
         for node in child.traverse_preorder() {
             // This needs to be in its own loop, because unbind_from_tree may
             // rely on the state of IS_IN_DOC of the context node's descendants,
             // e.g. when removing a <form>.
             vtable_for(&&*node).unbind_from_tree(&context);
             node.style_and_layout_data.get().map(|d| node.dispose(d));
@@ -422,17 +422,17 @@ impl Node {
     }
 
     /// Returns a string that describes this node.
     pub fn debug_str(&self) -> String {
         format!("{:?}", self.type_id())
     }
 
     pub fn is_in_doc(&self) -> bool {
-        self.flags.get().contains(IS_IN_DOC)
+        self.flags.get().contains(NodeFlags::IS_IN_DOC)
     }
 
     /// Returns the type ID of this node.
     pub fn type_id(&self) -> NodeTypeId {
         match *self.eventtarget.type_id() {
             EventTargetTypeId::Node(type_id) => type_id,
             _ => unreachable!(),
         }
@@ -484,17 +484,17 @@ impl Node {
         } else {
             flags.remove(flag);
         }
 
         self.flags.set(flags);
     }
 
     pub fn has_dirty_descendants(&self) -> bool {
-        self.get_flag(HAS_DIRTY_DESCENDANTS)
+        self.get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS)
     }
 
     pub fn rev_version(&self) {
         // The new version counter is 1 plus the max of the node's current version counter,
         // its descendants version, and the document's version. Normally, this will just be
         // the document's version, but we do have to deal with the case where the node has moved
         // document, so may have a higher version count than its owning document.
         let doc: DomRoot<Node> = DomRoot::upcast(self.owner_doc());
@@ -1373,17 +1373,17 @@ impl Node {
     }
 
     pub fn new_inherited(doc: &Document) -> Node {
         Node::new_(NodeFlags::new(), Some(doc))
     }
 
     #[allow(unrooted_must_root)]
     pub fn new_document_node() -> Node {
-        Node::new_(NodeFlags::new() | IS_IN_DOC, None)
+        Node::new_(NodeFlags::new() | NodeFlags::IS_IN_DOC, None)
     }
 
     #[allow(unrooted_must_root)]
     fn new_(flags: NodeFlags, doc: Option<&Document>) -> Node {
         Node {
             eventtarget: EventTarget::new_inherited(),
 
             parent_node: Default::default(),
--- a/servo/components/script/dom/serviceworkerglobalscope.rs
+++ b/servo/components/script/dom/serviceworkerglobalscope.rs
@@ -27,17 +27,17 @@ use net_traits::request::{CredentialsMod
 use script_runtime::{CommonScriptMsg, ScriptChan, new_rt_and_cx, Runtime};
 use script_traits::{TimerEvent, WorkerGlobalScopeInit, ScopeThings, ServiceWorkerMsg, WorkerScriptLoadOrigin};
 use servo_config::prefs::PREFS;
 use servo_rand::random;
 use servo_url::ServoUrl;
 use std::sync::mpsc::{Receiver, RecvError, Select, Sender, channel};
 use std::thread;
 use std::time::Duration;
-use style::thread_state::{self, IN_WORKER, SCRIPT};
+use style::thread_state::{self, ThreadState};
 
 /// Messages used to control service worker event loop
 pub enum ServiceWorkerScriptMsg {
     /// Message common to all workers
     CommonWorker(WorkerScriptMsg),
     // Message to request a custom response by the service worker
     Response(CustomResponseMediator)
 }
@@ -148,17 +148,17 @@ impl ServiceWorkerGlobalScope {
         let ScopeThings { script_url,
                           init,
                           worker_load_origin,
                           .. } = scope_things;
 
         let serialized_worker_url = script_url.to_string();
         let origin = GlobalScope::current().expect("No current global object").origin().immutable().clone();
         thread::Builder::new().name(format!("ServiceWorker for {}", serialized_worker_url)).spawn(move || {
-            thread_state::initialize(SCRIPT | IN_WORKER);
+            thread_state::initialize(ThreadState::SCRIPT | ThreadState::IN_WORKER);
             let roots = RootCollection::new();
             let _stack_roots = ThreadLocalStackRoots::new(&roots);
 
             let WorkerScriptLoadOrigin { referrer_url, referrer_policy, pipeline_id } = worker_load_origin;
 
             let request = RequestInit {
                 url: script_url.clone(),
                 destination: Destination::ServiceWorker,
--- a/servo/components/script/dom/validitystate.rs
+++ b/servo/components/script/dom/validitystate.rs
@@ -23,27 +23,27 @@ pub enum ValidityStatus {
     RangeOverflow,
     StepMismatch,
     BadInput,
     CustomError,
     Valid
 }
 
 bitflags!{
-    pub flags ValidationFlags: u32 {
-        const VALUE_MISSING    = 0b0000000001,
-        const TYPE_MISMATCH    = 0b0000000010,
-        const PATTERN_MISMATCH = 0b0000000100,
-        const TOO_LONG         = 0b0000001000,
-        const TOO_SHORT        = 0b0000010000,
-        const RANGE_UNDERFLOW  = 0b0000100000,
-        const RANGE_OVERFLOW   = 0b0001000000,
-        const STEP_MISMATCH    = 0b0010000000,
-        const BAD_INPUT        = 0b0100000000,
-        const CUSTOM_ERROR     = 0b1000000000,
+    pub struct ValidationFlags: u32 {
+        const VALUE_MISSING    = 0b0000000001;
+        const TYPE_MISMATCH    = 0b0000000010;
+        const PATTERN_MISMATCH = 0b0000000100;
+        const TOO_LONG         = 0b0000001000;
+        const TOO_SHORT        = 0b0000010000;
+        const RANGE_UNDERFLOW  = 0b0000100000;
+        const RANGE_OVERFLOW   = 0b0001000000;
+        const STEP_MISMATCH    = 0b0010000000;
+        const BAD_INPUT        = 0b0100000000;
+        const CUSTOM_ERROR     = 0b1000000000;
     }
 }
 
 // https://html.spec.whatwg.org/multipage/#validitystate
 #[dom_struct]
 pub struct ValidityState {
     reflector_: Reflector,
     element: Dom<Element>,
--- a/servo/components/script/dom/webglrenderingcontext.rs
+++ b/servo/components/script/dom/webglrenderingcontext.rs
@@ -131,20 +131,20 @@ fn has_invalid_blend_constants(arg1: u32
         (constants::CONSTANT_COLOR, constants::ONE_MINUS_CONSTANT_ALPHA) => true,
         (_, _) => false
     }
 }
 
 /// Set of bitflags for texture unpacking (texImage2d, etc...)
 bitflags! {
     #[derive(JSTraceable, MallocSizeOf)]
-    flags TextureUnpacking: u8 {
-        const FLIP_Y_AXIS = 0x01,
-        const PREMULTIPLY_ALPHA = 0x02,
-        const CONVERT_COLORSPACE = 0x04,
+    struct TextureUnpacking: u8 {
+        const FLIP_Y_AXIS = 0x01;
+        const PREMULTIPLY_ALPHA = 0x02;
+        const CONVERT_COLORSPACE = 0x04;
     }
 }
 
 /// Information about the bound textures of a WebGL texture unit.
 #[must_root]
 #[derive(JSTraceable, MallocSizeOf)]
 struct TextureUnitBindings {
     bound_texture_2d: MutNullableDom<WebGLTexture>,
@@ -234,17 +234,17 @@ impl WebGLRenderingContext {
                 reflector_: Reflector::new(),
                 webgl_sender: ctx_data.sender,
                 webrender_image: Cell::new(None),
                 share_mode: ctx_data.share_mode,
                 webgl_version,
                 limits: ctx_data.limits,
                 canvas: Dom::from_ref(canvas),
                 last_error: Cell::new(None),
-                texture_unpacking_settings: Cell::new(CONVERT_COLORSPACE),
+                texture_unpacking_settings: Cell::new(TextureUnpacking::CONVERT_COLORSPACE),
                 texture_unpacking_alignment: Cell::new(4),
                 bound_framebuffer: MutNullableDom::new(None),
                 bound_textures: DomRefCell::new(Default::default()),
                 bound_texture_unit: Cell::new(constants::TEXTURE0),
                 bound_buffer_array: MutNullableDom::new(None),
                 bound_buffer_element_array: MutNullableDom::new(None),
                 bound_attrib_buffers: DomRefCell::new(Default::default()),
                 bound_renderbuffer: MutNullableDom::new(None),
@@ -882,17 +882,17 @@ impl WebGLRenderingContext {
     /// UNPACK_FLIP_Y_WEBGL is currently enabled.
     fn flip_teximage_y(&self,
                        pixels: Vec<u8>,
                        internal_format: TexFormat,
                        data_type: TexDataType,
                        width: usize,
                        height: usize,
                        unpacking_alignment: usize) -> Vec<u8> {
-        if !self.texture_unpacking_settings.get().contains(FLIP_Y_AXIS) {
+        if !self.texture_unpacking_settings.get().contains(TextureUnpacking::FLIP_Y_AXIS) {
             return pixels;
         }
 
         let cpp = (data_type.element_size() *
                    internal_format.components() / data_type.components_per_element()) as usize;
 
         let stride = (width * cpp + unpacking_alignment - 1) & !(unpacking_alignment - 1);
 
@@ -910,17 +910,17 @@ impl WebGLRenderingContext {
     }
 
     /// Performs premultiplication of the pixels if
     /// UNPACK_PREMULTIPLY_ALPHA_WEBGL is currently enabled.
     fn premultiply_pixels(&self,
                           format: TexFormat,
                           data_type: TexDataType,
                           pixels: Vec<u8>) -> Vec<u8> {
-        if !self.texture_unpacking_settings.get().contains(PREMULTIPLY_ALPHA) {
+        if !self.texture_unpacking_settings.get().contains(TextureUnpacking::PREMULTIPLY_ALPHA) {
             return pixels;
         }
 
         match (format, data_type) {
             (TexFormat::RGBA, TexDataType::UnsignedByte) => {
                 let mut premul = Vec::<u8>::with_capacity(pixels.len());
                 for rgba in pixels.chunks(4) {
                     premul.push(multiply_u8_pixel(rgba[0], rgba[3]));
@@ -994,17 +994,17 @@ impl WebGLRenderingContext {
                       internal_format: TexFormat,
                       data_type: TexDataType,
                       width: u32,
                       height: u32,
                       unpacking_alignment: u32,
                       source_premultiplied: bool,
                       source_from_image_or_canvas: bool,
                       mut pixels: Vec<u8>) -> Vec<u8> {
-        let dest_premultiply = self.texture_unpacking_settings.get().contains(PREMULTIPLY_ALPHA);
+        let dest_premultiply = self.texture_unpacking_settings.get().contains(TextureUnpacking::PREMULTIPLY_ALPHA);
         if !source_premultiplied && dest_premultiply {
             if source_from_image_or_canvas {
                 // When the pixels come from image or canvas or imagedata, use RGBA8 format
                 pixels = self.premultiply_pixels(TexFormat::RGBA, TexDataType::UnsignedByte, pixels);
             } else {
                 pixels = self.premultiply_pixels(internal_format, data_type, pixels);
             }
         } else if source_premultiplied && !dest_premultiply {
@@ -2454,40 +2454,40 @@ impl WebGLRenderingContextMethods for We
     // NOTE: Usage of this function could affect rendering while we keep using
     //   readback to render to the page.
     // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3
     fn PixelStorei(&self, param_name: u32, param_value: i32) {
         let mut texture_settings = self.texture_unpacking_settings.get();
         match param_name {
             constants::UNPACK_FLIP_Y_WEBGL => {
                if param_value != 0 {
-                    texture_settings.insert(FLIP_Y_AXIS)
+                    texture_settings.insert(TextureUnpacking::FLIP_Y_AXIS)
                 } else {
-                    texture_settings.remove(FLIP_Y_AXIS)
+                    texture_settings.remove(TextureUnpacking::FLIP_Y_AXIS)
                 }
 
                 self.texture_unpacking_settings.set(texture_settings);
                 return;
             },
             constants::UNPACK_PREMULTIPLY_ALPHA_WEBGL => {
                 if param_value != 0 {
-                    texture_settings.insert(PREMULTIPLY_ALPHA)
+                    texture_settings.insert(TextureUnpacking::PREMULTIPLY_ALPHA)
                 } else {
-                    texture_settings.remove(PREMULTIPLY_ALPHA)
+                    texture_settings.remove(TextureUnpacking::PREMULTIPLY_ALPHA)
                 }
 
                 self.texture_unpacking_settings.set(texture_settings);
                 return;
             },
             constants::UNPACK_COLORSPACE_CONVERSION_WEBGL => {
                 match param_value as u32 {
                     constants::BROWSER_DEFAULT_WEBGL
-                        => texture_settings.insert(CONVERT_COLORSPACE),
+                        => texture_settings.insert(TextureUnpacking::CONVERT_COLORSPACE),
                     constants::NONE
-                        => texture_settings.remove(CONVERT_COLORSPACE),
+                        => texture_settings.remove(TextureUnpacking::CONVERT_COLORSPACE),
                     _ => return self.webgl_error(InvalidEnum),
                 }
 
                 self.texture_unpacking_settings.set(texture_settings);
                 return;
             },
             constants::UNPACK_ALIGNMENT |
             constants::PACK_ALIGNMENT => {
--- a/servo/components/script/dom/window.rs
+++ b/servo/components/script/dom/window.rs
@@ -103,17 +103,17 @@ use std::sync::mpsc::{Sender, channel};
 use std::sync::mpsc::TryRecvError::{Disconnected, Empty};
 use style::media_queries;
 use style::parser::ParserContext as CssParserContext;
 use style::properties::PropertyId;
 use style::properties::longhands::overflow_x;
 use style::selector_parser::PseudoElement;
 use style::str::HTML_SPACE_CHARACTERS;
 use style::stylesheets::CssRuleType;
-use style_traits::PARSING_MODE_DEFAULT;
+use style_traits::ParsingMode;
 use task::TaskCanceller;
 use task_source::dom_manipulation::DOMManipulationTaskSource;
 use task_source::file_reading::FileReadingTaskSource;
 use task_source::history_traversal::HistoryTraversalTaskSource;
 use task_source::networking::NetworkingTaskSource;
 use task_source::performance_timeline::PerformanceTimelineTaskSource;
 use task_source::user_interaction::UserInteractionTaskSource;
 use time;
@@ -1007,17 +1007,17 @@ impl WindowMethods for Window {
 
     // https://drafts.csswg.org/cssom-view/#dom-window-matchmedia
     fn MatchMedia(&self, query: DOMString) -> DomRoot<MediaQueryList> {
         let mut input = ParserInput::new(&query);
         let mut parser = Parser::new(&mut input);
         let url = self.get_url();
         let quirks_mode = self.Document().quirks_mode();
         let context = CssParserContext::new_for_cssom(&url, Some(CssRuleType::Media),
-                                                      PARSING_MODE_DEFAULT,
+                                                      ParsingMode::DEFAULT,
                                                       quirks_mode);
         let media_query_list = media_queries::parse_media_query_list(&context, &mut parser,
                                                                      self.css_error_reporter());
         let document = self.Document();
         let mql = MediaQueryList::new(&document, media_query_list);
         self.media_query_lists.push(&*mql);
         mql
     }
--- a/servo/components/script/dom/worklet.rs
+++ b/servo/components/script/dom/worklet.rs
@@ -57,17 +57,17 @@ use std::collections::hash_map;
 use std::rc::Rc;
 use std::sync::Arc;
 use std::sync::atomic::AtomicIsize;
 use std::sync::atomic::Ordering;
 use std::sync::mpsc;
 use std::sync::mpsc::Receiver;
 use std::sync::mpsc::Sender;
 use std::thread;
-use style::thread_state;
+use style::thread_state::{self, ThreadState};
 use swapper::Swapper;
 use swapper::swapper;
 use task::TaskBox;
 use uuid::Uuid;
 
 // Magic numbers
 const WORKLET_THREAD_POOL_SIZE: u32 = 3;
 const MIN_GC_THRESHOLD: u32 = 1_000_000;
@@ -420,17 +420,17 @@ impl WorkletThread {
     fn spawn(role: WorkletThreadRole, init: WorkletThreadInit) -> Sender<WorkletControl> {
         let (control_sender, control_receiver) = mpsc::channel();
         // TODO: name this thread
         thread::spawn(move || {
             // TODO: add a new IN_WORKLET thread state?
             // TODO: set interrupt handler?
             // TODO: configure the JS runtime (e.g. discourage GC, encourage agressive JIT)
             debug!("Initializing worklet thread.");
-            thread_state::initialize(thread_state::SCRIPT | thread_state::IN_WORKER);
+            thread_state::initialize(ThreadState::SCRIPT | ThreadState::IN_WORKER);
             let roots = RootCollection::new();
             let _stack_roots = ThreadLocalStackRoots::new(&roots);
             let mut thread = RootedTraceableBox::new(WorkletThread {
                 role: role,
                 control_receiver: control_receiver,
                 primary_sender: init.primary_sender,
                 hot_backup_sender: init.hot_backup_sender,
                 cold_backup_sender: init.cold_backup_sender,
--- a/servo/components/script/lib.rs
+++ b/servo/components/script/lib.rs
@@ -135,18 +135,17 @@ mod webdriver_handlers;
 /// TODO(emilio): A few of the FooHelpers can go away, presumably...
 pub mod layout_exports {
     pub use dom::bindings::inheritance::{CharacterDataTypeId, ElementTypeId};
     pub use dom::bindings::inheritance::{HTMLElementTypeId, NodeTypeId};
     pub use dom::bindings::root::LayoutDom;
     pub use dom::characterdata::LayoutCharacterDataHelpers;
     pub use dom::document::{Document, LayoutDocumentHelpers, PendingRestyle};
     pub use dom::element::{Element, LayoutElementHelpers, RawLayoutElementHelpers};
-    pub use dom::node::{CAN_BE_FRAGMENTED, HAS_DIRTY_DESCENDANTS, IS_IN_DOC};
-    pub use dom::node::{HANDLED_SNAPSHOT, HAS_SNAPSHOT};
+    pub use dom::node::NodeFlags;
     pub use dom::node::{LayoutNodeHelpers, Node};
     pub use dom::text::Text;
 }
 
 use dom::bindings::codegen::RegisterBindings;
 use dom::bindings::proxyhandler;
 use script_traits::SWManagerSenders;
 use serviceworker_manager::ServiceWorkerManager;
--- a/servo/components/script/script_runtime.rs
+++ b/servo/components/script/script_runtime.rs
@@ -30,17 +30,17 @@ use servo_config::prefs::PREFS;
 use std::cell::Cell;
 use std::fmt;
 use std::io::{Write, stdout};
 use std::ops::Deref;
 use std::os;
 use std::os::raw::c_void;
 use std::panic::AssertUnwindSafe;
 use std::ptr;
-use style::thread_state;
+use style::thread_state::{self, ThreadState};
 use task::TaskBox;
 use time::{Tm, now};
 
 /// Common messages used to control the event loops in both the script and the worker
 pub enum CommonScriptMsg {
     /// Requests that the script thread measure its memory usage. The results are sent back via the
     /// supplied channel.
     CollectReports(ReportsChan),
@@ -406,18 +406,18 @@ unsafe extern "C" fn gc_slice_callback(_
         println!("  isCompartment={}, invocation_kind={}", desc.isCompartment_, invocation_kind);
     }
     let _ = stdout().flush();
 }
 
 #[allow(unsafe_code)]
 unsafe extern "C" fn debug_gc_callback(_rt: *mut JSRuntime, status: JSGCStatus, _data: *mut os::raw::c_void) {
     match status {
-        JSGCStatus::JSGC_BEGIN => thread_state::enter(thread_state::IN_GC),
-        JSGCStatus::JSGC_END   => thread_state::exit(thread_state::IN_GC),
+        JSGCStatus::JSGC_BEGIN => thread_state::enter(ThreadState::IN_GC),
+        JSGCStatus::JSGC_END   => thread_state::exit(ThreadState::IN_GC),
     }
 }
 
 thread_local!(
     static THREAD_ACTIVE: Cell<bool> = Cell::new(true);
 );
 
 #[allow(unsafe_code)]
--- a/servo/components/script/script_thread.rs
+++ b/servo/components/script/script_thread.rs
@@ -108,17 +108,17 @@ use std::default::Default;
 use std::ops::Deref;
 use std::option::Option;
 use std::ptr;
 use std::rc::Rc;
 use std::result::Result;
 use std::sync::Arc;
 use std::sync::mpsc::{Receiver, Select, Sender, channel};
 use std::thread;
-use style::thread_state;
+use style::thread_state::{self, ThreadState};
 use task_source::dom_manipulation::DOMManipulationTaskSource;
 use task_source::file_reading::FileReadingTaskSource;
 use task_source::history_traversal::HistoryTraversalTaskSource;
 use task_source::networking::NetworkingTaskSource;
 use task_source::performance_timeline::PerformanceTimelineTaskSource;
 use task_source::user_interaction::UserInteractionTaskSource;
 use time::{get_time, precise_time_ns, Tm};
 use url::Position;
@@ -542,17 +542,17 @@ impl ScriptThreadFactory for ScriptThrea
     fn create(state: InitialScriptState,
               load_data: LoadData)
               -> (Sender<message::Msg>, Receiver<message::Msg>) {
         let (script_chan, script_port) = channel();
 
         let (sender, receiver) = channel();
         let layout_chan = sender.clone();
         thread::Builder::new().name(format!("ScriptThread {:?}", state.id)).spawn(move || {
-            thread_state::initialize(thread_state::SCRIPT);
+            thread_state::initialize(ThreadState::SCRIPT);
             PipelineNamespace::install(state.pipeline_namespace_id);
             TopLevelBrowsingContextId::install(state.top_level_browsing_context_id);
             let roots = RootCollection::new();
             let _stack_roots = ThreadLocalStackRoots::new(&roots);
             let id = state.id;
             let browsing_context_id = state.browsing_context_id;
             let top_level_browsing_context_id = state.top_level_browsing_context_id;
             let parent_info = state.parent_info;
--- a/servo/components/script/textinput.rs
+++ b/servo/components/script/textinput.rs
@@ -2,17 +2,16 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 //! Common handling of keyboard input and state management for text input controls
 
 use clipboard_provider::ClipboardProvider;
 use dom::bindings::str::DOMString;
 use dom::keyboardevent::KeyboardEvent;
-use msg::constellation_msg::{ALT, CONTROL, SHIFT, SUPER};
 use msg::constellation_msg::{Key, KeyModifiers};
 use std::borrow::ToOwned;
 use std::cmp::{max, min};
 use std::default::Default;
 use std::ops::Range;
 use std::usize;
 use unicode_segmentation::UnicodeSegmentation;
 
@@ -109,22 +108,22 @@ pub enum Direction {
     Backward
 }
 
 
 /// Was the keyboard event accompanied by the standard control modifier,
 /// i.e. cmd on Mac OS or ctrl on other platforms.
 #[cfg(target_os = "macos")]
 fn is_control_key(mods: KeyModifiers) -> bool {
-    mods.contains(SUPER) && !mods.contains(CONTROL | ALT)
+    mods.contains(KeyModifiers::SUPER) && !mods.contains(KeyModifiers::CONTROL | KeyModifiers::ALT)
 }
 
 #[cfg(not(target_os = "macos"))]
 fn is_control_key(mods: KeyModifiers) -> bool {
-    mods.contains(CONTROL) && !mods.contains(SUPER | ALT)
+    mods.contains(KeyModifiers::CONTROL) && !mods.contains(KeyModifiers::SUPER | KeyModifiers::ALT)
 }
 
 /// The length in bytes of the first n characters in a UTF-8 string.
 ///
 /// If the string has fewer than n characters, returns the length of the whole string.
 fn len_of_first_n_chars(text: &str, n: usize) -> usize {
     match text.char_indices().take(n).last() {
         Some((index, ch)) => index + ch.len_utf8(),
@@ -580,41 +579,46 @@ impl<T: ClipboardProvider> TextInput<T> 
             KeyReaction::Nothing
         }
     }
 
     pub fn handle_keydown_aux(&mut self,
                               printable: Option<char>,
                               key: Key,
                               mods: KeyModifiers) -> KeyReaction {
-        let maybe_select = if mods.contains(SHIFT) { Selection::Selected } else { Selection::NotSelected };
+        let maybe_select = if mods.contains(KeyModifiers::SHIFT) {
+                Selection::Selected
+            } else {
+                Selection::NotSelected
+        };
+
         match (printable, key) {
-            (_, Key::B) if mods.contains(CONTROL | ALT) => {
+            (_, Key::B) if mods.contains(KeyModifiers::CONTROL | KeyModifiers::ALT) => {
                 self.adjust_horizontal_by_word(Direction::Backward, maybe_select);
                 KeyReaction::RedrawSelection
             },
-            (_, Key::F) if mods.contains(CONTROL | ALT) => {
+            (_, Key::F) if mods.contains(KeyModifiers::CONTROL | KeyModifiers::ALT) => {
                 self.adjust_horizontal_by_word(Direction::Forward, maybe_select);
                 KeyReaction::RedrawSelection
             },
-            (_, Key::A) if mods.contains(CONTROL | ALT) => {
+            (_, Key::A) if mods.contains(KeyModifiers::CONTROL | KeyModifiers::ALT) => {
                 self.adjust_horizontal_to_line_end(Direction::Backward, maybe_select);
                 KeyReaction::RedrawSelection
             },
-            (_, Key::E) if mods.contains(CONTROL | ALT) => {
+            (_, Key::E) if mods.contains(KeyModifiers::CONTROL | KeyModifiers::ALT) => {
                 self.adjust_horizontal_to_line_end(Direction::Forward, maybe_select);
                 KeyReaction::RedrawSelection
             },
             #[cfg(target_os = "macos")]
-            (None, Key::A) if mods == CONTROL => {
+            (None, Key::A) if mods == KeyModifiers::CONTROL => {
                 self.adjust_horizontal_to_line_end(Direction::Backward, maybe_select);
                 KeyReaction::RedrawSelection
             },
             #[cfg(target_os = "macos")]
-            (None, Key::E) if mods == CONTROL => {
+            (None, Key::E) if mods == KeyModifiers::CONTROL => {
                 self.adjust_horizontal_to_line_end(Direction::Forward, maybe_select);
                 KeyReaction::RedrawSelection
             },
             (_, Key::A) if is_control_key(mods) => {
                 self.select_all();
                 KeyReaction::RedrawSelection
             },
             (_, Key::C) if is_control_key(mods) => {
@@ -636,40 +640,40 @@ impl<T: ClipboardProvider> TextInput<T> 
                 self.delete_char(Direction::Forward);
                 KeyReaction::DispatchInput
             },
             (None, Key::Backspace) => {
                 self.delete_char(Direction::Backward);
                 KeyReaction::DispatchInput
             },
             #[cfg(target_os = "macos")]
-            (None, Key::Left) if mods.contains(SUPER) => {
+            (None, Key::Left) if mods.contains(KeyModifiers::SUPER) => {
                 self.adjust_horizontal_to_line_end(Direction::Backward, maybe_select);
                 KeyReaction::RedrawSelection
             },
             #[cfg(target_os = "macos")]
-            (None, Key::Right) if mods.contains(SUPER) => {
+            (None, Key::Right) if mods.contains(KeyModifiers::SUPER) => {
                 self.adjust_horizontal_to_line_end(Direction::Forward, maybe_select);
                 KeyReaction::RedrawSelection
             },
             #[cfg(target_os = "macos")]
-            (None, Key::Up) if mods.contains(SUPER) => {
+            (None, Key::Up) if mods.contains(KeyModifiers::SUPER) => {
                 self.adjust_horizontal_to_limit(Direction::Backward, maybe_select);
                 KeyReaction::RedrawSelection
             },
             #[cfg(target_os = "macos")]
-            (None, Key::Down) if mods.contains(SUPER) => {
+            (None, Key::Down) if mods.contains(KeyModifiers::SUPER) => {
                 self.adjust_horizontal_to_limit(Direction::Forward, maybe_select);
                 KeyReaction::RedrawSelection
             },
-            (None, Key::Left) if mods.contains(ALT) => {
+            (None, Key::Left) if mods.contains(KeyModifiers::ALT) => {
                 self.adjust_horizontal_by_word(Direction::Backward, maybe_select);
                 KeyReaction::RedrawSelection
             },
-            (None, Key::Right) if mods.contains(ALT) => {
+            (None, Key::Right) if mods.contains(KeyModifiers::ALT) => {
                 self.adjust_horizontal_by_word(Direction::Forward, maybe_select);
                 KeyReaction::RedrawSelection
             },
             (None, Key::Left) => {
                 self.adjust_horizontal_by_one(Direction::Backward, maybe_select);
                 KeyReaction::RedrawSelection
             },
             (None, Key::Right) => {
--- a/servo/components/selectors/Cargo.toml
+++ b/servo/components/selectors/Cargo.toml
@@ -18,17 +18,17 @@ path = "lib.rs"
 # https://github.com/servo/servo/issues/16710
 doctest = false
 
 [features]
 gecko_like_types = []
 bench = []
 
 [dependencies]
-bitflags = "0.7"
+bitflags = "1.0"
 matches = "0.1"
 cssparser = "0.22.0"
 log = "0.3"
 fnv = "1.0"
 malloc_size_of = { path = "../malloc_size_of" }
 malloc_size_of_derive = { path = "../malloc_size_of_derive" }
 phf = "0.7.18"
 precomputed-hash = "0.1"
--- a/servo/components/selectors/matching.rs
+++ b/servo/components/selectors/matching.rs
@@ -15,47 +15,49 @@ pub use context::*;
 // The bloom filter for descendant CSS selectors will have a <1% false
 // positive rate until it has this many selectors in it, then it will
 // rapidly increase.
 pub static RECOMMENDED_SELECTOR_BLOOM_FILTER_SIZE: usize = 4096;
 
 bitflags! {
     /// Set of flags that are set on either the element or its parent (depending
     /// on the flag) if the element could potentially match a selector.
-    pub flags ElementSelectorFlags: usize {
+    pub struct ElementSelectorFlags: usize {
         /// When a child is added or removed from the parent, all the children
         /// must be restyled, because they may match :nth-last-child,
         /// :last-of-type, :nth-last-of-type, or :only-of-type.
-        const HAS_SLOW_SELECTOR = 1 << 0,
+        const HAS_SLOW_SELECTOR = 1 << 0;
 
         /// When a child is added or removed from the parent, any later
         /// children must be restyled, because they may match :nth-child,
         /// :first-of-type, or :nth-of-type.
-        const HAS_SLOW_SELECTOR_LATER_SIBLINGS = 1 << 1,
+        const HAS_SLOW_SELECTOR_LATER_SIBLINGS = 1 << 1;
 
         /// When a child is added or removed from the parent, the first and
         /// last children must be restyled, because they may match :first-child,
         /// :last-child, or :only-child.
-        const HAS_EDGE_CHILD_SELECTOR = 1 << 2,
+        const HAS_EDGE_CHILD_SELECTOR = 1 << 2;
 
         /// The element has an empty selector, so when a child is appended we
         /// might need to restyle the parent completely.
-        const HAS_EMPTY_SELECTOR = 1 << 3,
+        const HAS_EMPTY_SELECTOR = 1 << 3;
     }
 }
 
 impl ElementSelectorFlags {
     /// Returns the subset of flags that apply to the element.
     pub fn for_self(self) -> ElementSelectorFlags {
-        self & (HAS_EMPTY_SELECTOR)
+        self & (ElementSelectorFlags::HAS_EMPTY_SELECTOR)
     }
 
     /// Returns the subset of flags that apply to the parent.
     pub fn for_parent(self) -> ElementSelectorFlags {
-        self & (HAS_SLOW_SELECTOR | HAS_SLOW_SELECTOR_LATER_SIBLINGS | HAS_EDGE_CHILD_SELECTOR)
+        self & (ElementSelectorFlags::HAS_SLOW_SELECTOR |
+                ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS |
+                ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR)
     }
 }
 
 /// Holds per-compound-selector data.
 struct LocalMatchingContext<'a, 'b: 'a, Impl: SelectorImpl> {
     shared: &'a mut MatchingContext<'b, Impl>,
     matches_hover_and_active_quirk: bool,
 }
@@ -546,17 +548,17 @@ where
                 &relevant_link,
                 flags_setter,
             )
         })
     };
 
     let combinator = selector_iter.next_sequence();
     if combinator.map_or(false, |c| c.is_sibling()) {
-        flags_setter(element, HAS_SLOW_SELECTOR_LATER_SIBLINGS);
+        flags_setter(element, ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS);
     }
 
     if !matches_all_simple_selectors {
         return SelectorMatchingResult::NotMatchedAndRestartFromClosestLaterSibling;
     }
 
     let combinator = match combinator {
         None => return SelectorMatchingResult::Matched,
@@ -743,17 +745,17 @@ where
         Component::OnlyChild => {
             matches_first_child(element, flags_setter) &&
             matches_last_child(element, flags_setter)
         }
         Component::Root => {
             element.is_root()
         }
         Component::Empty => {
-            flags_setter(element, HAS_EMPTY_SELECTOR);
+            flags_setter(element, ElementSelectorFlags::HAS_EMPTY_SELECTOR);
             element.is_empty()
         }
         Component::Scope => {
             match context.shared.scope_element {
                 Some(ref scope_element) => element.opaque() == *scope_element,
                 None => element.is_root(),
             }
         }
@@ -818,19 +820,19 @@ where
     E: Element,
     F: FnMut(&E, ElementSelectorFlags),
 {
     if element.ignores_nth_child_selectors() {
         return false;
     }
 
     flags_setter(element, if is_from_end {
-        HAS_SLOW_SELECTOR
+        ElementSelectorFlags::HAS_SLOW_SELECTOR
     } else {
-        HAS_SLOW_SELECTOR_LATER_SIBLINGS
+        ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS
     });
 
     // Grab a reference to the appropriate cache.
     let mut cache = context.shared.nth_index_cache.as_mut().map(|c| {
         c.get(is_of_type, is_from_end)
     });
 
     // Lookup or compute the index.
@@ -913,21 +915,21 @@ where
 }
 
 #[inline]
 fn matches_first_child<E, F>(element: &E, flags_setter: &mut F) -> bool
 where
     E: Element,
     F: FnMut(&E, ElementSelectorFlags),
 {
-    flags_setter(element, HAS_EDGE_CHILD_SELECTOR);
+    flags_setter(element, ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR);
     element.prev_sibling_element().is_none()
 }
 
 #[inline]
 fn matches_last_child<E, F>(element: &E, flags_setter: &mut F) -> bool
 where
     E: Element,
     F: FnMut(&E, ElementSelectorFlags),
 {
-    flags_setter(element, HAS_EDGE_CHILD_SELECTOR);
+    flags_setter(element, ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR);
     element.next_sibling_element().is_none()
 }
--- a/servo/components/style/Cargo.toml
+++ b/servo/components/style/Cargo.toml
@@ -27,17 +27,17 @@ servo = ["serde", "style_traits/servo", 
 
          "servo_url"]
 gecko_debug = ["nsstring/gecko_debug"]
 
 [dependencies]
 app_units = "0.5.5"
 arrayvec = "0.3.20"
 atomic_refcell = "0.1"
-bitflags = "0.7"
+bitflags = "1.0"
 byteorder = "1.0"
 cfg-if = "0.1.0"
 cssparser = "0.22.0"
 encoding = {version = "0.2", optional = true}
 euclid = "0.15"
 fallible = { path = "../fallible" }
 fnv = "1.0"
 hashglobe = { path = "../hashglobe" }
--- a/servo/components/style/context.rs
+++ b/servo/components/style/context.rs
@@ -32,17 +32,17 @@ use sharing::StyleSharingCache;
 use std::fmt;
 use std::ops;
 #[cfg(feature = "servo")] use std::sync::Mutex;
 #[cfg(feature = "servo")] use std::sync::mpsc::Sender;
 use style_traits::CSSPixel;
 use style_traits::DevicePixel;
 #[cfg(feature = "servo")] use style_traits::SpeculativePainter;
 use stylist::Stylist;
-use thread_state;
+use thread_state::{self, ThreadState};
 use time;
 use timer::Timer;
 use traversal::DomTraversal;
 use traversal_flags::TraversalFlags;
 
 pub use selectors::matching::QuirksMode;
 
 /// This structure is used to create a local style context from a shared one.
@@ -416,37 +416,37 @@ impl TraversalStatistics {
         self.is_large.unwrap()
     }
 }
 
 #[cfg(feature = "gecko")]
 bitflags! {
     /// Represents which tasks are performed in a SequentialTask of
     /// UpdateAnimations which is a result of normal restyle.
-    pub flags UpdateAnimationsTasks: u8 {
+    pub struct UpdateAnimationsTasks: u8 {
         /// Update CSS Animations.
-        const CSS_ANIMATIONS = structs::UpdateAnimationsTasks_CSSAnimations,
+        const CSS_ANIMATIONS = structs::UpdateAnimationsTasks_CSSAnimations;
         /// Update CSS Transitions.
-        const CSS_TRANSITIONS = structs::UpdateAnimationsTasks_CSSTransitions,
+        const CSS_TRANSITIONS = structs::UpdateAnimationsTasks_CSSTransitions;
         /// Update effect properties.
-        const EFFECT_PROPERTIES = structs::UpdateAnimationsTasks_EffectProperties,
+        const EFFECT_PROPERTIES = structs::UpdateAnimationsTasks_EffectProperties;
         /// Update animation cacade results for animations running on the compositor.
-        const CASCADE_RESULTS = structs::UpdateAnimationsTasks_CascadeResults,
+        const CASCADE_RESULTS = structs::UpdateAnimationsTasks_CascadeResults;
     }
 }
 
 #[cfg(feature = "gecko")]
 bitflags! {
     /// Represents which tasks are performed in a SequentialTask as a result of
     /// animation-only restyle.
-    pub flags PostAnimationTasks: u8 {
+    pub struct PostAnimationTasks: u8 {
         /// Display property was changed from none in animation-only restyle so
         /// that we need to resolve styles for descendants in a subsequent
         /// normal restyle.
-        const DISPLAY_CHANGED_FROM_NONE_FOR_SMIL = 0x01,
+        const DISPLAY_CHANGED_FROM_NONE_FOR_SMIL = 0x01;
     }
 }
 
 
 /// A task to be run in sequential mode on the parent (non-worker) thread. This
 /// is used by the style system to queue up work which is not safe to do during
 /// the parallel traversal.
 pub enum SequentialTask<E: TElement> {
@@ -478,17 +478,17 @@ pub enum SequentialTask<E: TElement> {
         tasks: PostAnimationTasks
     },
 }
 
 impl<E: TElement> SequentialTask<E> {
     /// Executes this task.
     pub fn execute(self) {
         use self::SequentialTask::*;
-        debug_assert!(thread_state::get() == thread_state::LAYOUT);
+        debug_assert!(thread_state::get() == ThreadState::LAYOUT);
         match self {
             Unused(_) => unreachable!(),
             #[cfg(feature = "gecko")]
             UpdateAnimations { el, before_change_style, tasks } => {
                 unsafe { el.update_animations(before_change_style, tasks) };
             }
             #[cfg(feature = "gecko")]
             PostAnimation { el, tasks } => {
@@ -566,17 +566,17 @@ impl<E: TElement> SelectorFlagsMap<E> {
 
         // Insert into the cache. We don't worry about duplicate entries,
         // which lets us avoid reshuffling.
         self.cache.insert((unsafe { SendElement::new(element) }, *f))
     }
 
     /// Applies the flags. Must be called on the main thread.
     pub fn apply_flags(&mut self) {
-        debug_assert!(thread_state::get() == thread_state::LAYOUT);
+        debug_assert!(thread_state::get() == ThreadState::LAYOUT);
         for (el, flags) in self.map.drain() {
             unsafe { el.set_selector_flags(flags); }
         }
     }
 }
 
 /// A list of SequentialTasks that get executed on Drop.
 pub struct SequentialTaskList<E>(Vec<SequentialTask<E>>)
@@ -603,17 +603,17 @@ where
     }
 }
 
 impl<E> Drop for SequentialTaskList<E>
 where
     E: TElement,
 {
     fn drop(&mut self) {
-        debug_assert!(thread_state::get() == thread_state::LAYOUT);
+        debug_assert!(thread_state::get() == ThreadState::LAYOUT);
         for task in self.0.drain(..) {
             task.execute()
         }
     }
 }
 
 
 /// A helper type for stack limit checking.  This assumes that stacks grow
@@ -798,17 +798,17 @@ impl<E: TElement> ThreadLocalStyleContex
     pub fn is_initial_style(&self) -> bool {
         self.current_element_info.as_ref().unwrap().is_initial_style
     }
 }
 
 impl<E: TElement> Drop for ThreadLocalStyleContext<E> {
     fn drop(&mut self) {
         debug_assert!(self.current_element_info.is_none());
-        debug_assert!(thread_state::get() == thread_state::LAYOUT);
+        debug_assert!(thread_state::get() == ThreadState::LAYOUT);
 
         // Apply any slow selector flags that need to be set on parents.
         self.selector_flags.apply_flags();
     }
 }
 
 /// A `StyleContext` is just a simple container for a immutable reference to a
 /// shared style context, and a mutable reference to a local one.
--- a/servo/components/style/data.rs
+++ b/servo/components/style/data.rs
@@ -21,37 +21,37 @@ use smallvec::SmallVec;
 use std::fmt;
 use std::mem;
 use std::ops::{Deref, DerefMut};
 use style_resolver::{PrimaryStyle, ResolvedElementStyles, ResolvedStyle};
 
 bitflags! {
     /// Various flags stored on ElementData.
     #[derive(Default)]
-    pub flags ElementDataFlags: u8 {
+    pub struct ElementDataFlags: u8 {
         /// Whether the styles changed for this restyle.
-        const WAS_RESTYLED = 1 << 0,
+        const WAS_RESTYLED = 1 << 0;
         /// Whether the last traversal of this element did not do
         /// any style computation. This is not true during the initial
         /// styling pass, nor is it true when we restyle (in which case
         /// WAS_RESTYLED is set).
         ///
         /// This bit always corresponds to the last time the element was
         /// traversed, so each traversal simply updates it with the appropriate
         /// value.
-        const TRAVERSED_WITHOUT_STYLING = 1 << 1,
+        const TRAVERSED_WITHOUT_STYLING = 1 << 1;
         /// Whether we reframed/reconstructed any ancestor or self.
-        const ANCESTOR_WAS_RECONSTRUCTED = 1 << 2,
+        const ANCESTOR_WAS_RECONSTRUCTED = 1 << 2;
         /// Whether the primary style of this element data was reused from another
         /// element via a rule node comparison. This allows us to differentiate
         /// between elements that shared styles because they met all the criteria
         /// of the style sharing cache, compared to elements that reused style
         /// structs via rule node identity. The former gives us stronger transitive
         /// guarantees that allows us to apply the style sharing cache to cousins.
-        const PRIMARY_STYLE_REUSED_VIA_RULE_NODE = 1 << 3,
+        const PRIMARY_STYLE_REUSED_VIA_RULE_NODE = 1 << 3;
     }
 }
 
 /// A lazily-allocated list of styles for eagerly-cascaded pseudo-elements.
 ///
 /// We use an Arc so that sharing these styles via the style sharing cache does
 /// not require duplicate allocations. We leverage the copy-on-write semantics of
 /// Arc::make_mut(), which is free (i.e. does not require atomic RMU operations)
@@ -299,30 +299,30 @@ impl ElementData {
             primary: self.share_primary_style(),
             pseudos: self.styles.pseudos.clone(),
         }
     }
 
     /// Returns this element's primary style as a resolved style to use for sharing.
     pub fn share_primary_style(&self) -> PrimaryStyle {
         let reused_via_rule_node =
-            self.flags.contains(PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
+            self.flags.contains(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
 
         PrimaryStyle {
             style: ResolvedStyle(self.styles.primary().clone()),
             reused_via_rule_node,
         }
     }
 
     /// Sets a new set of styles, returning the old ones.
     pub fn set_styles(&mut self, new_styles: ResolvedElementStyles) -> ElementStyles {
         if new_styles.primary.reused_via_rule_node {
-            self.flags.insert(PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
+            self.flags.insert(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
         } else {
-            self.flags.remove(PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
+            self.flags.remove(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
         }
         mem::replace(&mut self.styles, new_styles.into())
     }
 
     /// Returns the kind of restyling that we're going to need to do on this
     /// element, based of the stored restyle hint.
     pub fn restyle_kind(
         &self,
@@ -400,69 +400,69 @@ impl ElementData {
         self.hint = RestyleHint::empty();
         self.clear_restyle_flags_and_damage();
     }
 
     /// Drops restyle flags and damage from the element.
     #[inline]
     pub fn clear_restyle_flags_and_damage(&mut self) {
         self.damage = RestyleDamage::empty();
-        self.flags.remove(WAS_RESTYLED | ANCESTOR_WAS_RECONSTRUCTED)
+        self.flags.remove(ElementDataFlags::WAS_RESTYLED | ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED)
     }
 
     /// Returns whether this element or any ancestor is going to be
     /// reconstructed.
     pub fn reconstructed_self_or_ancestor(&self) -> bool {
         self.reconstructed_ancestor() || self.reconstructed_self()
     }
 
     /// Returns whether this element is going to be reconstructed.
     pub fn reconstructed_self(&self) -> bool {
         self.damage.contains(RestyleDamage::reconstruct())
     }
 
     /// Returns whether any ancestor of this element is going to be
     /// reconstructed.
     fn reconstructed_ancestor(&self) -> bool {
-        self.flags.contains(ANCESTOR_WAS_RECONSTRUCTED)
+        self.flags.contains(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED)
     }
 
     /// Sets the flag that tells us whether we've reconstructed an ancestor.
     pub fn set_reconstructed_ancestor(&mut self, reconstructed: bool) {
         if reconstructed {
             // If it weren't for animation-only traversals, we could assert
             // `!self.reconstructed_ancestor()` here.
-            self.flags.insert(ANCESTOR_WAS_RECONSTRUCTED);
+            self.flags.insert(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED);
         } else {
-            self.flags.remove(ANCESTOR_WAS_RECONSTRUCTED);
+            self.flags.remove(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED);
         }
     }
 
     /// Mark this element as restyled, which is useful to know whether we need
     /// to do a post-traversal.
     pub fn set_restyled(&mut self) {
-        self.flags.insert(WAS_RESTYLED);
-        self.flags.remove(TRAVERSED_WITHOUT_STYLING);
+        self.flags.insert(ElementDataFlags::WAS_RESTYLED);
+        self.flags.remove(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
     }
 
     /// Returns true if this element was restyled.
     #[inline]
     pub fn is_restyle(&self) -> bool {
-        self.flags.contains(WAS_RESTYLED)
+        self.flags.contains(ElementDataFlags::WAS_RESTYLED)
     }
 
     /// Mark that we traversed this element without computing any style for it.
     pub fn set_traversed_without_styling(&mut self) {
-        self.flags.insert(TRAVERSED_WITHOUT_STYLING);
+        self.flags.insert(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
     }
 
     /// Returns whether the element was traversed without computing any style for
     /// it.
     pub fn traversed_without_styling(&self) -> bool {
-        self.flags.contains(TRAVERSED_WITHOUT_STYLING)
+        self.flags.contains(ElementDataFlags::TRAVERSED_WITHOUT_STYLING)
     }
 
     /// Returns whether this element has been part of a restyle.
     #[inline]
     pub fn contains_restyle_data(&self) -> bool {
         self.is_restyle() || !self.hint.is_empty() || !self.damage.is_empty()
     }
 
@@ -494,17 +494,18 @@ impl ElementData {
     /// tighten it by having the invalidation logic explicitly flag elements for which it
     /// ellided styling.
     ///
     /// Second, we want to only consider elements whose ComputedValues match due to a hit
     /// in the style sharing cache, rather than due to the rule-node-based reuse that
     /// happens later in the styling pipeline. The former gives us the stronger guarantees
     /// we need for style sharing, the latter does not.
     pub fn safe_for_cousin_sharing(&self) -> bool {
-        !self.flags.intersects(TRAVERSED_WITHOUT_STYLING | PRIMARY_STYLE_REUSED_VIA_RULE_NODE)
+        !self.flags.intersects(ElementDataFlags::TRAVERSED_WITHOUT_STYLING |
+                               ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE)
     }
 
     /// Measures memory usage.
     #[cfg(feature = "gecko")]
     pub fn size_of_excluding_cvs(&self, ops: &mut MallocSizeOfOps) -> usize {
         let n = self.styles.size_of_excluding_cvs(ops);
 
         // We may measure more fields in the future if DMD says it's worth it.
--- a/servo/components/style/dom.rs
+++ b/servo/components/style/dom.rs
@@ -27,17 +27,17 @@ use selectors::sink::Push;
 use servo_arc::{Arc, ArcBorrow};
 use shared_lock::Locked;
 use std::fmt;
 #[cfg(feature = "gecko")] use hash::FnvHashMap;
 use std::fmt::Debug;
 use std::hash::Hash;
 use std::ops::Deref;
 use stylist::Stylist;
-use traversal_flags::{TraversalFlags, self};
+use traversal_flags::TraversalFlags;
 
 /// An opaque handle to a node, which, unlike UnsafeNode, cannot be transformed
 /// back into a non-opaque representation. The only safe operation that can be
 /// performed on this node is to compare it to another opaque handle or to another
 /// OpaqueNode.
 ///
 /// Layout and Graphics use this to safely represent nodes for comparison purposes.
 /// Because the script task's GC does not trace layout, node data cannot be safely stored in layout
@@ -550,17 +550,17 @@ pub trait TElement
             // restyle which is a result of normal restyle (e.g. setting
             // animation-name in normal restyle and creating a new CSS
             // animation in a SequentialTask) is processed after the normal
             // traversal in that we had elements that handled snapshot.
             return data.has_styles() &&
                    !data.hint.has_animation_hint_or_recascade();
         }
 
-        if traversal_flags.contains(traversal_flags::UnstyledOnly) {
+        if traversal_flags.contains(TraversalFlags::UnstyledOnly) {
             // We don't process invalidations in UnstyledOnly mode.
             return data.has_styles();
         }
 
         if self.has_snapshot() && !self.handled_snapshot() {
             return false;
         }
 
--- a/servo/components/style/element_state.rs
+++ b/servo/components/style/element_state.rs
@@ -10,145 +10,146 @@ bitflags! {
     /// NB: Is important for this to remain in sync with Gecko's
     /// dom/events/EventStates.h.
     ///
     /// Please keep in that order in order for this to be easily auditable.
     ///
     /// TODO(emilio): We really really want to use the NS_EVENT_STATE bindings
     /// for this.
     #[derive(MallocSizeOf)]
-    pub flags ElementState: u64 {
+    pub struct ElementState: u64 {
         /// The mouse is down on this element.
         /// <https://html.spec.whatwg.org/multipage/#selector-active>
         /// FIXME(#7333): set/unset this when appropriate
-        const IN_ACTIVE_STATE = 1 << 0,
+        const IN_ACTIVE_STATE = 1 << 0;
         /// This element has focus.
         /// <https://html.spec.whatwg.org/multipage/#selector-focus>
-        const IN_FOCUS_STATE = 1 << 1,
+        const IN_FOCUS_STATE = 1 << 1;
         /// The mouse is hovering over this element.
         /// <https://html.spec.whatwg.org/multipage/#selector-hover>
-        const IN_HOVER_STATE = 1 << 2,
+        const IN_HOVER_STATE = 1 << 2;
         /// Content is enabled (and can be disabled).
         /// <http://www.whatwg.org/html/#selector-enabled>
-        const IN_ENABLED_STATE = 1 << 3,
+        const IN_ENABLED_STATE = 1 << 3;
         /// Content is disabled.
         /// <http://www.whatwg.org/html/#selector-disabled>
-        const IN_DISABLED_STATE = 1 << 4,
+        const IN_DISABLED_STATE = 1 << 4;
         /// Content is checked.
         /// <https://html.spec.whatwg.org/multipage/#selector-checked>
-        const IN_CHECKED_STATE = 1 << 5,
+        const IN_CHECKED_STATE = 1 << 5;
         /// <https://html.spec.whatwg.org/multipage/#selector-indeterminate>
-        const IN_INDETERMINATE_STATE = 1 << 6,
+        const IN_INDETERMINATE_STATE = 1 << 6;
         /// <https://html.spec.whatwg.org/multipage/#selector-placeholder-shown>
-        const IN_PLACEHOLDER_SHOWN_STATE = 1 << 7,
+        const IN_PLACEHOLDER_SHOWN_STATE = 1 << 7;
         /// <https://html.spec.whatwg.org/multipage/#selector-target>
-        const IN_TARGET_STATE = 1 << 8,
+        const IN_TARGET_STATE = 1 << 8;
         /// <https://fullscreen.spec.whatwg.org/#%3Afullscreen-pseudo-class>
-        const IN_FULLSCREEN_STATE = 1 << 9,
+        const IN_FULLSCREEN_STATE = 1 << 9;
         /// <https://html.spec.whatwg.org/multipage/#selector-valid>
-        const IN_VALID_STATE = 1 << 10,
+        const IN_VALID_STATE = 1 << 10;
         /// <https://html.spec.whatwg.org/multipage/#selector-invalid>
-        const IN_INVALID_STATE = 1 << 11,
+        const IN_INVALID_STATE = 1 << 11;
         /// Non-standard: https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-ui-valid
-        const IN_MOZ_UI_VALID_STATE = 1 << 12,
+        const IN_MOZ_UI_VALID_STATE = 1 << 12;
         /// Non-standard: https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-ui-invalid
-        const IN_MOZ_UI_INVALID_STATE = 1 << 13,
+        const IN_MOZ_UI_INVALID_STATE = 1 << 13;
         /// Non-standard: https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-broken
-        const IN_BROKEN_STATE = 1 << 14,
+        const IN_BROKEN_STATE = 1 << 14;
         /// Non-standard: https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-user-disabled
-        const IN_USER_DISABLED_STATE = 1 << 15,
+        const IN_USER_DISABLED_STATE = 1 << 15;
         /// Non-standard: https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-suppressed
-        const IN_SUPPRESSED_STATE = 1 << 16,
+        const IN_SUPPRESSED_STATE = 1 << 16;
         /// Non-standard: https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-loading
-        const IN_LOADING_STATE = 1 << 17,
+        const IN_LOADING_STATE = 1 << 17;
         /// Non-standard: https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-handler-blocked
-        const IN_HANDLER_BLOCKED_STATE = 1 << 18,
+        const IN_HANDLER_BLOCKED_STATE = 1 << 18;
         /// Non-standard: https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-handler-disabled
-        const IN_HANDLER_DISABLED_STATE = 1 << 19,
+        const IN_HANDLER_DISABLED_STATE = 1 << 19;
         /// Non-standard: https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-handler-crashed
-        const IN_HANDLER_CRASHED_STATE = 1 << 20,
+        const IN_HANDLER_CRASHED_STATE = 1 << 20;
         /// <https://html.spec.whatwg.org/multipage/#selector-required>
-        const IN_REQUIRED_STATE = 1 << 21,
+        const IN_REQUIRED_STATE = 1 << 21;
         /// <https://html.spec.whatwg.org/multipage/#selector-optional>
-        const IN_OPTIONAL_STATE = 1 << 22,
+        const IN_OPTIONAL_STATE = 1 << 22;
         /// <https://html.spec.whatwg.org/multipage/#selector-read-write>
-        const IN_READ_WRITE_STATE = 1 << 22,
+        const IN_READ_WRITE_STATE = 1 << 22;
         /// Non-standard: Older custom-elements spec.
-        const IN_UNRESOLVED_STATE = 1 << 23,
+        const IN_UNRESOLVED_STATE = 1 << 23;
         /// <https://html.spec.whatwg.org/multipage/#selector-visited>
-        const IN_VISITED_STATE = 1 << 24,
+        const IN_VISITED_STATE = 1 << 24;
         /// <https://html.spec.whatwg.org/multipage/#selector-link>
-        const IN_UNVISITED_STATE = 1 << 25,
+        const IN_UNVISITED_STATE = 1 << 25;
         /// <https://drafts.csswg.org/selectors-4/#the-any-link-pseudo>
-        const IN_VISITED_OR_UNVISITED_STATE = IN_VISITED_STATE.bits | IN_UNVISITED_STATE.bits,
+        const IN_VISITED_OR_UNVISITED_STATE = ElementState::IN_VISITED_STATE.bits |
+                                              ElementState::IN_UNVISITED_STATE.bits;
         /// Non-standard: https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-drag-over
-        const IN_DRAGOVER_STATE = 1 << 26,
+        const IN_DRAGOVER_STATE = 1 << 26;
         /// <https://html.spec.whatwg.org/multipage/#selector-in-range>
-        const IN_INRANGE_STATE = 1 << 27,
+        const IN_INRANGE_STATE = 1 << 27;
         /// <https://html.spec.whatwg.org/multipage/#selector-out-of-range>
-        const IN_OUTOFRANGE_STATE = 1 << 28,
+        const IN_OUTOFRANGE_STATE = 1 << 28;
         /// <https://html.spec.whatwg.org/multipage/#selector-read-only>
-        const IN_MOZ_READONLY_STATE = 1 << 29,
+        const IN_MOZ_READONLY_STATE = 1 << 29;
         /// <https://html.spec.whatwg.org/multipage/#selector-read-write>
-        const IN_MOZ_READWRITE_STATE = 1 << 30,
+        const IN_MOZ_READWRITE_STATE = 1 << 30;
         /// <https://html.spec.whatwg.org/multipage/#selector-default>
-        const IN_DEFAULT_STATE = 1 << 31,
+        const IN_DEFAULT_STATE = 1 << 31;
         /// Non-standard: https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-submit-invalid
-        const IN_MOZ_SUBMITINVALID_STATE = 1 << 32,
+        const IN_MOZ_SUBMITINVALID_STATE = 1 << 32;
         /// Non-standard & undocumented.
-        const IN_OPTIMUM_STATE = 1 << 33,
+        const IN_OPTIMUM_STATE = 1 << 33;
         /// Non-standard & undocumented.
-        const IN_SUB_OPTIMUM_STATE = 1 << 34,
+        const IN_SUB_OPTIMUM_STATE = 1 << 34;
         /// Non-standard & undocumented.
-        const IN_SUB_SUB_OPTIMUM_STATE = 1 << 35,
+        const IN_SUB_SUB_OPTIMUM_STATE = 1 << 35;
         /// Non-standard & undocumented.
-        const IN_DEVTOOLS_HIGHLIGHTED_STATE = 1 << 36,
+        const IN_DEVTOOLS_HIGHLIGHTED_STATE = 1 << 36;
         /// Non-standard & undocumented.
-        const IN_STYLEEDITOR_TRANSITIONING_STATE = 1 << 37,
+        const IN_STYLEEDITOR_TRANSITIONING_STATE = 1 << 37;
         /// Non-standard & undocumented.
-        const IN_INCREMENT_SCRIPT_LEVEL_STATE = 1 << 38,
+        const IN_INCREMENT_SCRIPT_LEVEL_STATE = 1 << 38;
         /// Non-standard: https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-focusring
-        const IN_FOCUSRING_STATE = 1 << 39,
+        const IN_FOCUSRING_STATE = 1 << 39;
         /// Non-standard & undocumented.
-        const IN_HANDLER_CLICK_TO_PLAY_STATE = 1 << 40,
+        const IN_HANDLER_CLICK_TO_PLAY_STATE = 1 << 40;
         /// Non-standard & undocumented.
-        const IN_HANDLER_VULNERABLE_UPDATABLE_STATE = 1 << 41,
+        const IN_HANDLER_VULNERABLE_UPDATABLE_STATE = 1 << 41;
         /// Non-standard & undocumented.
-        const IN_HANDLER_VULNERABLE_NO_UPDATE_STATE = 1 << 42,
+        const IN_HANDLER_VULNERABLE_NO_UPDATE_STATE = 1 << 42;
         /// <https://drafts.csswg.org/selectors-4/#the-focus-within-pseudo>
-        const IN_FOCUS_WITHIN_STATE = 1 << 43,
+        const IN_FOCUS_WITHIN_STATE = 1 << 43;
         /// :dir matching; the states are used for dynamic change detection.
         /// State that elements that match :dir(ltr) are in.
-        const IN_LTR_STATE = 1 << 44,
+        const IN_LTR_STATE = 1 << 44;
         /// State that elements that match :dir(rtl) are in.
-        const IN_RTL_STATE = 1 << 45,
+        const IN_RTL_STATE = 1 << 45;
         /// State that HTML elements that have a "dir" attr are in.
-        const IN_HAS_DIR_ATTR_STATE = 1 << 46,
+        const IN_HAS_DIR_ATTR_STATE = 1 << 46;
         /// State that HTML elements with dir="ltr" (or something
         /// case-insensitively equal to "ltr") are in.
-        const IN_HAS_DIR_ATTR_LTR_STATE = 1 << 47,
+        const IN_HAS_DIR_ATTR_LTR_STATE = 1 << 47;
         /// State that HTML elements with dir="rtl" (or something
         /// case-insensitively equal to "rtl") are in.
-        const IN_HAS_DIR_ATTR_RTL_STATE = 1 << 48,
+        const IN_HAS_DIR_ATTR_RTL_STATE = 1 << 48;
         /// State that HTML <bdi> elements without a valid-valued "dir" attr or
         /// any HTML elements (including <bdi>) with dir="auto" (or something
         /// case-insensitively equal to "auto") are in.
-        const IN_HAS_DIR_ATTR_LIKE_AUTO_STATE = 1 << 49,
+        const IN_HAS_DIR_ATTR_LIKE_AUTO_STATE = 1 << 49;
         /// Non-standard & undocumented.
-        const IN_AUTOFILL_STATE = 1 << 50,
+        const IN_AUTOFILL_STATE = 1 << 50;
         /// Non-standard & undocumented.
-        const IN_AUTOFILL_PREVIEW_STATE = 1 << 51,
+        const IN_AUTOFILL_PREVIEW_STATE = 1 << 51;
     }
 }
 
 bitflags! {
     /// Event-based document states.
     ///
     /// NB: Is important for this to remain in sync with Gecko's
     /// dom/base/nsIDocument.h.
     #[derive(MallocSizeOf)]
-    pub flags DocumentState: u64 {
+    pub struct DocumentState: u64 {
         /// RTL locale: specific to the XUL localedir attribute
-        const NS_DOCUMENT_STATE_RTL_LOCALE = 1 << 0,
+        const NS_DOCUMENT_STATE_RTL_LOCALE = 1 << 0;
         /// Window activation status
-        const NS_DOCUMENT_STATE_WINDOW_INACTIVE = 1 << 1,
+        const NS_DOCUMENT_STATE_WINDOW_INACTIVE = 1 << 1;
     }
 }
--- a/servo/components/style/gecko/pseudo_element.rs
+++ b/servo/components/style/gecko/pseudo_element.rs
@@ -5,19 +5,17 @@
 //! Gecko's definition of a pseudo-element.
 //!
 //! Note that a few autogenerated bits of this live in
 //! `pseudo_element_definition.mako.rs`. If you touch that file, you probably
 //! need to update the checked-in files for Servo.
 
 use cssparser::{ToCss, serialize_identifier};
 use gecko_bindings::structs::{self, CSSPseudoElementType};
-use properties::{PropertyFlags, APPLIES_TO_FIRST_LETTER, APPLIES_TO_FIRST_LINE};
-use properties::APPLIES_TO_PLACEHOLDER;
-use properties::ComputedValues;
+use properties::{ComputedValues, PropertyFlags};
 use properties::longhands::display::computed_value as display;
 use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl};
 use std::fmt;
 use string_cache::Atom;
 
 include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs"));
 
 impl ::selectors::parser::PseudoElement for PseudoElement {
@@ -148,19 +146,19 @@ impl PseudoElement {
             _ => self.clone(),
         }
     }
 
     /// Property flag that properties must have to apply to this pseudo-element.
     #[inline]
     pub fn property_restriction(&self) -> Option<PropertyFlags> {
         match *self {
-            PseudoElement::FirstLetter => Some(APPLIES_TO_FIRST_LETTER),
-            PseudoElement::FirstLine => Some(APPLIES_TO_FIRST_LINE),
-            PseudoElement::Placeholder => Some(APPLIES_TO_PLACEHOLDER),
+            PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER),
+            PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE),
+            PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER),
             _ => None,
         }
     }
 
     /// Whether this pseudo-element should actually exist if it has
     /// the given styles.
     pub fn should_exist(&self, style: &ComputedValues) -> bool
     {
--- a/servo/components/style/gecko/selector_parser.rs
+++ b/servo/components/style/gecko/selector_parser.rs
@@ -1,37 +1,38 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 //! Gecko-specific bits for selector-parsing.
 
 use cssparser::{BasicParseError, BasicParseErrorKind, Parser, ToCss, Token, CowRcStr, SourceLocation};
-use element_state::{self, DocumentState, ElementState};
+use element_state::{DocumentState, ElementState};
 use gecko_bindings::structs::CSSPseudoClassType;
 use gecko_bindings::structs::RawServoSelectorList;
 use gecko_bindings::sugar::ownership::{HasBoxFFI, HasFFI, HasSimpleFFI};
 use selector_parser::{SelectorParser, PseudoElementCascadeType};
 use selectors::SelectorList;
 use selectors::parser::{Selector, SelectorMethods, SelectorParseErrorKind};
 use selectors::visitor::SelectorVisitor;
 use std::fmt;
 use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace};
 use style_traits::{ParseError, StyleParseErrorKind};
 
 pub use gecko::pseudo_element::{PseudoElement, EAGER_PSEUDOS, EAGER_PSEUDO_COUNT, PSEUDO_COUNT};
 pub use gecko::snapshot::SnapshotMap;
 
 bitflags! {
     // See NonTSPseudoClass::is_enabled_in()
-    flags NonTSPseudoClassFlag: u8 {
-        const PSEUDO_CLASS_ENABLED_IN_UA_SHEETS = 1 << 0,
-        const PSEUDO_CLASS_ENABLED_IN_CHROME = 1 << 1,
+    struct NonTSPseudoClassFlag: u8 {
+        const PSEUDO_CLASS_ENABLED_IN_UA_SHEETS = 1 << 0;
+        const PSEUDO_CLASS_ENABLED_IN_CHROME = 1 << 1;
         const PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME =
-            PSEUDO_CLASS_ENABLED_IN_UA_SHEETS.bits | PSEUDO_CLASS_ENABLED_IN_CHROME.bits,
+            NonTSPseudoClassFlag::PSEUDO_CLASS_ENABLED_IN_UA_SHEETS.bits |
+            NonTSPseudoClassFlag::PSEUDO_CLASS_ENABLED_IN_CHROME.bits;
     }
 }
 
 /// The type used for storing pseudo-class string arguments.
 pub type PseudoClassStringArg = Box<[u16]>;
 
 macro_rules! pseudo_class_name {
     (bare: [$(($css:expr, $name:ident, $gecko_type:tt, $state:tt, $flags:tt),)*],
@@ -129,17 +130,17 @@ impl SelectorMethods for NonTSPseudoClas
 }
 
 
 impl NonTSPseudoClass {
     /// Returns true if this pseudo-class has any of the given flags set.
     fn has_any_flag(&self, flags: NonTSPseudoClassFlag) -> bool {
         macro_rules! check_flag {
             (_) => (false);
-            ($flags:expr) => ($flags.intersects(flags));
+            ($flags:ident) => (NonTSPseudoClassFlag::$flags.intersects(flags));
         }
         macro_rules! pseudo_class_check_is_enabled_in {
             (bare: [$(($css:expr, $name:ident, $gecko_type:tt, $state:tt, $flags:tt),)*],
             string: [$(($s_css:expr, $s_name:ident, $s_gecko_type:tt, $s_state:tt, $s_flags:tt),)*],
             keyword: [$(($k_css:expr, $k_name:ident, $k_gecko_type:tt, $k_state:tt, $k_flags:tt),)*]) => {
                 match *self {
                     $(NonTSPseudoClass::$name => check_flag!($flags),)*
                     $(NonTSPseudoClass::$s_name(..) => check_flag!($s_flags),)*
@@ -156,34 +157,34 @@ impl NonTSPseudoClass {
         use gecko_bindings::structs::mozilla;
         match self {
             // For pseudo-classes with pref, the availability in content
             // depends on the pref.
             &NonTSPseudoClass::Fullscreen =>
                 unsafe { mozilla::StylePrefs_sUnprefixedFullscreenApiEnabled },
             // Otherwise, a pseudo-class is enabled in content when it
             // doesn't have any enabled flag.
-            _ => !self.has_any_flag(PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
+            _ => !self.has_any_flag(NonTSPseudoClassFlag::PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
         }
     }
 
     /// <https://drafts.csswg.org/selectors-4/#useraction-pseudos>
     ///
     /// We intentionally skip the link-related ones.
     pub fn is_safe_user_action_state(&self) -> bool {
         matches!(*self, NonTSPseudoClass::Hover |
                         NonTSPseudoClass::Active |
                         NonTSPseudoClass::Focus)
     }
 
     /// Get the state flag associated with a pseudo-class, if any.
     pub fn state_flag(&self) -> ElementState {
         macro_rules! flag {
             (_) => (ElementState::empty());
-            ($state:ident) => (::element_state::$state);
+            ($state:ident) => (ElementState::$state);
         }
         macro_rules! pseudo_class_state {
             (bare: [$(($css:expr, $name:ident, $gecko_type:tt, $state:tt, $flags:tt),)*],
              string: [$(($s_css:expr, $s_name:ident, $s_gecko_type:tt, $s_state:tt, $s_flags:tt),)*],
              keyword: [$(($k_css:expr, $k_name:ident, $k_gecko_type:tt, $k_state:tt, $k_flags:tt),)*]) => {
                 match *self {
                     $(NonTSPseudoClass::$name => flag!($state),)*
                     $(NonTSPseudoClass::$s_name(..) => flag!($s_state),)*
@@ -193,18 +194,18 @@ impl NonTSPseudoClass {
             }
         }
         apply_non_ts_list!(pseudo_class_state)
     }
 
     /// Get the document state flag associated with a pseudo-class, if any.
     pub fn document_state_flag(&self) -> DocumentState {
         match *self {
-            NonTSPseudoClass::MozLocaleDir(..) => element_state::NS_DOCUMENT_STATE_RTL_LOCALE,
-            NonTSPseudoClass::MozWindowInactive => element_state::NS_DOCUMENT_STATE_WINDOW_INACTIVE,
+            NonTSPseudoClass::MozLocaleDir(..) => DocumentState::NS_DOCUMENT_STATE_RTL_LOCALE,
+            NonTSPseudoClass::MozWindowInactive => DocumentState::NS_DOCUMENT_STATE_WINDOW_INACTIVE,
             _ => DocumentState::empty(),
         }
     }
 
     /// Returns true if the given pseudoclass should trigger style sharing cache
     /// revalidation.
     pub fn needs_cache_revalidation(&self) -> bool {
         self.state_flag().is_empty() &&
@@ -294,19 +295,19 @@ impl ::selectors::SelectorImpl for Selec
 }
 
 impl<'a> SelectorParser<'a> {
     fn is_pseudo_class_enabled(&self,
                                pseudo_class: &NonTSPseudoClass)
                                -> bool {
         pseudo_class.is_enabled_in_content() ||
             (self.in_user_agent_stylesheet() &&
-             pseudo_class.has_any_flag(PSEUDO_CLASS_ENABLED_IN_UA_SHEETS)) ||
+             pseudo_class.has_any_flag(NonTSPseudoClassFlag::PSEUDO_CLASS_ENABLED_IN_UA_SHEETS)) ||
             (self.in_chrome_stylesheet() &&
-             pseudo_class.has_any_flag(PSEUDO_CLASS_ENABLED_IN_CHROME))
+             pseudo_class.has_any_flag(NonTSPseudoClassFlag::PSEUDO_CLASS_ENABLED_IN_CHROME))
     }
 }
 
 impl<'a, 'i> ::selectors::Parser<'i> for SelectorParser<'a> {
     type Impl = SelectorImpl;
     type Error = StyleParseErrorKind<'i>;
 
     fn is_pseudo_element_allows_single_colon(name: &CowRcStr<'i>) -> bool {
--- a/servo/components/style/gecko/wrapper.rs
+++ b/servo/components/style/gecko/wrapper.rs
@@ -16,17 +16,17 @@
 
 use CaseSensitivityExt;
 use app_units::Au;
 use applicable_declarations::ApplicableDeclarationBlock;
 use atomic_refcell::{AtomicRefCell, AtomicRef, AtomicRefMut};
 use context::{QuirksMode, SharedStyleContext, PostAnimationTasks, UpdateAnimationsTasks};
 use data::ElementData;
 use dom::{LayoutIterator, NodeInfo, OpaqueNode, TElement, TDocument, TNode};
-use element_state::{ElementState, DocumentState, NS_DOCUMENT_STATE_WINDOW_INACTIVE};
+use element_state::{ElementState, DocumentState};
 use error_reporting::ParseErrorReporter;
 use font_metrics::{FontMetrics, FontMetricsProvider, FontMetricsQueryResult};
 use gecko::data::PerDocumentStyleData;
 use gecko::global_style_data::GLOBAL_STYLE_DATA;
 use gecko::selector_parser::{SelectorImpl, NonTSPseudoClass, PseudoElement};
 use gecko::snapshot_helpers;
 use gecko_bindings::bindings;
 use gecko_bindings::bindings::{Gecko_ConstructStyleChildrenIterator, Gecko_DestroyStyleChildrenIterator};
@@ -769,28 +769,27 @@ impl<'le> GeckoElement<'le> {
     }
 }
 
 /// Converts flags from the layout used by rust-selectors to the layout used
 /// by Gecko. We could align these and then do this without conditionals, but
 /// it's probably not worth the trouble.
 fn selector_flags_to_node_flags(flags: ElementSelectorFlags) -> u32 {
     use gecko_bindings::structs::*;
-    use selectors::matching::*;
     let mut gecko_flags = 0u32;
-    if flags.contains(HAS_SLOW_SELECTOR) {
+    if flags.contains(ElementSelectorFlags::HAS_SLOW_SELECTOR) {
         gecko_flags |= NODE_HAS_SLOW_SELECTOR as u32;
     }
-    if flags.contains(HAS_SLOW_SELECTOR_LATER_SIBLINGS) {
+    if flags.contains(ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS) {
         gecko_flags |= NODE_HAS_SLOW_SELECTOR_LATER_SIBLINGS as u32;
     }
-    if flags.contains(HAS_EDGE_CHILD_SELECTOR) {
+    if flags.contains(ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR) {
         gecko_flags |= NODE_HAS_EDGE_CHILD_SELECTOR as u32;
     }
-    if flags.contains(HAS_EMPTY_SELECTOR) {
+    if flags.contains(ElementSelectorFlags::HAS_EMPTY_SELECTOR) {
         gecko_flags |= NODE_HAS_EMPTY_SELECTOR as u32;
     }
 
     gecko_flags
 }
 
 fn get_animation_rule(
     element: &GeckoElement,
@@ -1142,18 +1141,17 @@ impl<'le> TElement for GeckoElement<'le>
     unsafe fn clear_dirty_bits(&self) {
         self.unset_flags(ELEMENT_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32 |
                          ELEMENT_HAS_ANIMATION_ONLY_DIRTY_DESCENDANTS_FOR_SERVO as u32 |
                          NODE_DESCENDANTS_NEED_FRAMES as u32 |
                          NODE_NEEDS_FRAME as u32)
     }
 
     fn is_visited_link(&self) -> bool {
-        use element_state::IN_VISITED_STATE;
-        self.get_state().intersects(IN_VISITED_STATE)
+        self.get_state().intersects(ElementState::IN_VISITED_STATE)
     }
 
     #[inline]
     fn is_native_anonymous(&self) -> bool {
         use gecko_bindings::structs::NODE_IS_NATIVE_ANONYMOUS;
         self.flags() & (NODE_IS_NATIVE_ANONYMOUS as u32) != 0
     }
 
@@ -1254,27 +1252,26 @@ impl<'le> TElement for GeckoElement<'le>
             });
         }
         self.as_node().get_bool_flag(nsINode_BooleanFlag::ElementHasAnimations)
     }
 
     /// Process various tasks that are a result of animation-only restyle.
     fn process_post_animation(&self,
                               tasks: PostAnimationTasks) {
-        use context::DISPLAY_CHANGED_FROM_NONE_FOR_SMIL;
         use gecko_bindings::structs::nsChangeHint_nsChangeHint_Empty;
         use gecko_bindings::structs::nsRestyleHint_eRestyle_Subtree;
 
         debug_assert!(!tasks.is_empty(), "Should be involved a task");
 
         // If display style was changed from none to other, we need to resolve
         // the descendants in the display:none subtree. Instead of resolving
         // those styles in animation-only restyle, we defer it to a subsequent
         // normal restyle.
-        if tasks.intersects(DISPLAY_CHANGED_FROM_NONE_FOR_SMIL) {
+        if tasks.intersects(PostAnimationTasks::DISPLAY_CHANGED_FROM_NONE_FOR_SMIL) {
             debug_assert!(self.implemented_pseudo_element()
                               .map_or(true, |p| !p.is_before_or_after()),
                           "display property animation shouldn't run on pseudo elements \
                            since it's only for SMIL");
             self.note_explicit_hints(nsRestyleHint_eRestyle_Subtree,
                                      nsChangeHint_nsChangeHint_Empty);
         }
     }
@@ -1959,39 +1956,39 @@ impl<'le> ::selectors::Element for Gecko
             NonTSPseudoClass::Hover |
             NonTSPseudoClass::MozAutofillPreview => {
                 self.get_state().intersects(pseudo_class.state_flag())
             },
             NonTSPseudoClass::AnyLink => self.is_link(),
             NonTSPseudoClass::Link => relevant_link.is_unvisited(self, context),
             NonTSPseudoClass::Visited => relevant_link.is_visited(self, context),
             NonTSPseudoClass::MozFirstNode => {
-                flags_setter(self, HAS_EDGE_CHILD_SELECTOR);
+                flags_setter(self, ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR);
                 let mut elem = self.as_node();
                 while let Some(prev) = elem.prev_sibling() {
                     if prev.contains_non_whitespace_content() {
                         return false
                     }
                     elem = prev;
                 }
                 true
             }
             NonTSPseudoClass::MozLastNode => {
-                flags_setter(self, HAS_EDGE_CHILD_SELECTOR);
+                flags_setter(self, ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR);
                 let mut elem = self.as_node();
                 while let Some(next) = elem.next_sibling() {
                     if next.contains_non_whitespace_content() {
                         return false
                     }
                     elem = next;
                 }
                 true
             }
             NonTSPseudoClass::MozOnlyWhitespace => {
-                flags_setter(self, HAS_EMPTY_SELECTOR);
+                flags_setter(self, ElementSelectorFlags::HAS_EMPTY_SELECTOR);
                 if self.as_node().dom_children().any(|c| c.contains_non_whitespace_content()) {
                     return false
                 }
                 true
             }
             NonTSPseudoClass::MozTableBorderNonzero |
             NonTSPseudoClass::MozBrowserFrame |
             NonTSPseudoClass::MozNativeAnonymous |
@@ -2006,17 +2003,17 @@ impl<'le> ::selectors::Element for Gecko
             }
             NonTSPseudoClass::MozLWThemeBrightText => {
                 self.get_document_theme() == DocumentTheme::Doc_Theme_Bright
             }
             NonTSPseudoClass::MozLWThemeDarkText => {
                 self.get_document_theme() == DocumentTheme::Doc_Theme_Dark
             }
             NonTSPseudoClass::MozWindowInactive => {
-                self.document_state().contains(NS_DOCUMENT_STATE_WINDOW_INACTIVE)
+                self.document_state().contains(DocumentState::NS_DOCUMENT_STATE_WINDOW_INACTIVE)
             }
             NonTSPseudoClass::MozPlaceholder => false,
             NonTSPseudoClass::MozAny(ref sels) => {
                 context.nesting_level += 1;
                 let result = sels.iter().any(|s| {
                     matches_complex_selector(s.iter(), self, context, flags_setter)
                 });
                 context.nesting_level -= 1;
--- a/servo/components/style/gecko_bindings/sugar/origin_flags.rs
+++ b/servo/components/style/gecko_bindings/sugar/origin_flags.rs
@@ -8,19 +8,19 @@ use gecko_bindings::structs::OriginFlags
 use gecko_bindings::structs::OriginFlags_Author;
 use gecko_bindings::structs::OriginFlags_User;
 use gecko_bindings::structs::OriginFlags_UserAgent;
 use stylesheets::OriginSet;
 
 /// Checks that the values for OriginFlags are the ones we expect.
 pub fn assert_flags_match() {
     use stylesheets::origin::*;
-    debug_assert_eq!(OriginFlags_UserAgent.0, ORIGIN_USER_AGENT.bits());
-    debug_assert_eq!(OriginFlags_Author.0, ORIGIN_AUTHOR.bits());
-    debug_assert_eq!(OriginFlags_User.0, ORIGIN_USER.bits());
+    debug_assert_eq!(OriginFlags_UserAgent.0, OriginSet::ORIGIN_USER_AGENT.bits());
+    debug_assert_eq!(OriginFlags_Author.0, OriginSet::ORIGIN_AUTHOR.bits());
+    debug_assert_eq!(OriginFlags_User.0, OriginSet::ORIGIN_USER.bits());
 }
 
 impl From<OriginFlags> for OriginSet {
     fn from(flags: OriginFlags) -> Self {
         Self::from_bits_truncate(flags.0)
     }
 }
 
--- a/servo/components/style/invalidation/element/collector.rs
+++ b/servo/components/style/invalidation/element/collector.rs
@@ -5,21 +5,21 @@
 //! An invalidation processor for style changes due to state and attribute
 //! changes.
 
 use Atom;
 use atomic_refcell::AtomicRef;
 use context::{QuirksMode, SharedStyleContext};
 use data::ElementData;
 use dom::TElement;
-use element_state::{ElementState, IN_VISITED_OR_UNVISITED_STATE};
+use element_state::ElementState;
 use invalidation::element::element_wrapper::{ElementSnapshot, ElementWrapper};
 use invalidation::element::invalidation_map::*;
 use invalidation::element::invalidator::{InvalidationVector, Invalidation, InvalidationProcessor};
-use invalidation::element::restyle_hints::*;
+use invalidation::element::restyle_hints::RestyleHint;
 use selector_map::SelectorMap;
 use selector_parser::Snapshot;
 use selectors::NthIndexCache;
 use selectors::attr::CaseSensitivity;
 use selectors::matching::{MatchingContext, MatchingMode, VisitedHandlingMode};
 use selectors::matching::matches_selector;
 use smallvec::SmallVec;
 use stylesheets::origin::{Origin, OriginSet};
@@ -123,17 +123,17 @@ where
         if !snapshot.has_attrs() && state_changes.is_empty() {
             return false;
         }
 
         // If we are sensitive to visitedness and the visited state changed, we
         // force a restyle here. Matching doesn't depend on the actual visited
         // state at all, so we can't look at matching results to decide what to
         // do for this case.
-        if state_changes.intersects(IN_VISITED_OR_UNVISITED_STATE) {
+        if state_changes.intersects(ElementState::IN_VISITED_OR_UNVISITED_STATE) {
             trace!(" > visitedness change, force subtree restyle");
             // We can't just return here because there may also be attribute
             // changes as well that imply additional hints.
             self.data.hint.insert(RestyleHint::restyle_subtree());
         }
 
         let mut classes_removed = SmallVec::<[Atom; 8]>::new();
         let mut classes_added = SmallVec::<[Atom; 8]>::new();
@@ -210,45 +210,45 @@ where
                     collector.collect_dependencies_in_invalidation_map(invalidation_map);
                 })
             }
 
             collector.invalidates_self
         };
 
         if invalidated_self {
-            self.data.hint.insert(RESTYLE_SELF);
+            self.data.hint.insert(RestyleHint::RESTYLE_SELF);
         }
 
         invalidated_self
     }
 
     fn should_process_descendants(&mut self, element: E) -> bool {
         if element == self.element {
             return !self.data.styles.is_display_none() &&
-                !self.data.hint.contains(RESTYLE_DESCENDANTS)
+                !self.data.hint.contains(RestyleHint::RESTYLE_DESCENDANTS)
         }
 
         let data = match element.borrow_data() {
             None => return false,
             Some(data) => data,
         };
 
         !data.styles.is_display_none() &&
-            !data.hint.contains(RESTYLE_DESCENDANTS)
+            !data.hint.contains(RestyleHint::RESTYLE_DESCENDANTS)
     }
 
     fn recursion_limit_exceeded(&mut self, element: E) {
         if element == self.element {
-            self.data.hint.insert(RESTYLE_DESCENDANTS);
+            self.data.hint.insert(RestyleHint::RESTYLE_DESCENDANTS);
             return;
         }
 
         if let Some(mut data) = element.mutate_data() {
-            data.hint.insert(RESTYLE_DESCENDANTS);
+            data.hint.insert(RestyleHint::RESTYLE_DESCENDANTS);
         }
     }
 
     fn invalidated_descendants(&mut self, element: E, child: E) {
         if child.get_data().is_none() {
             return;
         }
 
@@ -266,17 +266,17 @@ where
                 break;
             }
         }
     }
 
     fn invalidated_self(&mut self, element: E) {
         debug_assert_ne!(element, self.element);
         if let Some(mut data) = element.mutate_data() {
-            data.hint.insert(RESTYLE_SELF);
+            data.hint.insert(RestyleHint::RESTYLE_SELF);
         }
     }
 }
 
 impl<'a, 'b, 'selectors, E> Collector<'a, 'b, 'selectors, E>
 where
     E: TElement,
     'selectors: 'a,
@@ -358,17 +358,17 @@ where
             self.quirks_mode,
             self.removed_id,
             self.classes_removed,
             |dependency| {
                 if !dependency.state.intersects(state_changes) {
                     return true;
                 }
                 let visited_dependent =
-                    if dependency.state.intersects(IN_VISITED_OR_UNVISITED_STATE) {
+                    if dependency.state.intersects(ElementState::IN_VISITED_OR_UNVISITED_STATE) {
                         VisitedDependent::Yes
                     } else {
                         VisitedDependent::No
                     };
                 self.scan_dependency(&dependency.dep, visited_dependent);
                 true
             },
         );
--- a/servo/components/style/invalidation/element/invalidation_map.rs
+++ b/servo/components/style/invalidation/element/invalidation_map.rs
@@ -15,26 +15,26 @@ use selectors::attr::NamespaceConstraint
 use selectors::parser::{Combinator, Component};
 use selectors::parser::{Selector, SelectorIter, SelectorMethods};
 use selectors::visitor::SelectorVisitor;
 use smallvec::SmallVec;
 
 #[cfg(feature = "gecko")]
 /// Gets the element state relevant to the given `:dir` pseudo-class selector.
 pub fn dir_selector_to_state(s: &[u16]) -> ElementState {
-    use element_state::{IN_LTR_STATE, IN_RTL_STATE};
+    use element_state::ElementState;
 
     // Jump through some hoops to deal with our Box<[u16]> thing.
     const LTR: [u16; 4] = [b'l' as u16, b't' as u16, b'r' as u16, 0];
     const RTL: [u16; 4] = [b'r' as u16, b't' as u16, b'l' as u16, 0];
 
     if LTR == *s {
-        IN_LTR_STATE
+        ElementState::IN_LTR_STATE
     } else if RTL == *s {
-        IN_RTL_STATE
+        ElementState::IN_RTL_STATE
     } else {
         // :dir(something-random) is a valid selector, but shouldn't
         // match anything.
         ElementState::empty()
     }
 }
 
 /// Mapping between (partial) CompoundSelectors (and the combinator to their
--- a/servo/components/style/invalidation/element/restyle_hints.rs
+++ b/servo/components/style/invalidation/element/restyle_hints.rs
@@ -5,75 +5,75 @@
 //! Restyle hints: an optimization to avoid unnecessarily matching selectors.
 
 #[cfg(feature = "gecko")]
 use gecko_bindings::structs::nsRestyleHint;
 use traversal_flags::TraversalFlags;
 
 bitflags! {
     /// The kind of restyle we need to do for a given element.
-    pub flags RestyleHint: u8 {
+    pub struct RestyleHint: u8 {
         /// Do a selector match of the element.
-        const RESTYLE_SELF = 1 << 0,
+        const RESTYLE_SELF = 1 << 0;
 
         /// Do a selector match of the element's descendants.
-        const RESTYLE_DESCENDANTS = 1 << 1,
+        const RESTYLE_DESCENDANTS = 1 << 1;
 
         /// Recascade the current element.
-        const RECASCADE_SELF = 1 << 2,
+        const RECASCADE_SELF = 1 << 2;
 
         /// Recascade all descendant elements.
-        const RECASCADE_DESCENDANTS = 1 << 3,
+        const RECASCADE_DESCENDANTS = 1 << 3;
 
         /// Replace the style data coming from CSS transitions without updating
         /// any other style data. This hint is only processed in animation-only
         /// traversal which is prior to normal traversal.
-        const RESTYLE_CSS_TRANSITIONS = 1 << 4,
+        const RESTYLE_CSS_TRANSITIONS = 1 << 4;
 
         /// Replace the style data coming from CSS animations without updating
         /// any other style data. This hint is only processed in animation-only
         /// traversal which is prior to normal traversal.
-        const RESTYLE_CSS_ANIMATIONS = 1 << 5,
+        const RESTYLE_CSS_ANIMATIONS = 1 << 5;
 
         /// Don't re-run selector-matching on the element, only the style
         /// attribute has changed, and this change didn't have any other
         /// dependencies.
-        const RESTYLE_STYLE_ATTRIBUTE = 1 << 6,
+        const RESTYLE_STYLE_ATTRIBUTE = 1 << 6;
 
         /// Replace the style data coming from SMIL animations without updating
         /// any other style data. This hint is only processed in animation-only
         /// traversal which is prior to normal traversal.
-        const RESTYLE_SMIL = 1 << 7,
+        const RESTYLE_SMIL = 1 << 7;
     }
 }
 
 impl RestyleHint {
     /// Creates a new `RestyleHint` indicating that the current element and all
     /// its descendants must be fully restyled.
     pub fn restyle_subtree() -> Self {
-        RESTYLE_SELF | RESTYLE_DESCENDANTS
+        RestyleHint::RESTYLE_SELF | RestyleHint::RESTYLE_DESCENDANTS
     }
 
     /// Creates a new `RestyleHint` indicating that the current element and all
     /// its descendants must be recascaded.
     pub fn recascade_subtree() -> Self {
-        RECASCADE_SELF | RECASCADE_DESCENDANTS
+        RestyleHint::RECASCADE_SELF | RestyleHint::RECASCADE_DESCENDANTS
     }
 
     /// Returns whether this hint invalidates the element and all its
     /// descendants.
     pub fn contains_subtree(&self) -> bool {
-        self.contains(RESTYLE_SELF | RESTYLE_DESCENDANTS)
+        self.contains(RestyleHint::RESTYLE_SELF | RestyleHint::RESTYLE_DESCENDANTS)
     }
 
     /// Returns whether we need to restyle this element.
     pub fn has_non_animation_invalidations(&self) -> bool {
         self.intersects(
-            RESTYLE_SELF |
-            RECASCADE_SELF |
+            RestyleHint::RESTYLE_SELF |
+            RestyleHint::RECASCADE_SELF |
             (Self::replacements() & !Self::for_animations())
         )
     }
 
     /// Propagates this restyle hint to a child element.
     pub fn propagate(&mut self, traversal_flags: &TraversalFlags) -> Self {
         use std::mem;
 
@@ -91,74 +91,74 @@ impl RestyleHint {
         // Else we should clear ourselves, and return the propagated hint.
         mem::replace(self, Self::empty())
             .propagate_for_non_animation_restyle()
     }
 
     /// Returns a new `CascadeHint` appropriate for children of the current
     /// element.
     fn propagate_for_non_animation_restyle(&self) -> Self {
-        if self.contains(RESTYLE_DESCENDANTS) {
+        if self.contains(RestyleHint::RESTYLE_DESCENDANTS) {
             return Self::restyle_subtree()
         }
-        if self.contains(RECASCADE_DESCENDANTS) {
+        if self.contains(RestyleHint::RECASCADE_DESCENDANTS) {
             return Self::recascade_subtree()
         }
         Self::empty()
     }
 
     /// Creates a new `RestyleHint` that indicates the element must be
     /// recascaded.
     pub fn recascade_self() -> Self {
-        RECASCADE_SELF
+        RestyleHint::RECASCADE_SELF
     }
 
     /// Returns a hint that contains all the replacement hints.
     pub fn replacements() -> Self {
-        RESTYLE_STYLE_ATTRIBUTE | Self::for_animations()
+        RestyleHint::RESTYLE_STYLE_ATTRIBUTE | Self::for_animations()
     }
 
     /// The replacements for the animation cascade levels.
     #[inline]
     pub fn for_animations() -> Self {
-        RESTYLE_SMIL | RESTYLE_CSS_ANIMATIONS | RESTYLE_CSS_TRANSITIONS
+        RestyleHint::RESTYLE_SMIL | RestyleHint::RESTYLE_CSS_ANIMATIONS | RestyleHint::RESTYLE_CSS_TRANSITIONS
     }
 
     /// Returns whether the hint specifies that the currently element must be
     /// recascaded.
     pub fn has_recascade_self(&self) -> bool {
-        self.contains(RECASCADE_SELF)
+        self.contains(RestyleHint::RECASCADE_SELF)
     }
 
     /// Returns whether the hint specifies that an animation cascade level must
     /// be replaced.
     #[inline]
     pub fn has_animation_hint(&self) -> bool {
         self.intersects(Self::for_animations())
     }
 
     /// Returns whether the hint specifies that an animation cascade level must
     /// be replaced.
     #[inline]
     pub fn has_animation_hint_or_recascade(&self) -> bool {
-        self.intersects(Self::for_animations() | RECASCADE_SELF)
+        self.intersects(Self::for_animations() | RestyleHint::RECASCADE_SELF)
     }
 
     /// Returns whether the hint specifies some restyle work other than an
     /// animation cascade level replacement.
     #[inline]
     pub fn has_non_animation_hint(&self) -> bool {
         !(*self & !Self::for_animations()).is_empty()
     }
 
     /// Returns whether the hint specifies that selector matching must be re-run
     /// for the element.
     #[inline]
     pub fn match_self(&self) -> bool {
-        self.intersects(RESTYLE_SELF)
+        self.intersects(RestyleHint::RESTYLE_SELF)
     }
 
     /// Returns whether the hint specifies that some cascade levels must be
     /// replaced.
     #[inline]
     pub fn has_replacements(&self) -> bool {
         self.intersects(Self::replacements())
     }
@@ -172,17 +172,17 @@ impl RestyleHint {
         // process it during traversal.  If we are here, removing animation
         // hints, then we are in an animation-only traversal, and we know that
         // any RECASCADE_SELF flag must have been set due to changes in
         // inherited values after restyling for animations, and thus we want to
         // remove it so that we don't later try to restyle the element during a
         // normal restyle.  (We could have separate RECASCADE_SELF_NORMAL and
         // RECASCADE_SELF_ANIMATIONS flags to make it clear, but this isn't
         // currently necessary.)
-        self.remove(RECASCADE_SELF);
+        self.remove(RestyleHint::RECASCADE_SELF);
     }
 }
 
 impl Default for RestyleHint {
     fn default() -> Self {
         Self::empty()
     }
 }
@@ -199,33 +199,33 @@ impl From<nsRestyleHint> for RestyleHint
 
         let mut hint = RestyleHint::empty();
 
         debug_assert!(raw.0 & eRestyle_LaterSiblings.0 == 0,
                       "Handle later siblings manually if necessary plz.");
 
         if (raw.0 & (eRestyle_Self.0 | eRestyle_Subtree.0)) != 0 {
             raw.0 &= !eRestyle_Self.0;
-            hint.insert(RESTYLE_SELF);
+            hint.insert(RestyleHint::RESTYLE_SELF);
         }
 
         if (raw.0 & (eRestyle_Subtree.0 | eRestyle_SomeDescendants.0)) != 0 {
             raw.0 &= !eRestyle_Subtree.0;
             raw.0 &= !eRestyle_SomeDescendants.0;
-            hint.insert(RESTYLE_DESCENDANTS);
+            hint.insert(RestyleHint::RESTYLE_DESCENDANTS);
         }
 
         if (raw.0 & (eRestyle_ForceDescendants.0 | eRestyle_Force.0)) != 0 {
             raw.0 &= !eRestyle_Force.0;
-            hint.insert(RECASCADE_SELF);
+            hint.insert(RestyleHint::RECASCADE_SELF);
         }
 
         if (raw.0 & eRestyle_ForceDescendants.0) != 0 {
             raw.0 &= !eRestyle_ForceDescendants.0;
-            hint.insert(RECASCADE_DESCENDANTS);
+            hint.insert(RestyleHint::RECASCADE_DESCENDANTS);
         }
 
         hint.insert(RestyleHint::from_bits_truncate(raw.0 as u8));
 
         hint
     }
 }
 
@@ -234,29 +234,29 @@ malloc_size_of_is_0!(RestyleHint);
 
 /// Asserts that all replacement hints have a matching nsRestyleHint value.
 #[cfg(feature = "gecko")]
 #[inline]
 pub fn assert_restyle_hints_match() {
     use gecko_bindings::structs;
 
     macro_rules! check_restyle_hints {
-        ( $( $a:ident => $b:ident ),*, ) => {
+        ( $( $a:ident => $b:path),*, ) => {
             if cfg!(debug_assertions) {
                 let mut replacements = RestyleHint::replacements();
                 $(
                     assert_eq!(structs::$a.0 as usize, $b.bits() as usize, stringify!($b));
                     replacements.remove($b);
                 )*
                 assert_eq!(replacements, RestyleHint::empty(),
                            "all RestyleHint replacement bits should have an \
                             assertion");
             }
         }
     }
 
     check_restyle_hints! {
-        nsRestyleHint_eRestyle_CSSTransitions => RESTYLE_CSS_TRANSITIONS,
-        nsRestyleHint_eRestyle_CSSAnimations => RESTYLE_CSS_ANIMATIONS,
-        nsRestyleHint_eRestyle_StyleAttribute => RESTYLE_STYLE_ATTRIBUTE,
-        nsRestyleHint_eRestyle_StyleAttribute_Animations => RESTYLE_SMIL,
+        nsRestyleHint_eRestyle_CSSTransitions => RestyleHint::RESTYLE_CSS_TRANSITIONS,
+        nsRestyleHint_eRestyle_CSSAnimations => RestyleHint::RESTYLE_CSS_ANIMATIONS,
+        nsRestyleHint_eRestyle_StyleAttribute => RestyleHint::RESTYLE_STYLE_ATTRIBUTE,
+        nsRestyleHint_eRestyle_StyleAttribute_Animations => RestyleHint::RESTYLE_SMIL,
     }
 }
--- a/servo/components/style/invalidation/stylesheets.rs
+++ b/servo/components/style/invalidation/stylesheets.rs
@@ -6,17 +6,17 @@
 //! document.
 
 #![deny(unsafe_code)]
 
 use Atom;
 use LocalName as SelectorLocalName;
 use dom::{TElement, TNode};
 use fnv::FnvHashSet;
-use invalidation::element::restyle_hints::{RESTYLE_SELF, RestyleHint};
+use invalidation::element::restyle_hints::RestyleHint;
 use media_queries::Device;
 use selector_parser::SelectorImpl;
 use selectors::attr::CaseSensitivity;
 use selectors::parser::{Component, LocalName, Selector};
 use shared_lock::SharedRwLockReadGuard;
 use stylesheets::{CssRule, StylesheetInDocument};
 
 /// A style sheet invalidation represents a kind of element or subtree that may
@@ -218,22 +218,22 @@ impl StylesheetInvalidationSet {
                        element, invalidation);
                 data.hint.insert(RestyleHint::restyle_subtree());
                 return true;
             }
         }
 
         let mut self_invalid = false;
 
-        if !data.hint.contains(RESTYLE_SELF) {
+        if !data.hint.contains(RestyleHint::RESTYLE_SELF) {
             for invalidation in &self.invalid_elements {
                 if invalidation.matches(element) {
                     debug!("process_invalidations_in_subtree: {:?} matched self {:?}",
                            element, invalidation);
-                    data.hint.insert(RESTYLE_SELF);
+                    data.hint.insert(RestyleHint::RESTYLE_SELF);
                     self_invalid = true;
                     break;
                 }
             }
         }
 
         let mut any_children_invalid = false;
 
--- a/servo/components/style/logical_geometry.rs
+++ b/servo/components/style/logical_geometry.rs
@@ -20,61 +20,61 @@ pub enum BlockFlowDirection {
 pub enum InlineBaseDirection {
     LeftToRight,
     RightToLeft
 }
 
 // TODO: improve the readability of the WritingMode serialization, refer to the Debug:fmt()
 bitflags!(
     #[cfg_attr(feature = "servo", derive(MallocSizeOf, Serialize))]
-    pub flags WritingMode: u8 {
-        const FLAG_RTL = 1 << 0,
-        const FLAG_VERTICAL = 1 << 1,
-        const FLAG_VERTICAL_LR = 1 << 2,
+    pub struct WritingMode: u8 {
+        const RTL = 1 << 0;
+        const VERTICAL = 1 << 1;
+        const VERTICAL_LR = 1 << 2;
         /// For vertical writing modes only.  When set, line-over/line-under
         /// sides are inverted from block-start/block-end.  This flag is
         /// set when sideways-lr is used.
-        const FLAG_LINE_INVERTED = 1 << 3,
-        const FLAG_SIDEWAYS = 1 << 4,
-        const FLAG_UPRIGHT = 1 << 5,
+        const LINE_INVERTED = 1 << 3;
+        const SIDEWAYS = 1 << 4;
+        const UPRIGHT = 1 << 5;
     }
 );
 
 impl WritingMode {
     #[inline]
     pub fn is_vertical(&self) -> bool {
-        self.intersects(FLAG_VERTICAL)
+        self.intersects(WritingMode::VERTICAL)
     }
 
     /// Assuming .is_vertical(), does the block direction go left to right?
     #[inline]
     pub fn is_vertical_lr(&self) -> bool {
-        self.intersects(FLAG_VERTICAL_LR)
+        self.intersects(WritingMode::VERTICAL_LR)
     }
 
     /// Assuming .is_vertical(), does the inline direction go top to bottom?
     #[inline]
     pub fn is_inline_tb(&self) -> bool {
         // https://drafts.csswg.org/css-writing-modes-3/#logical-to-physical
-        self.intersects(FLAG_RTL) == self.intersects(FLAG_LINE_INVERTED)
+        self.intersects(WritingMode::RTL) == self.intersects(WritingMode::LINE_INVERTED)
     }
 
     #[inline]
     pub fn is_bidi_ltr(&self) -> bool {
-        !self.intersects(FLAG_RTL)
+        !self.intersects(WritingMode::RTL)
     }
 
     #[inline]
     pub fn is_sideways(&self) -> bool {
-        self.intersects(FLAG_SIDEWAYS)
+        self.intersects(WritingMode::SIDEWAYS)
     }
 
     #[inline]
     pub fn is_upright(&self) -> bool {
-        self.intersects(FLAG_UPRIGHT)
+        self.intersects(WritingMode::UPRIGHT)
     }
 
     #[inline]
     pub fn inline_start_physical_side(&self) -> PhysicalSide {
         match (self.is_vertical(), self.is_inline_tb(), self.is_bidi_ltr()) {
             (false, _, true) => PhysicalSide::Left,
             (false, _, false) => PhysicalSide::Right,
             (true, true, _) => PhysicalSide::Top,
@@ -116,17 +116,17 @@ impl WritingMode {
             (false, _) => BlockFlowDirection::TopToBottom,
             (true, true) => BlockFlowDirection::LeftToRight,
             (true, false) => BlockFlowDirection::RightToLeft,
         }
     }
 
     #[inline]
     pub fn inline_base_direction(&self) -> InlineBaseDirection {
-        if self.intersects(FLAG_RTL) {
+        if self.intersects(WritingMode::RTL) {
             InlineBaseDirection::RightToLeft
         } else {
             InlineBaseDirection::LeftToRight
         }
     }
 
     #[inline]
     /// The default bidirectional embedding level for this writing mode.
@@ -145,20 +145,20 @@ impl fmt::Display for WritingMode {
     fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
         if self.is_vertical() {
             write!(formatter, "V")?;
             if self.is_vertical_lr() {
                 write!(formatter, " LR")?;
             } else {
                 write!(formatter, " RL")?;
             }
-            if self.intersects(FLAG_SIDEWAYS) {
+            if self.intersects(WritingMode::SIDEWAYS) {
                 write!(formatter, " Sideways")?;
             }
-            if self.intersects(FLAG_LINE_INVERTED) {
+            if self.intersects(WritingMode::LINE_INVERTED) {
                 write!(formatter, " Inverted")?;
             }
         } else {
             write!(formatter, "H")?;
         }
         if self.is_bidi_ltr() {
             write!(formatter, " LTR")
         } else {
--- a/servo/components/style/matching.rs
+++ b/servo/components/style/matching.rs
@@ -6,26 +6,24 @@
 
 #![allow(unsafe_code)]
 #![deny(missing_docs)]
 
 use context::{ElementCascadeInputs, QuirksMode, SelectorFlagsMap};
 use context::{SharedStyleContext, StyleContext};
 use data::ElementData;
 use dom::TElement;
-use invalidation::element::restyle_hints::{RESTYLE_CSS_ANIMATIONS, RESTYLE_CSS_TRANSITIONS};
-use invalidation::element::restyle_hints::{RESTYLE_SMIL, RESTYLE_STYLE_ATTRIBUTE};
 use invalidation::element::restyle_hints::RestyleHint;
 use properties::ComputedValues;
 use rule_tree::{CascadeLevel, StrongRuleNode};
 use selector_parser::{PseudoElement, RestyleDamage};
 use selectors::matching::ElementSelectorFlags;
 use servo_arc::{Arc, ArcBorrow};
 use style_resolver::ResolvedElementStyles;
-use traversal_flags;
+use traversal_flags::TraversalFlags;
 
 /// Represents the result of comparing an element's old and new style.
 #[derive(Debug)]
 pub struct StyleDifference {
     /// The resulting damage.
     pub damage: RestyleDamage,
 
     /// Whether any styles changed.
@@ -156,17 +154,17 @@ trait PrivateMatchMethods: TElement {
             let new_display_style = new_box_style.clone_display();
 
             // If the traverse is triggered by CSS rule changes, we need to
             // try to update all CSS animations on the element if the element
             // has or will have CSS animation style regardless of whether the
             // animation is running or not.
             // TODO: We should check which @keyframes changed/added/deleted
             // and update only animations corresponding to those @keyframes.
-            (context.shared.traversal_flags.contains(traversal_flags::ForCSSRuleChanges) &&
+            (context.shared.traversal_flags.contains(TraversalFlags::ForCSSRuleChanges) &&
              (has_new_animation_style || has_animations)) ||
             !old_box_style.animations_equals(new_box_style) ||
              (old_display_style == display::T::none &&
               new_display_style != display::T::none &&
               has_new_animation_style) ||
              (old_display_style != display::T::none &&
               new_display_style == display::T::none &&
               has_animations)
@@ -178,20 +176,20 @@ trait PrivateMatchMethods: TElement {
     #[cfg(feature = "gecko")]
     fn handle_display_change_for_smil_if_needed(
         &self,
         context: &mut StyleContext<Self>,
         old_values: Option<&ComputedValues>,
         new_values: &ComputedValues,
         restyle_hints: RestyleHint
     ) {
-        use context::DISPLAY_CHANGED_FROM_NONE_FOR_SMIL;
+        use context::PostAnimationTasks;
         use properties::longhands::display::computed_value as display;
 
-        if !restyle_hints.intersects(RESTYLE_SMIL) {
+        if !restyle_hints.intersects(RestyleHint::RESTYLE_SMIL) {
             return;
         }
 
         let display_changed_from_none = old_values.map_or(false, |old| {
             let old_display_style = old.get_box().clone_display();
             let new_display_style = new_values.get_box().clone_display();
             old_display_style == display::T::none &&
             new_display_style != display::T::none
@@ -201,30 +199,29 @@ trait PrivateMatchMethods: TElement {
             // When display value is changed from none to other, we need to
             // traverse descendant elements in a subsequent normal
             // traversal (we can't traverse them in this animation-only restyle
             // since we have no way to know whether the decendants
             // need to be traversed at the beginning of the animation-only
             // restyle).
             let task = ::context::SequentialTask::process_post_animation(
                 *self,
-                DISPLAY_CHANGED_FROM_NONE_FOR_SMIL,
+                PostAnimationTasks::DISPLAY_CHANGED_FROM_NONE_FOR_SMIL,
             );
             context.thread_local.tasks.push(task);
         }
     }
 
     #[cfg(feature = "gecko")]
     fn process_animations(&self,
                           context: &mut StyleContext<Self>,
                           old_values: &mut Option<Arc<ComputedValues>>,
                           new_values: &mut Arc<ComputedValues>,
                           restyle_hint: RestyleHint,
                           important_rules_changed: bool) {
-        use context::{CASCADE_RESULTS, CSS_ANIMATIONS, CSS_TRANSITIONS, EFFECT_PROPERTIES};
         use context::UpdateAnimationsTasks;
 
         if context.shared.traversal_flags.for_animation_only() {
             self.handle_display_change_for_smil_if_needed(
                 context,
                 old_values.as_ref().map(|v| &**v),
                 new_values,
                 restyle_hint,
@@ -232,17 +229,17 @@ trait PrivateMatchMethods: TElement {
             return;
         }
 
         // Bug 868975: These steps should examine and update the visited styles
         // in addition to the unvisited styles.
 
         let mut tasks = UpdateAnimationsTasks::empty();
         if self.needs_animations_update(context, old_values.as_ref(), new_values) {
-            tasks.insert(CSS_ANIMATIONS);
+            tasks.insert(UpdateAnimationsTasks::CSS_ANIMATIONS);
         }
 
         let before_change_style = if self.might_need_transitions_update(old_values.as_ref().map(|s| &**s),
                                                                         new_values) {
             let after_change_style = if self.has_css_transitions() {
                 self.get_after_change_style(context, new_values)
             } else {
                 None
@@ -260,31 +257,31 @@ trait PrivateMatchMethods: TElement {
                 self.needs_transitions_update(old_values.as_ref().unwrap(),
                                               after_change_style_ref)
             };
 
             if needs_transitions_update {
                 if let Some(values_without_transitions) = after_change_style {
                     *new_values = values_without_transitions;
                 }
-                tasks.insert(CSS_TRANSITIONS);
+                tasks.insert(UpdateAnimationsTasks::CSS_TRANSITIONS);
 
                 // We need to clone old_values into SequentialTask, so we can use it later.
                 old_values.clone()
             } else {
                 None
             }
         } else {
             None
         };
 
         if self.has_animations() {
-            tasks.insert(EFFECT_PROPERTIES);
+            tasks.insert(UpdateAnimationsTasks::EFFECT_PROPERTIES);
             if important_rules_changed {
-                tasks.insert(CASCADE_RESULTS);
+                tasks.insert(UpdateAnimationsTasks::CASCADE_RESULTS);
             }
         }
 
         if !tasks.is_empty() {
             let task = ::context::SequentialTask::update_animations(*self,
                                                                     before_change_style,
                                                                     tasks);
             context.thread_local.tasks.push(task);
@@ -340,17 +337,17 @@ trait PrivateMatchMethods: TElement {
         damage: &mut RestyleDamage,
         old_values: &ComputedValues,
         new_values: &ComputedValues,
         pseudo: Option<&PseudoElement>,
     ) -> ChildCascadeRequirement {
         debug!("accumulate_damage_for: {:?}", self);
 
         // Don't accumulate damage if we're in a forgetful traversal.
-        if shared_context.traversal_flags.contains(traversal_flags::Forgetful) {
+        if shared_context.traversal_flags.contains(TraversalFlags::Forgetful) {
             debug!(" > forgetful traversal");
             return ChildCascadeRequirement::MustCascadeChildren;
         }
 
         let difference =
             self.compute_style_difference(old_values, new_values, pseudo);
 
         if !skip_applying_damage {
@@ -396,28 +393,28 @@ trait PrivateMatchMethods: TElement {
 
                 // Children with justify-items: auto may depend on our
                 // justify-items property value.
                 //
                 // Similarly, we could potentially do better, but this really
                 // seems not common enough to care about.
                 #[cfg(feature = "gecko")]
                 {
-                    use values::specified::align;
+                    use values::specified::align::AlignFlags;
 
                     let old_justify_items =
                         old_values.get_position().clone_justify_items();
                     let new_justify_items =
                         new_values.get_position().clone_justify_items();
 
                     let was_legacy_justify_items =
-                        old_justify_items.computed.0.contains(align::ALIGN_LEGACY);
+                        old_justify_items.computed.0.contains(AlignFlags::LEGACY);
 
                     let is_legacy_justify_items =
-                        new_justify_items.computed.0.contains(align::ALIGN_LEGACY);
+                        new_justify_items.computed.0.contains(AlignFlags::LEGACY);
 
                     if is_legacy_justify_items != was_legacy_justify_items {
                         return ChildCascadeRequirement::MustCascadeChildren;
                     }
 
                     if was_legacy_justify_items &&
                         old_justify_items.computed != new_justify_items.computed {
                         return ChildCascadeRequirement::MustCascadeChildren;
@@ -579,17 +576,17 @@ pub trait MatchMethods : TElement {
 
                 // Needed for the "inherit from body" quirk.
                 let text_color = new_primary_style.get_color().clone_color();
                 device.set_body_text_color(text_color);
             }
         }
 
         // Don't accumulate damage if we're in a forgetful traversal.
-        if context.shared.traversal_flags.contains(traversal_flags::Forgetful) {
+        if context.shared.traversal_flags.contains(TraversalFlags::Forgetful) {
             return ChildCascadeRequirement::MustCascadeChildren;
         }
 
         // Also, don't do anything if there was no style.
         let old_primary_style = match old_styles.primary {
             Some(s) => s,
             None => return ChildCascadeRequirement::MustCascadeChildren,
         };
@@ -763,17 +760,17 @@ pub trait MatchMethods : TElement {
             if let Some(n) = new_node {
                 *path = n;
             }
             important_rules_changed
         };
 
         if !context.shared.traversal_flags.for_animation_only() {
             let mut result = false;
-            if replacements.contains(RESTYLE_STYLE_ATTRIBUTE) {
+            if replacements.contains(RestyleHint::RESTYLE_STYLE_ATTRIBUTE) {
                 let style_attribute = self.style_attribute();
                 result |= replace_rule_node(CascadeLevel::StyleAttributeNormal,
                                             style_attribute,
                                             primary_rules);
                 result |= replace_rule_node(CascadeLevel::StyleAttributeImportant,
                                             style_attribute,
                                             primary_rules);
                 // FIXME(emilio): Still a hack!
@@ -785,38 +782,38 @@ pub trait MatchMethods : TElement {
         // Animation restyle hints are processed prior to other restyle
         // hints in the animation-only traversal.
         //
         // Non-animation restyle hints will be processed in a subsequent
         // normal traversal.
         if replacements.intersects(RestyleHint::for_animations()) {
             debug_assert!(context.shared.traversal_flags.for_animation_only());
 
-            if replacements.contains(RESTYLE_SMIL) {
+            if replacements.contains(RestyleHint::RESTYLE_SMIL) {