Skip to main content

style/stylesheets/
layer_rule.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! A [`@layer`][layer] rule.
6//!
7//! [layer]: https://drafts.csswg.org/css-cascade-5/#layering
8
9use crate::derives::*;
10use crate::parser::{Parse, ParserContext};
11use crate::shared_lock::{DeepCloneWithLock, Locked};
12use crate::shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
13use crate::values::AtomIdent;
14
15use super::CssRules;
16
17use cssparser::{Parser, SourceLocation, Token};
18use servo_arc::Arc;
19use smallvec::SmallVec;
20use std::fmt::{self, Write};
21use style_traits::{CssWriter, ParseError, ToCss};
22
23/// The order of a given layer. We use 16 bits so that we can pack LayerOrder
24/// and CascadeLevel in a single 32-bit struct. If we need more bits we can go
25/// back to packing CascadeLevel in a single byte as we did before.
26#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, PartialEq, PartialOrd, Ord)]
27pub struct LayerOrder(u16);
28
29impl LayerOrder {
30    /// The order of the root layer.
31    pub const fn root() -> Self {
32        Self(u16::MAX - 1)
33    }
34
35    /// The order of the style attribute layer.
36    pub const fn style_attribute() -> Self {
37        Self(u16::MAX)
38    }
39
40    /// Returns whether this layer is for the style attribute, which behaves
41    /// differently in terms of !important, see
42    /// https://github.com/w3c/csswg-drafts/issues/6872
43    ///
44    /// (This is a bit silly, mind-you, but it's needed so that revert-layer
45    /// behaves correctly).
46    #[inline]
47    pub fn is_style_attribute_layer(&self) -> bool {
48        *self == Self::style_attribute()
49    }
50
51    /// The first cascade layer order.
52    pub const fn first() -> Self {
53        Self(0)
54    }
55
56    /// Increment the cascade layer order.
57    #[inline]
58    pub fn inc(&mut self) {
59        if self.0 != u16::MAX - 1 {
60            self.0 += 1;
61        }
62    }
63}
64
65/// A `<layer-name>`: https://drafts.csswg.org/css-cascade-5/#typedef-layer-name
66#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToShmem)]
67pub struct LayerName(pub SmallVec<[AtomIdent; 1]>);
68
69impl LayerName {
70    /// Returns an empty layer name (which isn't a valid final state, so caller
71    /// is responsible to fill up the name before use).
72    pub fn new_empty() -> Self {
73        Self(Default::default())
74    }
75
76    /// Returns a synthesized name for an anonymous layer.
77    pub fn new_anonymous() -> Self {
78        use std::sync::atomic::{AtomicUsize, Ordering};
79        static NEXT_ANONYMOUS_LAYER_NAME: AtomicUsize = AtomicUsize::new(0);
80
81        let mut name = SmallVec::new();
82        let next_id = NEXT_ANONYMOUS_LAYER_NAME.fetch_add(1, Ordering::Relaxed);
83        // The parens don't _technically_ prevent conflicts with authors, as
84        // authors could write escaped parens as part of the identifier, I
85        // think, but highly reduces the possibility.
86        name.push(AtomIdent::from(&*format!("-moz-anon-layer({})", next_id)));
87
88        LayerName(name)
89    }
90
91    /// Returns the names of the layers. That is, for a layer like `foo.bar`,
92    /// it'd return [foo, bar].
93    pub fn layer_names(&self) -> &[AtomIdent] {
94        &self.0
95    }
96}
97
98impl Parse for LayerName {
99    fn parse(_: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
100        let mut result = SmallVec::new();
101        result.push(AtomIdent::from(&**input.expect_ident()?));
102        loop {
103            let next_name = input.try_parse(|input| -> Result<AtomIdent, ParseError> {
104                match input.next_including_whitespace()? {
105                    Token::Delim('.') => {},
106                    other => {
107                        let _ = other.clone();
108                        return Err(ParseError::unexpected_token());
109                    },
110                }
111
112                let name = match input.next_including_whitespace()? {
113                    Token::Ident(ident) => ident,
114                    other => {
115                        let _ = other.clone();
116                        return Err(ParseError::unexpected_token());
117                    },
118                };
119
120                Ok(AtomIdent::from(&**name))
121            });
122
123            match next_name {
124                Ok(name) => result.push(name),
125                Err(..) => break,
126            }
127        }
128        Ok(LayerName(result))
129    }
130}
131
132impl ToCss for LayerName {
133    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
134    where
135        W: Write,
136    {
137        let mut first = true;
138        for name in self.0.iter() {
139            if !first {
140                dest.write_char('.')?;
141            }
142            first = false;
143            name.to_css(dest)?;
144        }
145        Ok(())
146    }
147}
148
149#[derive(Debug, ToShmem)]
150/// A block `@layer <name>? { ... }`
151/// https://drafts.csswg.org/css-cascade-5/#layer-block
152pub struct LayerBlockRule {
153    /// The layer name, or `None` if anonymous.
154    pub name: Option<LayerName>,
155    /// The nested rules.
156    pub rules: Arc<Locked<CssRules>>,
157    /// The source position where this rule was found.
158    pub source_location: SourceLocation,
159}
160
161impl ToCssWithGuard for LayerBlockRule {
162    fn to_css(
163        &self,
164        guard: &SharedRwLockReadGuard,
165        dest: &mut style_traits::CssStringWriter,
166    ) -> fmt::Result {
167        dest.write_str("@layer")?;
168        if let Some(ref name) = self.name {
169            dest.write_char(' ')?;
170            name.to_css(&mut CssWriter::new(dest))?;
171        }
172        self.rules.read_with(guard).to_css_block(guard, dest)
173    }
174}
175
176impl DeepCloneWithLock for LayerBlockRule {
177    fn deep_clone_with_lock(&self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard) -> Self {
178        Self {
179            name: self.name.clone(),
180            rules: Arc::new(
181                lock.wrap(
182                    self.rules
183                        .read_with(guard)
184                        .deep_clone_with_lock(lock, guard),
185                ),
186            ),
187            source_location: self.source_location,
188        }
189    }
190}
191
192/// A statement `@layer <name>, <name>, <name>;`
193///
194/// https://drafts.csswg.org/css-cascade-5/#layer-empty
195#[derive(Clone, Debug, ToShmem)]
196pub struct LayerStatementRule {
197    /// The list of layers to sort.
198    pub names: Vec<LayerName>,
199    /// The source position where this rule was found.
200    pub source_location: SourceLocation,
201}
202
203impl ToCssWithGuard for LayerStatementRule {
204    fn to_css(
205        &self,
206        _: &SharedRwLockReadGuard,
207        dest: &mut style_traits::CssStringWriter,
208    ) -> fmt::Result {
209        let mut writer = CssWriter::new(dest);
210        writer.write_str("@layer ")?;
211        let mut first = true;
212        for name in &*self.names {
213            if !first {
214                writer.write_str(", ")?;
215            }
216            first = false;
217            name.to_css(&mut writer)?;
218        }
219        writer.write_char(';')
220    }
221}