1use std::collections::HashMap;
25use std::fmt::{self, Write};
26use std::sync::{Mutex, OnceLock};
27
28use crate::media::{Comparison, Condition, Environment, Feature, MediaQueryList, QueryLengths};
29use crate::parser::{AtRule, Block, Bracket, ComponentValue, Item};
30use crate::serialize::{write_identifier, write_string};
31use crate::tokenizer::Token;
32use crate::values::{Component, Grammar, Leaf, Specified, Unit};
33
34fn trimmed<'v, 'a>(values: &'v [ComponentValue<'a>]) -> &'v [ComponentValue<'a>] {
35 let start = values
36 .iter()
37 .position(|v| !v.is_whitespace())
38 .unwrap_or(values.len());
39 let end = values
40 .iter()
41 .rposition(|v| !v.is_whitespace())
42 .map_or(start, |i| i + 1);
43 &values[start..end]
44}
45
46fn text(values: &[ComponentValue<'_>]) -> String {
47 crate::to_css(trimmed(values))
48}
49
50fn written(c: Vec<Component<'_>>) -> String {
51 Specified::Value(c).to_string()
52}
53
54const CSS_WIDE: &[&str] = &[
55 "initial",
56 "inherit",
57 "unset",
58 "revert",
59 "revert-layer",
60 "revert-rule",
61 "default",
62];
63
64fn write_name(out: &mut impl Write, name: &str) -> fmt::Result {
66 write_identifier(out, name)
67}
68
69fn declarations<'b>(
72 block: &'b Block<'_>,
73) -> impl Iterator<Item = (&'b str, &'b [ComponentValue<'b>], bool)> {
74 block.items.iter().filter_map(|i| match i {
75 Item::Declaration(d) => Some((&*d.name, &d.value[..], d.important)),
76 _ => None,
77 })
78}
79
80#[derive(Clone, Debug, PartialEq)]
84pub struct Keyframes {
85 pub name: String,
86 pub frames: Vec<Keyframe>,
87}
88
89#[derive(Clone, Debug, PartialEq)]
92pub struct Keyframe {
93 pub offsets: Vec<KeyframeOffset>,
94 pub declarations: Vec<(String, String)>,
96}
97
98#[derive(Clone, Debug, PartialEq)]
101pub enum KeyframeOffset {
102 Percent(f64),
103 Range(String, f64),
104}
105
106const RANGE_NAMES: &[&str] = &[
107 "cover",
108 "contain",
109 "entry",
110 "exit",
111 "entry-crossing",
112 "exit-crossing",
113 "scroll",
114];
115
116impl Keyframes {
117 pub fn parse(rule: &AtRule<'_, Block<'_>>) -> Option<Keyframes> {
120 let name = rule.name.to_ascii_lowercase();
121 if !matches!(name.as_str(), "keyframes" | "-webkit-keyframes") {
122 return None;
123 }
124 let name = match trimmed(&rule.prelude) {
125 [ComponentValue::Token(Token::Ident(n), _)]
126 if !n.eq_ignore_ascii_case("none")
127 && !CSS_WIDE.iter().any(|w| n.eq_ignore_ascii_case(w)) =>
128 {
129 n.to_string()
130 }
131 [ComponentValue::Token(Token::String(s), _)] if !s.is_empty() => s.to_string(),
132 _ => return None,
133 };
134 let mut frames = Vec::new();
135 for item in &rule.block.as_ref()?.items {
136 let Item::Rule(crate::Rule::Qualified(q)) = item else {
137 continue;
138 };
139 let Some(offsets) = keyframe_offsets(&q.prelude) else {
140 continue;
141 };
142 let declarations = declarations(&q.block)
143 .filter(|(_, _, important)| !important)
144 .map(|(n, v, _)| (n.to_string(), text(v)))
145 .collect();
146 frames.push(Keyframe {
147 offsets,
148 declarations,
149 });
150 }
151 Some(Keyframes { name, frames })
152 }
153}
154
155fn keyframe_offsets(prelude: &[ComponentValue<'_>]) -> Option<Vec<KeyframeOffset>> {
156 let mut out = Vec::new();
157 for part in prelude.split(|v| matches!(v, ComponentValue::Token(Token::Comma, _))) {
158 let words: Vec<&ComponentValue<'_>> = part.iter().filter(|v| !v.is_whitespace()).collect();
159 let percent = |v: &ComponentValue<'_>| match v {
160 ComponentValue::Token(Token::Percentage(n), _) => Some(n.value),
161 _ => None,
162 };
163 out.push(match words[..] {
164 [ComponentValue::Token(Token::Ident(w), _)] if w.eq_ignore_ascii_case("from") => {
165 KeyframeOffset::Percent(0.0)
166 }
167 [ComponentValue::Token(Token::Ident(w), _)] if w.eq_ignore_ascii_case("to") => {
168 KeyframeOffset::Percent(100.0)
169 }
170 [v] => {
171 let p = percent(v)?;
172 if !(0.0..=100.0).contains(&p) {
173 return None;
174 }
175 KeyframeOffset::Percent(p)
176 }
177 [ComponentValue::Token(Token::Ident(w), _), v] => {
178 let name = RANGE_NAMES.iter().find(|n| w.eq_ignore_ascii_case(n))?;
179 KeyframeOffset::Range(name.to_string(), percent(v)?)
180 }
181 _ => return None,
182 });
183 }
184 Some(out)
185}
186
187impl fmt::Display for KeyframeOffset {
188 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189 match self {
190 KeyframeOffset::Percent(p) => {
191 crate::values::write_number(f, *p)?;
192 f.write_char('%')
193 }
194 KeyframeOffset::Range(n, p) => {
195 write!(f, "{n} ")?;
196 crate::values::write_number(f, *p)?;
197 f.write_char('%')
198 }
199 }
200 }
201}
202
203impl fmt::Display for Keyframes {
204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 f.write_str("@keyframes ")?;
206 write_name(f, &self.name)?;
207 f.write_str(" {")?;
208 for k in &self.frames {
209 f.write_str(" ")?;
210 for (i, o) in k.offsets.iter().enumerate() {
211 if i > 0 {
212 f.write_str(", ")?;
213 }
214 write!(f, "{o}")?;
215 }
216 f.write_str(" {")?;
217 for (n, v) in &k.declarations {
218 write!(f, " {n}: {v};")?;
219 }
220 f.write_str(" }")?;
221 }
222 f.write_str(" }")
223 }
224}
225
226fn grammar(src: &'static str) -> &'static Grammar {
230 static ALL: OnceLock<Mutex<HashMap<&'static str, &'static Grammar>>> = OnceLock::new();
231 let all = ALL.get_or_init(Default::default);
232 let mut all = all.lock().unwrap_or_else(|e| e.into_inner());
233 all.entry(src)
236 .or_insert_with(|| Box::leak(Box::new(Grammar::parse(src).expect(src))))
237}
238
239fn descriptor(src: &'static str, value: &[ComponentValue<'_>]) -> Option<String> {
241 crate::values::match_grammar(grammar(src), value).map(written)
242}
243
244#[derive(Clone, Debug, PartialEq)]
250pub struct CounterStyle {
251 pub name: String,
252 pub descriptors: Vec<(&'static str, String)>,
253}
254
255const COUNTER_DESCRIPTORS: &[(&str, &str)] = &[
257 (
258 "system",
259 "cyclic | numeric | alphabetic | symbolic | additive | [ fixed <integer>? ] | [ extends <counter-style-name> ]",
260 ),
261 ("symbols", "[ <string> | <image> | <custom-ident> ]+"),
262 (
263 "additive-symbols",
264 "[ <integer [0,โ]> && [ <string> | <image> | <custom-ident> ] ]#",
265 ),
266 (
267 "negative",
268 "[ <string> | <image> | <custom-ident> ] [ <string> | <image> | <custom-ident> ]?",
269 ),
270 ("prefix", "[ <string> | <image> | <custom-ident> ]"),
271 ("suffix", "[ <string> | <image> | <custom-ident> ]"),
272 ("range", "[ [ <integer> | infinite ]{2} ]# | auto"),
273 (
274 "pad",
275 "<integer [0,โ]> && [ <string> | <image> | <custom-ident> ]",
276 ),
277 ("fallback", "<counter-style-name>"),
278 (
279 "speak-as",
280 "auto | bullets | numbers | words | spell-out | <counter-style-name>",
281 ),
282];
283
284const FIXED_STYLES: &[&str] = &[
287 "none",
288 "decimal",
289 "disc",
290 "square",
291 "circle",
292 "disclosure-open",
293 "disclosure-closed",
294];
295
296impl CounterStyle {
297 pub fn parse(rule: &AtRule<'_, Block<'_>>) -> Option<CounterStyle> {
300 if !rule.name.eq_ignore_ascii_case("counter-style") {
301 return None;
302 }
303 let [ComponentValue::Token(Token::Ident(name), _)] = trimmed(&rule.prelude) else {
304 return None;
305 };
306 if CSS_WIDE
307 .iter()
308 .chain(FIXED_STYLES)
309 .any(|w| name.eq_ignore_ascii_case(w))
310 {
311 return None;
312 }
313 let mut found: Vec<Option<String>> = vec![None; COUNTER_DESCRIPTORS.len()];
314 for (n, value, _) in declarations(rule.block.as_ref()?) {
315 let Some(i) = COUNTER_DESCRIPTORS
316 .iter()
317 .position(|(d, _)| n.eq_ignore_ascii_case(d))
318 else {
319 continue;
320 };
321 let (d, g) = COUNTER_DESCRIPTORS[i];
322 let Some(v) = descriptor(g, value) else {
323 continue;
324 };
325 if !counter_valid(d, value) {
326 continue;
327 }
328 found[i] = Some(v);
329 }
330 let descriptors = COUNTER_DESCRIPTORS
331 .iter()
332 .zip(found)
333 .filter_map(|((d, _), v)| Some((*d, v?)))
334 .collect();
335 Some(CounterStyle {
336 name: name.to_string(),
337 descriptors,
338 })
339 }
340
341 pub fn usable(&self) -> bool {
346 let system = self.get("system").unwrap_or("symbolic");
347 let symbols = self.get("symbols").map_or(0, |s| {
348 crate::parse_component_values(s)
349 .iter()
350 .filter(|v| !v.is_whitespace())
351 .count()
352 });
353 let additive = self.get("additive-symbols").is_some();
354 match system.split(' ').next().unwrap_or("") {
355 "cyclic" | "fixed" | "symbolic" => symbols >= 1,
356 "alphabetic" | "numeric" => symbols >= 2,
357 "additive" => additive,
358 "extends" => symbols == 0 && !additive,
359 _ => false,
360 }
361 }
362
363 pub fn get(&self, descriptor: &str) -> Option<&str> {
365 self.descriptors
366 .iter()
367 .find(|(d, _)| *d == descriptor)
368 .map(|(_, v)| v.as_str())
369 }
370}
371
372fn counter_valid(descriptor: &str, value: &[ComponentValue<'_>]) -> bool {
374 let numbers = || {
375 value.iter().filter_map(|v| match v {
376 ComponentValue::Token(Token::Number(n), _) => Some(n.value),
377 ComponentValue::Token(Token::Ident(w), _) if w.eq_ignore_ascii_case("infinite") => {
378 Some(f64::NAN)
379 }
380 _ => None,
381 })
382 };
383 let named_none = value.iter().any(|v| {
385 matches!(v, ComponentValue::Token(Token::Ident(w), _) if w.eq_ignore_ascii_case("none"))
386 });
387 match descriptor {
388 "system" | "fallback" => !named_none,
389 "range" => {
391 let n: Vec<f64> = numbers().collect();
392 n.chunks(2).all(|r| match r {
393 [a, b] => a.is_nan() || b.is_nan() || a <= b,
394 _ => true,
395 })
396 }
397 "additive-symbols" => {
399 let n: Vec<f64> = numbers().collect();
400 n.windows(2).all(|w| w[0] > w[1])
401 }
402 _ => true,
403 }
404}
405
406impl fmt::Display for CounterStyle {
407 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
408 f.write_str("@counter-style ")?;
409 write_name(f, &self.name)?;
410 f.write_str(" {")?;
411 for (d, v) in &self.descriptors {
412 write!(f, " {d}: {v};")?;
413 }
414 f.write_str(" }")
415 }
416}
417
418#[derive(Clone, Debug, PartialEq)]
426pub struct PropertyRule {
427 pub name: String,
428 pub syntax: String,
430 pub inherits: bool,
431 pub initial_value: Option<String>,
433}
434
435const SYNTAX_TYPES: &[&str] = &[
437 "angle",
438 "color",
439 "custom-ident",
440 "image",
441 "integer",
442 "length",
443 "length-percentage",
444 "number",
445 "percentage",
446 "resolution",
447 "string",
448 "time",
449 "transform-function",
450 "transform-list",
451 "url",
452];
453
454#[derive(Clone, Copy, Debug)]
457pub struct Syntax {
458 grammar: Option<&'static Grammar>,
459}
460
461const MAX_SYNTAXES: usize = 4096;
465
466impl Syntax {
467 pub fn parse(src: &str) -> Option<Syntax> {
469 let s = src.trim_matches(|c: char| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0c'));
470 if s == "*" {
471 return Some(Syntax { grammar: None });
472 }
473 let mut parts = Vec::new();
474 for part in s.split('|') {
475 let p = part.trim_matches(|c: char| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0c'));
476 let (body, multiplier) = match p.as_bytes().last() {
477 Some(b'+') => (&p[..p.len() - 1], "+"),
478 Some(b'#') => (&p[..p.len() - 1], "#"),
479 _ => (p, ""),
480 };
481 if let Some(name) = body.strip_prefix('<').and_then(|b| b.strip_suffix('>')) {
482 if !SYNTAX_TYPES.contains(&name) {
483 return None;
484 }
485 if name == "transform-list" && !multiplier.is_empty() {
487 return None;
488 }
489 parts.push(format!("<{name}>{multiplier}"));
490 } else {
491 let ok = !body.is_empty()
493 && body.chars().all(|c| {
494 c.is_ascii_alphanumeric() || c == '-' || c == '_' || !c.is_ascii()
495 })
496 && !body.starts_with(|c: char| c.is_ascii_digit())
497 && !CSS_WIDE.iter().any(|w| body.eq_ignore_ascii_case(w));
498 if !ok {
499 return None;
500 }
501 parts.push(format!("{body}{multiplier}"));
502 }
503 }
504 let text = parts.join(" | ");
505 static ALL: OnceLock<Mutex<HashMap<String, &'static Grammar>>> = OnceLock::new();
506 let all = ALL.get_or_init(Default::default);
507 let mut all = all.lock().unwrap_or_else(|e| e.into_inner());
508 if let Some(g) = all.get(&text) {
509 return Some(Syntax { grammar: Some(g) });
510 }
511 if all.len() >= MAX_SYNTAXES {
514 return Some(Syntax { grammar: None });
515 }
516 let g: &'static Grammar = Box::leak(Box::new(Grammar::parse(&text)?));
517 all.insert(text, g);
518 Some(Syntax { grammar: Some(g) })
519 }
520
521 pub fn is_universal(&self) -> bool {
523 self.grammar.is_none()
524 }
525
526 pub fn parse_value<'a>(&self, values: &[ComponentValue<'a>]) -> Option<Vec<Component<'a>>> {
528 match self.grammar {
529 Some(g) => crate::values::match_grammar(g, values),
530 None => None,
531 }
532 }
533}
534
535fn independent(c: &[Component<'_>]) -> bool {
538 fn unit_ok(u: Unit) -> bool {
539 u.kind() != crate::values::Kind::Length || u.canonical().is_some()
540 }
541 fn node_ok(n: &crate::values::Node) -> bool {
542 use crate::values::{Leaf, Node};
543 match n {
544 Node::Value(Leaf::Dimension(_, u)) => unit_ok(*u),
545 Node::Value(_) | Node::Keyword(_) => true,
546 Node::Sum(c) | Node::Product(c) | Node::Function(_, c) => c.iter().all(node_ok),
547 Node::Negate(c) | Node::Invert(c) => node_ok(c),
548 }
549 }
550 c.iter().all(|x| match x {
551 Component::Dimension(_, u) => unit_ok(*u),
552 Component::Math(m) => node_ok(&m.root),
553 Component::Function { arguments, .. } => independent(arguments),
554 Component::Block(b) | Component::Parens(b) => independent(b),
555 _ => true,
556 })
557}
558
559impl PropertyRule {
560 pub fn parse(rule: &AtRule<'_, Block<'_>>) -> Option<PropertyRule> {
564 if !rule.name.eq_ignore_ascii_case("property") {
565 return None;
566 }
567 let [ComponentValue::Token(Token::Ident(name), _)] = trimmed(&rule.prelude) else {
568 return None;
569 };
570 if !name.starts_with("--") || name.len() < 3 {
571 return None;
572 }
573 let (mut syntax, mut inherits, mut initial) = (None, None, None);
574 for (n, value, _) in declarations(rule.block.as_ref()?) {
575 match n.to_ascii_lowercase().as_str() {
576 "syntax" => {
577 if let [ComponentValue::Token(Token::String(s), _)] = trimmed(value)
578 && Syntax::parse(s).is_some()
579 {
580 syntax = Some(s.to_string());
581 }
582 }
583 "inherits" => match trimmed(value) {
584 [ComponentValue::Token(Token::Ident(w), _)]
585 if w.eq_ignore_ascii_case("true") =>
586 {
587 inherits = Some(true)
588 }
589 [ComponentValue::Token(Token::Ident(w), _)]
590 if w.eq_ignore_ascii_case("false") =>
591 {
592 inherits = Some(false)
593 }
594 _ => {}
595 },
596 "initial-value" => initial = Some(value),
597 _ => {}
598 }
599 }
600 let syntax = syntax.unwrap_or_else(|| "*".to_string());
601 let inherits = inherits.unwrap_or(true);
602 let parsed = Syntax::parse(&syntax)?;
603 let initial_value = match initial {
604 Some(v) if parsed.is_universal() => Some(text(v)),
605 Some(v) => {
606 let c = parsed.parse_value(v)?;
607 if !independent(&c) || crate::values::has_substitution(v) {
608 return None;
609 }
610 Some(text(v))
611 }
612 None => None,
613 };
614 Some(PropertyRule {
615 name: name.to_string(),
616 syntax,
617 inherits,
618 initial_value,
619 })
620 }
621}
622
623impl PropertyRule {
624 pub fn registers(&self) -> bool {
627 self.initial_value.is_some()
628 || Syntax::parse(&self.syntax).is_some_and(|s| s.is_universal())
629 }
630}
631
632impl fmt::Display for PropertyRule {
633 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
634 f.write_str("@property ")?;
635 write_name(f, &self.name)?;
636 f.write_str(" { syntax: ")?;
637 write_string(f, &self.syntax)?;
638 write!(f, "; inherits: {};", self.inherits)?;
639 if let Some(v) = &self.initial_value {
640 write!(f, " initial-value: {v};")?;
641 }
642 f.write_str(" }")
643 }
644}
645
646#[derive(Clone, Debug, PartialEq)]
652pub struct ContainerQuery {
653 pub name: Option<String>,
654 pub condition: Option<Condition>,
656 styles: Vec<(String, StyleQuery)>,
659}
660
661#[derive(Clone, Debug, PartialEq)]
665pub enum StyleQuery {
666 Feature {
669 name: String,
670 value: Option<String>,
671 },
672 Range {
676 values: Vec<String>,
677 ops: Vec<Comparison>,
678 },
679 Not(Box<StyleQuery>),
680 And(Vec<StyleQuery>),
681 Or(Vec<StyleQuery>),
682 Unknown,
684}
685
686impl StyleQuery {
687 fn parse(values: &[ComponentValue<'_>], depth: usize) -> StyleQuery {
688 if depth > 32 {
689 return StyleQuery::Unknown;
690 }
691 let v = crate::media::solid(values);
692 let inner = |c: &ComponentValue<'_>| match c {
693 ComponentValue::Block(b) if b.bracket == Bracket::Paren => {
694 Some(StyleQuery::parse(&b.contents, depth + 1))
695 }
696 _ => None,
697 };
698 let word = |c: Option<&&ComponentValue<'_>>, w: &str| matches!(c, Some(ComponentValue::Token(Token::Ident(x), _)) if x.eq_ignore_ascii_case(w));
699 if word(v.first(), "not") {
700 return match (v.len(), v.get(1).and_then(|c| inner(c))) {
701 (2, Some(q)) => StyleQuery::Not(Box::new(q)),
702 _ => StyleQuery::Unknown,
703 };
704 }
705 if let Some(first) = v.first().and_then(|c| inner(c)) {
706 if v.len() == 1 {
707 return first;
708 }
709 let joiner = if word(v.get(1), "and") { "and" } else { "or" };
710 let mut items = vec![first];
711 let mut i = 1;
712 while i < v.len() {
713 match (word(v.get(i), joiner), v.get(i + 1).and_then(|c| inner(c))) {
714 (true, Some(q)) => items.push(q),
715 _ => return StyleQuery::Unknown,
716 }
717 i += 2;
718 }
719 return if joiner == "and" {
720 StyleQuery::And(items)
721 } else {
722 StyleQuery::Or(items)
723 };
724 }
725 if v.iter().any(|c| is_comparison(c)) {
726 return StyleQuery::range(&v);
727 }
728 if v.iter()
730 .any(|c| matches!(c, ComponentValue::Token(Token::Semicolon, _)))
731 {
732 return StyleQuery::Unknown;
733 }
734 let colon = values
736 .iter()
737 .position(|c| matches!(c, ComponentValue::Token(Token::Colon, _)));
738 let name_part = trimmed(&values[..colon.unwrap_or(values.len())]);
739 let [ComponentValue::Token(Token::Ident(name), _)] = name_part else {
740 return StyleQuery::Unknown;
741 };
742 let value = colon.map(|c| text(&values[c + 1..]));
743 StyleQuery::Feature {
744 name: name.to_string(),
745 value,
746 }
747 }
748
749 fn range(v: &[&ComponentValue<'_>]) -> StyleQuery {
752 let mut values = Vec::new();
753 let mut ops = Vec::new();
754 let mut start = 0;
755 let mut i = 0;
756 loop {
757 let end = i == v.len();
758 if !end && !is_comparison(v[i]) {
759 i += 1;
760 continue;
761 }
762 let part = &v[start..i];
763 let bad = part.iter().any(|c| {
765 matches!(
766 c,
767 ComponentValue::Token(Token::Delim('!') | Token::Semicolon | Token::Colon, _)
768 )
769 });
770 if part.is_empty() || bad || values.len() == 3 {
771 return StyleQuery::Unknown;
772 }
773 values.push(match part {
774 [ComponentValue::Token(Token::Ident(n), _)] if n.starts_with("--") => {
775 format!("var({n})")
776 }
777 _ => part
778 .iter()
779 .map(|c| crate::to_css(std::slice::from_ref(*c)))
780 .collect::<Vec<_>>()
781 .join(" "),
782 });
783 if end {
784 break;
785 }
786 let Some((op, n)) = crate::media::comparison(&v[i..]) else {
787 return StyleQuery::Unknown;
788 };
789 ops.push(op);
790 i += n;
791 start = i;
792 }
793 let lt = |o: &Comparison| matches!(o, Comparison::Lt | Comparison::Le);
794 let gt = |o: &Comparison| matches!(o, Comparison::Gt | Comparison::Ge);
795 let ok = match &ops[..] {
796 [_] => true,
797 [a, b] => lt(a) && lt(b) || gt(a) && gt(b),
798 _ => false,
799 };
800 if ok {
801 StyleQuery::Range { values, ops }
802 } else {
803 StyleQuery::Unknown
804 }
805 }
806
807 fn whole(&self) -> bool {
809 match self {
810 StyleQuery::Range { .. } => true,
811 StyleQuery::Feature { name, .. } => {
812 name.starts_with("--") || crate::values::property(name).is_some()
813 }
814 StyleQuery::Not(q) => q.whole(),
815 StyleQuery::And(qs) | StyleQuery::Or(qs) => qs.iter().all(StyleQuery::whole),
816 StyleQuery::Unknown => false,
817 }
818 }
819
820 fn evaluate(
821 &self,
822 get: &dyn Fn(&str) -> Option<String>,
823 number: &dyn Fn(&str) -> Option<Leaf>,
824 ) -> Option<bool> {
825 match self {
826 StyleQuery::Range { values, ops } => {
829 let mut leaves = Vec::with_capacity(values.len());
830 for v in values {
831 match number(v) {
832 Some(l) => leaves.push(l),
833 None => return Some(false),
834 }
835 }
836 Some(
837 ops.iter()
838 .zip(leaves.windows(2))
839 .all(|(op, w)| compare(w[0], *op, w[1])),
840 )
841 }
842 StyleQuery::Feature { name, value } => {
843 if !name.starts_with("--") {
844 return None;
845 }
846 let have = get(name).filter(|v| !v.is_empty());
847 Some(match value {
848 None => have.is_some(),
849 Some(v) => {
850 let v = text(&crate::parse_component_values(v));
852 have.is_some_and(|h| text(&crate::parse_component_values(&h)) == v)
853 }
854 })
855 }
856 StyleQuery::Not(q) => q.evaluate(get, number).map(|b| !b),
857 StyleQuery::And(qs) => three(qs.iter().map(|q| q.evaluate(get, number)), false),
858 StyleQuery::Or(qs) => three(qs.iter().map(|q| q.evaluate(get, number)), true),
859 StyleQuery::Unknown => None,
860 }
861 }
862}
863
864fn is_comparison(c: &ComponentValue<'_>) -> bool {
866 matches!(c, ComponentValue::Token(Token::Delim('<' | '>' | '='), _))
867}
868
869fn compare(a: Leaf, op: Comparison, b: Leaf) -> bool {
872 let typed = |l: Leaf| -> Option<(u8, Option<crate::values::Kind>, f64)> {
873 Some(match l {
874 Leaf::Number(v) => (0, None, v),
875 Leaf::Percentage(v) => (1, None, v),
876 Leaf::Dimension(v, u) => (2, Some(u.kind()), v * u.to_canonical()?),
877 })
878 };
879 let (Some(mut x), Some(mut y)) = (typed(a), typed(b)) else {
880 return false;
881 };
882 let length = Some(crate::values::Kind::Length);
883 if x.0 == 0 && x.2 == 0.0 && y.1 == length {
884 x = y;
885 x.2 = 0.0;
886 }
887 if y.0 == 0 && y.2 == 0.0 && x.1 == length {
888 y = x;
889 y.2 = 0.0;
890 }
891 (x.0, x.1) == (y.0, y.1) && op.test(x.2, y.2)
892}
893
894fn three(values: impl Iterator<Item = Option<bool>>, any: bool) -> Option<bool> {
897 let mut unknown = false;
898 for v in values {
899 match v {
900 Some(b) if b == any => return Some(any),
901 None => unknown = true,
902 Some(_) => {}
903 }
904 }
905 if unknown { None } else { Some(!any) }
906}
907
908#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
911pub struct Axes {
912 pub inline: bool,
913 pub block: bool,
914}
915
916const SIZE_FEATURES: &[&str] = &[
917 "width",
918 "height",
919 "inline-size",
920 "block-size",
921 "aspect-ratio",
922 "orientation",
923];
924
925impl ContainerQuery {
926 pub fn parse_list(prelude: &[ComponentValue<'_>]) -> Option<Vec<ContainerQuery>> {
928 let mut out = Vec::new();
929 for part in prelude.split(|v| matches!(v, ComponentValue::Token(Token::Comma, _))) {
930 out.push(ContainerQuery::parse(part)?);
931 }
932 (!out.is_empty()).then_some(out)
933 }
934
935 pub fn parse(values: &[ComponentValue<'_>]) -> Option<ContainerQuery> {
937 let v = crate::media::solid(values);
938 let (name, rest) = match v.first() {
939 Some(ComponentValue::Token(Token::Ident(n), _))
940 if !["not", "and", "or", "none"]
941 .iter()
942 .chain(CSS_WIDE)
943 .any(|w| n.eq_ignore_ascii_case(w)) =>
944 {
945 (Some(n.to_string()), &v[1..])
946 }
947 _ => (None, &v[..]),
948 };
949 if rest.is_empty() {
950 return name.map(|name| ContainerQuery {
951 name: Some(name),
952 condition: None,
953 styles: Vec::new(),
954 });
955 }
956 let condition = crate::media::parse_condition(rest, true, 0)?;
957 if matches!(rest.first(), Some(ComponentValue::Token(Token::Ident(w), _)) if !w.eq_ignore_ascii_case("not"))
959 {
960 return None;
961 }
962 let mut styles = Vec::new();
963 fn collect(c: &Condition, out: &mut Vec<(String, StyleQuery)>) {
964 match c {
965 Condition::Unknown(t) => {
966 let v = crate::parse_component_values(t);
967 if let [ComponentValue::Function(f)] = trimmed(&v)
968 && f.name.eq_ignore_ascii_case("style")
969 {
970 let q = StyleQuery::parse(&f.arguments, 0);
971 let q = if q.whole() { q } else { StyleQuery::Unknown };
974 out.push((t.clone(), q));
975 }
976 }
977 Condition::Not(c) | Condition::Parens(c) => collect(c, out),
978 Condition::And(cs) | Condition::Or(cs) => cs.iter().for_each(|c| collect(c, out)),
979 Condition::Feature(_) => {}
980 }
981 }
982 collect(&condition, &mut styles);
983 Some(ContainerQuery {
984 name,
985 condition: Some(condition),
986 styles,
987 })
988 }
989
990 pub fn axes(&self) -> Axes {
992 fn walk(c: &Condition, a: &mut Axes) {
993 match c {
994 Condition::Feature(f) => {
995 let name = match f {
996 Feature::Boolean(n) | Feature::Plain(n, _) => n.as_str(),
997 Feature::Range { name, .. } => name.as_str(),
998 };
999 let base = name
1000 .strip_prefix("min-")
1001 .or_else(|| name.strip_prefix("max-"))
1002 .unwrap_or(name);
1003 match base {
1004 "width" | "inline-size" => a.inline = true,
1005 "height" | "block-size" => a.block = true,
1006 "aspect-ratio" | "orientation" => {
1007 a.inline = true;
1008 a.block = true;
1009 }
1010 _ => {}
1011 }
1012 }
1013 Condition::Not(c) | Condition::Parens(c) => walk(c, a),
1014 Condition::And(cs) | Condition::Or(cs) => cs.iter().for_each(|c| walk(c, a)),
1015 Condition::Unknown(_) => {}
1016 }
1017 }
1018 let mut a = Axes::default();
1019 if let Some(c) = &self.condition {
1020 walk(c, &mut a);
1021 }
1022 a
1023 }
1024
1025 pub fn evaluate(
1033 &self,
1034 size: Option<(f64, f64)>,
1035 lengths: &QueryLengths,
1036 style: &dyn Fn(&str) -> Option<String>,
1037 number: &dyn Fn(&str) -> Option<Leaf>,
1038 ) -> Option<bool> {
1039 let Some(c) = &self.condition else {
1040 return Some(true);
1041 };
1042 let env = size.map(|(width, height)| Environment {
1043 width,
1044 height,
1045 font_size: lengths.font_size,
1046 keywords: Vec::new(),
1047 ..Environment::default()
1048 });
1049 let cx = Evaluation {
1050 env: env.as_ref(),
1051 lengths,
1052 styles: &self.styles,
1053 style,
1054 number,
1055 };
1056 evaluate(c, &cx)
1057 }
1058
1059 pub fn has_style(&self) -> bool {
1061 !self.styles.is_empty()
1062 }
1063}
1064
1065struct Evaluation<'e> {
1067 env: Option<&'e Environment>,
1069 lengths: &'e QueryLengths,
1070 styles: &'e [(String, StyleQuery)],
1071 style: &'e dyn Fn(&str) -> Option<String>,
1072 number: &'e dyn Fn(&str) -> Option<Leaf>,
1073}
1074
1075fn evaluate(c: &Condition, cx: &Evaluation<'_>) -> Option<bool> {
1078 let rename = |n: &str| -> Option<String> {
1079 let (prefix, base) = match n.strip_prefix("min-") {
1080 Some(b) => ("min-", b),
1081 None => match n.strip_prefix("max-") {
1082 Some(b) => ("max-", b),
1083 None => ("", n),
1084 },
1085 };
1086 if !SIZE_FEATURES.contains(&base) {
1087 return None;
1088 }
1089 let base = match base {
1090 "inline-size" => "width",
1091 "block-size" => "height",
1092 b => b,
1093 };
1094 Some(format!("{prefix}{base}"))
1095 };
1096 match c {
1097 Condition::Feature(f) => {
1098 let f = match f {
1099 Feature::Boolean(n) => Feature::Boolean(rename(n)?),
1100 Feature::Plain(n, v) => Feature::Plain(rename(n)?, v.clone()),
1101 Feature::Range {
1102 name,
1103 before,
1104 after,
1105 } => Feature::Range {
1106 name: rename(name)?,
1107 before: before.clone(),
1108 after: after.clone(),
1109 },
1110 };
1111 f.evaluate_with(cx.env?, cx.lengths)
1112 }
1113 Condition::Parens(c) => evaluate(c, cx),
1114 Condition::Not(c) => evaluate(c, cx).map(|b| !b),
1115 Condition::Unknown(t) => cx
1116 .styles
1117 .iter()
1118 .find(|(text, _)| text == t)
1119 .and_then(|(_, q)| q.evaluate(cx.style, cx.number)),
1120 Condition::And(cs) => three(cs.iter().map(|c| evaluate(c, cx)), false),
1121 Condition::Or(cs) => three(cs.iter().map(|c| evaluate(c, cx)), true),
1122 }
1123}
1124
1125impl fmt::Display for ContainerQuery {
1126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1127 if let Some(n) = &self.name {
1128 write_name(f, n)?;
1129 if self.condition.is_some() {
1130 f.write_char(' ')?;
1131 }
1132 }
1133 if let Some(c) = &self.condition {
1134 write!(f, "{c}")?;
1135 }
1136 Ok(())
1137 }
1138}
1139
1140#[derive(Clone, Debug, PartialEq, Default)]
1146pub struct ScopeBounds {
1147 pub start: Option<String>,
1148 pub end: Option<String>,
1149}
1150
1151impl ScopeBounds {
1152 pub fn parse(prelude: &[ComponentValue<'_>]) -> Option<ScopeBounds> {
1154 let v = crate::media::solid(prelude);
1155 let parens = |c: &ComponentValue<'_>| match c {
1159 ComponentValue::Block(b)
1160 if b.bracket == Bracket::Paren && !has_pseudo_element(&b.contents) =>
1161 {
1162 Some(text(&b.contents))
1163 }
1164 _ => None,
1165 };
1166 let mut i = 0;
1167 let mut out = ScopeBounds::default();
1168 if let Some(c) = v.first()
1169 && let Some(s) = parens(c)
1170 {
1171 out.start = Some(s);
1172 i = 1;
1173 }
1174 match &v[i..] {
1175 [] => {}
1176 [ComponentValue::Token(Token::Ident(w), _), c] if w.eq_ignore_ascii_case("to") => {
1177 out.end = Some(parens(c)?);
1178 }
1179 _ => return None,
1180 }
1181 Some(out)
1182 }
1183}
1184
1185fn has_pseudo_element(selector: &[ComponentValue<'_>]) -> bool {
1189 selector.windows(2).any(|w| match w {
1190 [
1191 ComponentValue::Token(Token::Colon, _),
1192 ComponentValue::Token(Token::Colon, _),
1193 ] => true,
1194 [
1195 ComponentValue::Token(Token::Colon, _),
1196 ComponentValue::Token(Token::Ident(name), _),
1197 ] => ["before", "after", "first-line", "first-letter"]
1198 .iter()
1199 .any(|legacy| name.eq_ignore_ascii_case(legacy)),
1200 _ => false,
1201 })
1202}
1203
1204impl fmt::Display for ScopeBounds {
1205 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1206 if let Some(s) = &self.start {
1207 write!(f, "({s})")?;
1208 }
1209 if let Some(e) = &self.end {
1210 if self.start.is_some() {
1211 f.write_char(' ')?;
1212 }
1213 write!(f, "to ({e})")?;
1214 }
1215 Ok(())
1216 }
1217}
1218
1219#[derive(Clone, Debug, PartialEq)]
1224pub struct Import {
1225 pub url: String,
1226 pub layer: Option<Option<String>>,
1229 pub supports: Option<(String, bool)>,
1231 pub media: MediaQueryList,
1232 pub scope: Option<ScopeBounds>,
1235}
1236
1237impl Import {
1238 pub fn parse<B>(rule: &AtRule<'_, B>) -> Option<Import> {
1240 if !rule.name.eq_ignore_ascii_case("import") || rule.block.is_some() {
1241 return None;
1242 }
1243 let v: Vec<&ComponentValue<'_>> =
1244 rule.prelude.iter().filter(|v| !v.is_whitespace()).collect();
1245 let url = match v.first()? {
1246 ComponentValue::Token(Token::String(s) | Token::Url(s), _) => s.to_string(),
1247 ComponentValue::Function(f) if f.name.eq_ignore_ascii_case("url") => {
1248 match trimmed(&f.arguments) {
1249 [ComponentValue::Token(Token::String(s), _)] => s.to_string(),
1250 _ => return None,
1251 }
1252 }
1253 _ => return None,
1254 };
1255 let mut i = 1;
1256 let mut layer = None;
1257 match v.get(i) {
1258 Some(ComponentValue::Token(Token::Ident(w), _)) if w.eq_ignore_ascii_case("layer") => {
1259 layer = Some(None);
1260 i += 1;
1261 }
1262 Some(ComponentValue::Function(f)) if f.name.eq_ignore_ascii_case("layer") => {
1263 let name = text(&f.arguments);
1264 let parts: Vec<&str> = name.split('.').map(str::trim).collect();
1265 let ok = !parts.is_empty()
1266 && parts.iter().all(|p| {
1267 let c = crate::parse_component_values(p);
1268 matches!(&c[..], [ComponentValue::Token(Token::Ident(_), _)])
1269 });
1270 if !ok {
1271 return None;
1272 }
1273 layer = Some(Some(parts.join(".")));
1274 i += 1;
1275 }
1276 _ => {}
1277 }
1278 let mut scope = None;
1279 if let Some(ComponentValue::Function(f)) = v.get(i)
1280 && f.name.eq_ignore_ascii_case("scope")
1281 {
1282 let bounds = ScopeBounds::parse(&f.arguments).or_else(|| {
1284 let start = text(&f.arguments);
1285 (!start.is_empty()).then_some(ScopeBounds {
1286 start: Some(start),
1287 end: None,
1288 })
1289 })?;
1290 scope = Some(bounds);
1291 i += 1;
1292 }
1293 let mut supports = None;
1294 if let Some(ComponentValue::Function(f)) = v.get(i)
1295 && f.name.eq_ignore_ascii_case("supports")
1296 {
1297 let inner = trimmed(&f.arguments);
1299 let held = match crate::supports::supports(inner) {
1300 Some(b) => b,
1301 None => {
1302 let wrapped = format!("({})", crate::to_css(inner));
1303 crate::supports::supports(&crate::parse_component_values(&wrapped))
1304 .unwrap_or(false)
1305 }
1306 };
1307 supports = Some((crate::to_css(inner), held));
1308 i += 1;
1309 }
1310 let first = v.get(i).map(|x| {
1312 rule.prelude
1313 .iter()
1314 .position(|p| std::ptr::eq(p, *x))
1315 .unwrap_or(rule.prelude.len())
1316 });
1317 let media = match first {
1318 Some(at) => MediaQueryList::parse(&rule.prelude[at..]),
1319 None => MediaQueryList::default(),
1320 };
1321 Some(Import {
1322 url,
1323 layer,
1324 supports,
1325 media,
1326 scope,
1327 })
1328 }
1329
1330 pub fn applies(&self, env: &Environment) -> bool {
1332 self.supports.as_ref().is_none_or(|(_, held)| *held)
1333 && (self.media.queries.is_empty() || self.media.matches(env))
1334 }
1335}
1336
1337#[cfg(test)]
1338mod tests {
1339 use super::*;
1340 use crate::Rule;
1341
1342 fn at(css: &str) -> AtRule<'_, Block<'_>> {
1343 let mut sheet = crate::parse_stylesheet_deep(css);
1344 match sheet.rules.remove(0) {
1345 Rule::At(a) => a,
1346 _ => panic!("{css}"),
1347 }
1348 }
1349
1350 #[test]
1351 fn keyframes() {
1352 let k = Keyframes::parse(&at(
1353 "@keyframes spin { from { rotate: 0deg } 50%, to { rotate: 1turn; color: red !important } 120% { x: y } }",
1354 ))
1355 .unwrap();
1356 assert_eq!(k.name, "spin");
1357 assert_eq!(k.frames.len(), 2);
1358 assert_eq!(
1359 k.to_string(),
1360 "@keyframes spin { 0% { rotate: 0deg; } 50%, 100% { rotate: 1turn; } }"
1361 );
1362 assert!(Keyframes::parse(&at("@keyframes none {}")).is_none());
1363 assert!(Keyframes::parse(&at("@keyframes \"a b\" {}")).is_some());
1364 }
1365
1366 #[test]
1367 fn counter_styles() {
1368 let c = CounterStyle::parse(&at(
1369 "@counter-style x { system: fixed 3; symbols: a 'b'; range: 5 2; pad: 'z' 2; suffix: ' ' }",
1370 ))
1371 .unwrap();
1372 assert_eq!(c.get("system"), Some("fixed 3"));
1373 assert_eq!(c.get("symbols"), Some("a \"b\""));
1374 assert_eq!(c.get("range"), None);
1375 assert_eq!(c.get("pad"), Some("2 \"z\""));
1376 assert!(
1377 CounterStyle::parse(&at("@counter-style decimal { system: cyclic; symbols: a }"))
1378 .is_none()
1379 );
1380 let one = CounterStyle::parse(&at("@counter-style x { system: alphabetic; symbols: a }"))
1381 .unwrap();
1382 assert!(!one.usable() && c.usable());
1383 let none = CounterStyle::parse(&at("@counter-style x { system: extends none }")).unwrap();
1384 assert_eq!(none.get("system"), None);
1385 }
1386
1387 #[test]
1388 fn properties() {
1389 let p = |css: &str| PropertyRule::parse(&at(css));
1390 assert!(
1391 p("@property --a { syntax: '<length>'; inherits: false; initial-value: 1em }")
1392 .is_none()
1393 );
1394 let no_inherits = p("@property --a { syntax: '<length>'; initial-value: 1px }").unwrap();
1395 assert!(no_inherits.inherits && no_inherits.registers());
1396 assert!(
1397 !p("@property --a { syntax: '<length>' }")
1398 .unwrap()
1399 .registers()
1400 );
1401 assert!(p("@property --a { syntax: '*'; inherits: true }").is_some());
1402 assert!(p("@property --a { syntax: '<color># | foo'; inherits: true; initial-value: red, blue }").is_some());
1403 assert_eq!(
1404 p("@property --a { syntax: '<colour>'; inherits: true }")
1405 .unwrap()
1406 .syntax,
1407 "*"
1408 );
1409 assert!(p("@property a { syntax: '*'; inherits: true }").is_none());
1410 }
1411
1412 #[test]
1413 fn containers() {
1414 let q = ContainerQuery::parse_list(&crate::parse_component_values(
1415 "card (min-width: 400px) and (inline-size < 50em)",
1416 ))
1417 .unwrap();
1418 assert_eq!(q[0].name.as_deref(), Some("card"));
1419 let none = |_: &str| None;
1420 let no_number = |_: &str| None;
1421 let lengths = QueryLengths::of(&Environment::default());
1422 assert_eq!(
1423 q[0].evaluate(Some((500.0, 10.0)), &lengths, &none, &no_number),
1424 Some(true)
1425 );
1426 assert_eq!(
1427 q[0].evaluate(Some((300.0, 10.0)), &lengths, &none, &no_number),
1428 Some(false)
1429 );
1430 assert_eq!(
1431 q[0].axes(),
1432 Axes {
1433 inline: true,
1434 block: false
1435 }
1436 );
1437 let q = ContainerQuery::parse(&crate::parse_component_values("(color)")).unwrap();
1438 assert_eq!(
1439 q.evaluate(Some((500.0, 10.0)), &lengths, &none, &no_number),
1440 None
1441 );
1442 let q = ContainerQuery::parse(&crate::parse_component_values(
1443 "style((--a: 1) and (not (--b)))",
1444 ))
1445 .unwrap();
1446 let get = |n: &str| (n == "--a").then(|| " 1".to_string());
1447 assert_eq!(q.evaluate(None, &lengths, &get, &no_number), Some(true));
1448 assert!(ContainerQuery::parse(&crate::parse_component_values("name screen")).is_none());
1449
1450 let range = |s: &str| {
1452 let v = crate::parse_component_values(s);
1453 StyleQuery::parse(&v, 0)
1454 };
1455 assert_eq!(
1456 range("10px < --a <= 2em"),
1457 StyleQuery::Range {
1458 values: vec!["10px".into(), "var(--a)".into(), "2em".into()],
1459 ops: vec![Comparison::Lt, Comparison::Le],
1460 }
1461 );
1462 for bad in [
1463 "10px < 1em > 1",
1464 "< 1em",
1465 "1px < 1em !",
1466 "1 = 2 = 3",
1467 "1 < 2 < 3 < 4",
1468 ] {
1469 assert_eq!(range(bad), StyleQuery::Unknown, "{bad}");
1470 }
1471 assert_eq!(range("--a: b;"), StyleQuery::Unknown);
1472 let q = ContainerQuery::parse(&crate::parse_component_values(
1473 "style(0 < 3px) and style(1 < 2%)",
1474 ))
1475 .unwrap();
1476 let number = |v: &str| match v {
1477 "0" => Some(Leaf::Number(0.0)),
1478 "1" => Some(Leaf::Number(1.0)),
1479 "3px" => Some(Leaf::Dimension(3.0, Unit::Px)),
1480 "2%" => Some(Leaf::Percentage(2.0)),
1481 _ => None,
1482 };
1483 assert_eq!(q.evaluate(None, &lengths, &none, &number), Some(false));
1486 let q = ContainerQuery::parse(&crate::parse_component_values("style(0 < 3px)")).unwrap();
1487 assert_eq!(q.evaluate(None, &lengths, &none, &number), Some(true));
1488 }
1489
1490 #[test]
1491 fn a_scope_bound_cant_be_a_pseudo_element() {
1492 let bounds = |s: &str| ScopeBounds::parse(&crate::parse_component_values(s));
1493 assert!(bounds("(div::before)").is_none());
1494 assert!(bounds("(.a) to (div:after)").is_none());
1495 assert!(bounds("(div:hover) to (.b)").is_some());
1496 assert!(bounds("(a:is(.x, .y))").is_some());
1497 }
1498
1499 #[test]
1500 fn scopes_and_imports() {
1501 let s = ScopeBounds::parse(&crate::parse_component_values("(.a) to (.b > c)")).unwrap();
1502 assert_eq!(
1503 (s.start.as_deref(), s.end.as_deref()),
1504 (Some(".a"), Some(".b > c"))
1505 );
1506 assert_eq!(s.to_string(), "(.a) to (.b > c)");
1507 assert!(ScopeBounds::parse(&crate::parse_component_values("to")).is_none());
1508 let i = Import::parse(&at(
1509 "@import url(a.css) layer(x.y) supports(display: grid) screen;",
1510 ))
1511 .unwrap();
1512 assert_eq!(i.url, "a.css");
1513 assert_eq!(i.layer, Some(Some("x.y".into())));
1514 assert_eq!(i.supports.as_ref().map(|s| s.1), Some(true));
1515 assert!(i.applies(&Environment::default()));
1516 let i = Import::parse(&at("@import 'b.css' supports(nonsense: 1);")).unwrap();
1517 assert!(!i.applies(&Environment::default()));
1518 }
1519}