Skip to main content

style/queries/
condition.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 query condition:
6//!
7//! https://drafts.csswg.org/mediaqueries-4/#typedef-media-condition
8//! https://drafts.csswg.org/css-contain-3/#typedef-container-condition
9
10use super::{FeatureFlags, FeatureType, QueryFeatureExpression, QueryStyleRange};
11use crate::computed_value_flags::ComputedValueFlags;
12use crate::context::QuirksMode;
13use crate::custom_properties;
14use crate::derives::*;
15use crate::dom::AttributeTracker;
16use crate::properties::CSSWideKeyword;
17use crate::properties_and_values::rule::Descriptors as PropertyDescriptors;
18use crate::properties_and_values::value::{
19    AllowComputationallyDependent, ComputedValue as ComputedRegisteredValue,
20    SpecifiedValue as SpecifiedRegisteredValue,
21};
22use crate::stylesheets::container_rule::AttrReferenceSet;
23use crate::stylesheets::{CssRuleType, CustomMediaEvaluator, Origin, UrlExtraData};
24use crate::stylist::Stylist;
25use crate::substitution;
26use crate::substitution::AttrTaint;
27use crate::values::{AtomString, DashedIdent, computed};
28use crate::{error_reporting::ContextualParseError, parser::Parse, parser::ParserContext};
29use cssparser::{
30    Parser, SourceLocation, SourcePosition, Token, match_ignore_ascii_case, parse_important,
31};
32use selectors::kleene_value::KleeneValue;
33use servo_arc::Arc;
34use std::borrow::Cow;
35use std::fmt::{self, Write};
36use style_traits::{CssWriter, ParseError, ParsingMode, StyleParseErrorKind, ToCss};
37
38/// A binary `and` or `or` operator.
39#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToCss, ToShmem)]
40#[allow(missing_docs)]
41pub enum Operator {
42    And,
43    Or,
44}
45
46/// Whether to allow an `or` condition or not during parsing.
47#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, ToCss)]
48enum AllowOr {
49    Yes,
50    No,
51}
52
53#[derive(Clone, Debug, PartialEq, ToShmem)]
54enum StyleFeatureValue {
55    Value(Option<Arc<custom_properties::SpecifiedValue>>),
56    Keyword(CSSWideKeyword),
57}
58
59/// Trait for query elements that parse a series of conditions separated by
60/// AND or OR operators, or prefixed with NOT.
61///
62/// This is used by both QueryCondition and StyleQuery as they support similar
63/// syntax for combining multiple conditions with a boolean operator.
64trait OperationParser: Sized {
65    /// https://drafts.csswg.org/mediaqueries-5/#typedef-media-condition or
66    /// https://drafts.csswg.org/mediaqueries-5/#typedef-media-condition-without-or
67    /// (depending on `allow_or`).
68    fn parse_internal(
69        context: &ParserContext,
70        input: &mut Parser,
71        feature_type: FeatureType,
72        allow_or: AllowOr,
73    ) -> Result<Self, ParseError> {
74        if input.try_parse(|i| i.expect_ident_matching("not")).is_ok() {
75            let inner_condition = Self::parse_in_parens(context, input, feature_type)?;
76            return Ok(Self::new_not(Box::new(inner_condition)));
77        }
78
79        let first_condition = Self::parse_in_parens(context, input, feature_type)?;
80        let operator = match input.try_parse(Operator::parse) {
81            Ok(op) => op,
82            Err(..) => return Ok(first_condition),
83        };
84
85        if allow_or == AllowOr::No && operator == Operator::Or {
86            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
87        }
88
89        let mut conditions = vec![];
90        conditions.push(first_condition);
91        conditions.push(Self::parse_in_parens(context, input, feature_type)?);
92
93        let delim = match operator {
94            Operator::And => "and",
95            Operator::Or => "or",
96        };
97
98        loop {
99            if input.try_parse(|i| i.expect_ident_matching(delim)).is_err() {
100                return Ok(Self::new_operation(conditions.into_boxed_slice(), operator));
101            }
102
103            conditions.push(Self::parse_in_parens(context, input, feature_type)?);
104        }
105    }
106
107    // Parse a condition in parentheses, or `<general-enclosed>`.
108    fn parse_in_parens(
109        context: &ParserContext,
110        input: &mut Parser,
111        feature_type: FeatureType,
112    ) -> Result<Self, ParseError>;
113
114    // Helpers to create the appropriate enum variant of the implementing type:
115    // Create a Not result that encapsulates the `inner` condition.
116    fn new_not(inner: Box<Self>) -> Self;
117
118    // Create an Operation result with the given list of `conditions` using `operator`.
119    fn new_operation(conditions: Box<[Self]>, operator: Operator) -> Self;
120}
121
122fn try_parse_block<'i, T, F>(
123    context: &ParserContext,
124    input: &mut Parser<'i>,
125    start: SourcePosition,
126    start_location: SourceLocation,
127    parse: F,
128) -> Option<T>
129where
130    F: FnOnce(&mut Parser<'i>) -> Result<T, ParseError>,
131{
132    input
133        .try_parse(|input| {
134            let result = input.parse_nested_block(parse);
135            if let Err(ref e) = result
136                && context.error_reporting_enabled()
137            {
138                // We're about to swallow the error in a `<general-enclosed>` condition, so report
139                // it while we can.
140                let error =
141                    ContextualParseError::InvalidMediaRule(input.slice_from(start), e.clone());
142                context.log_css_error(start_location, error);
143            }
144            result
145        })
146        .ok()
147}
148
149/// https://drafts.csswg.org/css-conditional-5/#typedef-style-query
150#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToShmem)]
151pub enum StyleQuery {
152    /// A negation of a condition.
153    Not(Box<StyleQuery>),
154    /// A set of joint operations.
155    Operation(Box<[StyleQuery]>, Operator),
156    /// A condition wrapped in parenthesis.
157    InParens(Box<StyleQuery>),
158    /// A feature query (`--foo: bar` or just `--foo`).
159    Feature(StyleFeature),
160    /// An unknown "general-enclosed" term.
161    GeneralEnclosed(String),
162}
163
164impl ToCss for StyleQuery {
165    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
166    where
167        W: fmt::Write,
168    {
169        match *self {
170            StyleQuery::Not(ref c) => {
171                dest.write_str("not ")?;
172                c.maybe_parenthesized(dest)
173            },
174            StyleQuery::Operation(ref list, op) => {
175                let mut iter = list.iter();
176                let item = iter.next().unwrap();
177                item.maybe_parenthesized(dest)?;
178                for item in iter {
179                    dest.write_char(' ')?;
180                    op.to_css(dest)?;
181                    dest.write_char(' ')?;
182                    item.maybe_parenthesized(dest)?;
183                }
184                Ok(())
185            },
186            StyleQuery::InParens(ref c) => match &**c {
187                StyleQuery::Feature(_) | StyleQuery::InParens(_) => {
188                    dest.write_char('(')?;
189                    c.to_css(dest)?;
190                    dest.write_char(')')
191                },
192                _ => c.to_css(dest),
193            },
194            StyleQuery::Feature(ref f) => f.to_css(dest),
195            StyleQuery::GeneralEnclosed(ref s) => dest.write_str(s),
196        }
197    }
198}
199
200impl StyleQuery {
201    // Helper for to_css when handling values within boolean operators:
202    // GeneralEnclosed includes its parens in the string, so we don't need to
203    // wrap the value with an additional set here.
204    fn maybe_parenthesized<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
205    where
206        W: fmt::Write,
207    {
208        if let StyleQuery::GeneralEnclosed(s) = self {
209            dest.write_str(s)
210        } else {
211            dest.write_char('(')?;
212            self.to_css(dest)?;
213            dest.write_char(')')
214        }
215    }
216
217    fn enabled(feature_type: FeatureType) -> bool {
218        crate::pref!("layout.css.style-queries.enabled") && feature_type == FeatureType::Container
219    }
220
221    fn parse(
222        context: &ParserContext,
223        input: &mut Parser,
224        feature_type: FeatureType,
225    ) -> Result<Self, ParseError> {
226        if let Ok(feature) = input.try_parse(|input| StyleFeature::parse(context, input)) {
227            return Ok(Self::Feature(feature));
228        }
229
230        let inner = Self::parse_internal(context, input, feature_type, AllowOr::Yes)?;
231        Ok(Self::InParens(Box::new(inner)))
232    }
233
234    fn parse_in_parenthesis_block(
235        context: &ParserContext,
236        input: &mut Parser,
237    ) -> Result<Self, ParseError> {
238        // Base case. Make sure to preserve this error as it's more generally
239        // relevant.
240        let feature_error = match input.try_parse(|input| StyleFeature::parse(context, input)) {
241            Ok(feature) => return Ok(Self::Feature(feature)),
242            Err(e) => e,
243        };
244
245        if let Ok(inner) = Self::parse(context, input, FeatureType::Container) {
246            return Ok(inner);
247        }
248
249        Err(feature_error)
250    }
251
252    fn matches(
253        &self,
254        ctx: &computed::Context,
255        attribute_tracker: &mut AttributeTracker,
256    ) -> KleeneValue {
257        ctx.builder
258            .add_flags(ComputedValueFlags::DEPENDS_ON_CONTAINER_STYLE_QUERY);
259        match *self {
260            StyleQuery::Feature(ref f) => f.matches(ctx, attribute_tracker),
261            StyleQuery::Not(ref c) => !c.matches(ctx, attribute_tracker),
262            StyleQuery::InParens(ref c) => c.matches(ctx, attribute_tracker),
263            StyleQuery::Operation(ref conditions, op) => {
264                debug_assert!(!conditions.is_empty(), "We never create an empty op");
265                match op {
266                    Operator::And => KleeneValue::any_false(conditions.iter(), |c| {
267                        c.matches(ctx, attribute_tracker)
268                    }),
269                    Operator::Or => {
270                        KleeneValue::any(conditions.iter(), |c| c.matches(ctx, attribute_tracker))
271                    },
272                }
273            },
274            StyleQuery::GeneralEnclosed(_) => KleeneValue::Unknown,
275        }
276    }
277
278    fn collect_attribute_references(&self, references: &mut AttrReferenceSet) {
279        match self {
280            Self::Feature(c) => c.collect_attribute_references(references),
281            Self::GeneralEnclosed(_) => {},
282            Self::InParens(c) => c.collect_attribute_references(references),
283            Self::Not(c) => c.collect_attribute_references(references),
284            Self::Operation(c, _) => c
285                .iter()
286                .for_each(|c| c.collect_attribute_references(references)),
287        }
288    }
289}
290
291impl OperationParser for StyleQuery {
292    fn parse_in_parens(
293        context: &ParserContext,
294        input: &mut Parser,
295        feature_type: FeatureType,
296    ) -> Result<Self, ParseError> {
297        assert!(feature_type == FeatureType::Container);
298        input.skip_whitespace();
299        let start = input.position();
300        let start_location = input.current_source_location();
301        match *input.next()? {
302            Token::ParenthesisBlock => {
303                if let Some(nested) = try_parse_block(context, input, start, start_location, |i| {
304                    Self::parse_in_parenthesis_block(context, i)
305                }) {
306                    return Ok(nested);
307                }
308                // Accept <ident>: <any-value> as a GeneralEnclosed (which evaluates
309                // to false, but does not invalidate the query as a whole).
310                input.parse_nested_block(|i| {
311                    i.expect_ident()?;
312                    i.expect_colon()?;
313                    consume_any_value(i)
314                })?;
315                Ok(Self::GeneralEnclosed(input.slice_from(start).to_owned()))
316            },
317            _ => Err(ParseError::unexpected_token()),
318        }
319    }
320
321    fn new_not(inner: Box<Self>) -> Self {
322        Self::Not(inner)
323    }
324
325    fn new_operation(conditions: Box<[Self]>, operator: Operator) -> Self {
326        Self::Operation(conditions, operator)
327    }
328}
329
330/// A style query feature:
331/// https://drafts.csswg.org/css-conditional-5/#typedef-style-feature
332#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToCss, ToShmem)]
333pub enum StyleFeature {
334    /// A property name and optional value to match.
335    Plain(StyleFeaturePlain),
336    /// A style query range expression.
337    Range(QueryStyleRange),
338}
339
340impl StyleFeature {
341    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
342        if let Ok(range) = input.try_parse(|i| QueryStyleRange::parse(context, i)) {
343            return Ok(Self::Range(range));
344        }
345
346        Ok(Self::Plain(StyleFeaturePlain::parse(context, input)?))
347    }
348
349    fn matches(
350        &self,
351        ctx: &computed::Context,
352        attribute_tracker: &mut AttributeTracker,
353    ) -> KleeneValue {
354        match self {
355            Self::Plain(plain) => plain.matches(ctx, attribute_tracker),
356            Self::Range(range) => range.evaluate(ctx, attribute_tracker),
357        }
358    }
359
360    fn collect_attribute_references(&self, references: &mut AttrReferenceSet) {
361        match self {
362            Self::Plain(plain) => plain.collect_attribute_references(references),
363            Self::Range(range) => range.collect_attribute_references(references),
364        }
365    }
366}
367
368/// A style feature consisting of a custom property name and (optionally) value.
369#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToShmem)]
370pub struct StyleFeaturePlain {
371    name: custom_properties::Name,
372    #[ignore_malloc_size_of = "StyleFeatureValue has an Arc variant"]
373    value: StyleFeatureValue,
374}
375
376impl ToCss for StyleFeaturePlain {
377    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
378    where
379        W: fmt::Write,
380    {
381        dest.write_str("--")?;
382        crate::values::serialize_atom_identifier(&self.name, dest)?;
383        match self.value {
384            StyleFeatureValue::Keyword(k) => {
385                dest.write_str(": ")?;
386                k.to_css(dest)?;
387            },
388            StyleFeatureValue::Value(Some(ref v)) => {
389                dest.write_str(": ")?;
390                v.to_css(dest)?;
391            },
392            StyleFeatureValue::Value(None) => (),
393        }
394        Ok(())
395    }
396}
397
398impl StyleFeaturePlain {
399    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
400        let ident = input.expect_ident()?;
401        // TODO(emilio): Maybe support non-custom properties?
402        let name = match custom_properties::parse_name(ident.as_ref()) {
403            Ok(name) => custom_properties::Name::from(name),
404            Err(()) => return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError)),
405        };
406        let value = if input.try_parse(|i| i.expect_colon()).is_ok() {
407            input.skip_whitespace();
408            if let Ok(keyword) = input.try_parse(|i| CSSWideKeyword::parse(i)) {
409                StyleFeatureValue::Keyword(keyword)
410            } else {
411                let value = custom_properties::SpecifiedValue::parse(context, input)?;
412                // `!important` is allowed (but ignored) after the value.
413                let _ = input.try_parse(parse_important);
414                StyleFeatureValue::Value(Some(Arc::new(value)))
415            }
416        } else {
417            StyleFeatureValue::Value(None)
418        };
419        Ok(Self { name, value })
420    }
421
422    // Substitute custom-property references in `value`, then re-parse and compute it,
423    // and compare against `current_value`.
424    fn substitute_and_compare(
425        value: &Arc<custom_properties::SpecifiedValue>,
426        registration: &PropertyDescriptors,
427        stylist: &Stylist,
428        ctx: &computed::Context,
429        attribute_tracker: &mut AttributeTracker,
430        current_value: Option<&ComputedRegisteredValue>,
431    ) -> bool {
432        let substitution_functions = custom_properties::ComputedSubstitutionFunctions::new(
433            Some(ctx.inherited_custom_properties().clone()),
434            None,
435        );
436        let substitution::SubstitutionResult { css, attr_taint } = match substitution::substitute(
437            value,
438            /* property_id */ None,
439            &substitution_functions,
440            stylist,
441            ctx,
442            attribute_tracker,
443        ) {
444            Ok(sub) => sub,
445            Err(_) => return current_value.is_none(),
446        };
447        if registration.is_universal() {
448            return match current_value {
449                Some(v) => v.as_universal().is_some_and(|v| v.css == css),
450                None => css.is_empty(),
451            };
452        }
453        let mut parser = Parser::new(&css);
454        let computed = SpecifiedRegisteredValue::compute(
455            &mut parser,
456            registration,
457            &value.url_data,
458            ctx,
459            AllowComputationallyDependent::Yes,
460            attr_taint,
461            /* property_id */ None,
462        )
463        .ok();
464        computed.as_ref() == current_value
465    }
466
467    fn matches(
468        &self,
469        ctx: &computed::Context,
470        attribute_tracker: &mut AttributeTracker,
471    ) -> KleeneValue {
472        // FIXME(emilio): Confirm this is the right style to query.
473        let stylist = ctx
474            .builder
475            .stylist
476            .expect("container queries should have a stylist around");
477        let registration = stylist.get_custom_property_registration(&self.name);
478        let current_value = ctx
479            .inherited_custom_properties()
480            .get(registration, &self.name);
481        KleeneValue::from(match self.value {
482            StyleFeatureValue::Value(Some(ref v)) => {
483                if ctx.container_info.is_none() {
484                    // If no container, custom props are guaranteed-unknown.
485                    false
486                } else if v.has_references() {
487                    // If there are --var() references in the query value,
488                    // try to substitute them before comparing to current.
489                    Self::substitute_and_compare(
490                        v,
491                        registration,
492                        stylist,
493                        ctx,
494                        attribute_tracker,
495                        current_value,
496                    )
497                } else {
498                    custom_properties::compute_variable_value(
499                        v,
500                        registration,
501                        ctx,
502                        /* property_id */ None,
503                    )
504                    .as_ref()
505                        == current_value
506                }
507            },
508            StyleFeatureValue::Value(None) => current_value.is_some(),
509            StyleFeatureValue::Keyword(kw) => {
510                match kw {
511                    CSSWideKeyword::Unset => current_value.is_none(),
512                    CSSWideKeyword::Initial => {
513                        if let Some(initial) = &registration.initial_value {
514                            let v = custom_properties::compute_variable_value(
515                                initial,
516                                registration,
517                                ctx,
518                                /* property_id */ None,
519                            );
520                            v.as_ref() == current_value
521                        } else {
522                            current_value.is_none()
523                        }
524                    },
525                    CSSWideKeyword::Inherit => {
526                        if let Some(inherited) = ctx
527                            .container_info
528                            .as_ref()
529                            .expect("queries should provide container info")
530                            .inherited_style()
531                        {
532                            inherited.custom_properties().get(registration, &self.name)
533                                == current_value
534                        } else {
535                            false
536                        }
537                    },
538                    // Cascade-dependent keywords, such as revert and revert-layer,
539                    // are invalid as values in a style feature, and cause the
540                    // container style query to be false.
541                    // https://drafts.csswg.org/css-conditional-5/#evaluate-a-style-range
542                    CSSWideKeyword::Revert
543                    | CSSWideKeyword::RevertLayer
544                    | CSSWideKeyword::RevertRule => false,
545                }
546            },
547        })
548    }
549
550    fn collect_attribute_references(&self, references: &mut AttrReferenceSet) {
551        if let StyleFeatureValue::Value(Some(v)) = &self.value {
552            v.collect_attribute_references(references)
553        }
554    }
555}
556
557/// A boolean value for a pref query.
558#[derive(
559    Clone,
560    Debug,
561    MallocSizeOf,
562    PartialEq,
563    Eq,
564    Parse,
565    SpecifiedValueInfo,
566    ToComputedValue,
567    ToCss,
568    ToShmem,
569)]
570#[repr(u8)]
571#[allow(missing_docs)]
572pub enum BoolValue {
573    False,
574    True,
575}
576
577/// Simple values we support for -moz-pref(). We don't want to deal with calc() and other
578/// shenanigans for now.
579#[derive(
580    Clone,
581    Debug,
582    Eq,
583    MallocSizeOf,
584    Parse,
585    PartialEq,
586    SpecifiedValueInfo,
587    ToComputedValue,
588    ToCss,
589    ToShmem,
590)]
591#[repr(u8)]
592pub enum MozPrefFeatureValue<I> {
593    /// No pref value, implicitly bool, but also used to represent missing prefs.
594    #[css(skip)]
595    None,
596    /// A bool value.
597    Boolean(BoolValue),
598    /// An integer value, useful for int prefs.
599    Integer(I),
600    /// A string pref value.
601    String(crate::values::AtomString),
602}
603
604type SpecifiedMozPrefFeatureValue = MozPrefFeatureValue<crate::values::specified::Integer>;
605/// The computed -moz-pref() value.
606pub type ComputedMozPrefFeatureValue = MozPrefFeatureValue<crate::values::computed::Integer>;
607
608/// A custom -moz-pref(<name>, <value>) query feature.
609#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToShmem)]
610pub struct MozPrefFeature {
611    name: crate::values::AtomString,
612    value: SpecifiedMozPrefFeatureValue,
613}
614
615impl MozPrefFeature {
616    fn parse(
617        context: &ParserContext,
618        input: &mut Parser,
619        feature_type: FeatureType,
620    ) -> Result<Self, ParseError> {
621        use crate::parser::Parse;
622        if !context.chrome_rules_enabled() || feature_type != FeatureType::Media {
623            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
624        }
625        let name = AtomString::parse(context, input)?;
626        let value = if input.try_parse(|i| i.expect_comma()).is_ok() {
627            SpecifiedMozPrefFeatureValue::parse(context, input)?
628        } else {
629            SpecifiedMozPrefFeatureValue::None
630        };
631        Ok(Self { name, value })
632    }
633
634    #[cfg(feature = "gecko")]
635    fn matches(&self, ctx: &computed::Context) -> KleeneValue {
636        use crate::values::computed::ToComputedValue;
637        let value = self.value.to_computed_value(ctx);
638        KleeneValue::from(unsafe {
639            crate::gecko_bindings::bindings::Gecko_EvalMozPrefFeature(self.name.as_ptr(), &value)
640        })
641    }
642
643    #[cfg(feature = "servo")]
644    fn matches(&self, _: &computed::Context) -> KleeneValue {
645        KleeneValue::Unknown
646    }
647}
648
649impl ToCss for MozPrefFeature {
650    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
651    where
652        W: fmt::Write,
653    {
654        self.name.to_css(dest)?;
655        if !matches!(self.value, MozPrefFeatureValue::None) {
656            dest.write_str(", ")?;
657            self.value.to_css(dest)?;
658        }
659        Ok(())
660    }
661}
662
663/// Represents a condition.
664#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToShmem)]
665pub enum QueryCondition {
666    /// A simple feature expression, implicitly parenthesized.
667    Feature(QueryFeatureExpression),
668    /// A custom media query reference in a boolean context, implicitly parenthesized.
669    Custom(DashedIdent),
670    /// A negation of a condition.
671    Not(Box<QueryCondition>),
672    /// A set of joint operations.
673    Operation(Box<[QueryCondition]>, Operator),
674    /// A condition wrapped in parenthesis.
675    InParens(Box<QueryCondition>),
676    /// A <style> query.
677    Style(StyleQuery),
678    /// A -moz-pref() query.
679    MozPref(MozPrefFeature),
680    /// [ <function-token> <any-value>? ) ] | [ ( <any-value>? ) ]
681    GeneralEnclosed(String, UrlExtraData, FeatureFlags),
682}
683
684impl ToCss for QueryCondition {
685    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
686    where
687        W: fmt::Write,
688    {
689        match *self {
690            // NOTE(emilio): QueryFeatureExpression already includes the
691            // parenthesis.
692            Self::Feature(ref f) => f.to_css(dest),
693            Self::Custom(ref name) => {
694                dest.write_char('(')?;
695                name.to_css(dest)?;
696                dest.write_char(')')
697            },
698            Self::Not(ref c) => {
699                dest.write_str("not ")?;
700                c.to_css(dest)
701            },
702            Self::InParens(ref c) => {
703                dest.write_char('(')?;
704                c.to_css(dest)?;
705                dest.write_char(')')
706            },
707            Self::Style(ref c) => {
708                dest.write_str("style(")?;
709                c.to_css(dest)?;
710                dest.write_char(')')
711            },
712            Self::MozPref(ref c) => {
713                dest.write_str("-moz-pref(")?;
714                c.to_css(dest)?;
715                dest.write_char(')')
716            },
717            Self::Operation(ref list, op) => {
718                let mut iter = list.iter();
719                iter.next().unwrap().to_css(dest)?;
720                for item in iter {
721                    dest.write_char(' ')?;
722                    op.to_css(dest)?;
723                    dest.write_char(' ')?;
724                    item.to_css(dest)?;
725                }
726                Ok(())
727            },
728            Self::GeneralEnclosed(ref s, ..) => dest.write_str(s),
729        }
730    }
731}
732
733/// <https://drafts.csswg.org/css-syntax-3/#typedef-any-value>
734fn consume_any_value(input: &mut Parser) -> Result<(), ParseError> {
735    input.expect_no_error_token().map_err(Into::into)
736}
737
738impl QueryCondition {
739    /// Parse a single condition.
740    pub fn parse(
741        context: &ParserContext,
742        input: &mut Parser,
743        feature_type: FeatureType,
744    ) -> Result<Self, ParseError> {
745        Self::parse_internal(context, input, feature_type, AllowOr::Yes)
746    }
747
748    fn visit<F>(&self, visitor: &mut F)
749    where
750        F: FnMut(&Self),
751    {
752        visitor(self);
753        match *self {
754            Self::Custom(..)
755            | Self::Feature(..)
756            | Self::GeneralEnclosed(..)
757            | Self::Style(..)
758            | Self::MozPref(..) => {},
759            Self::Not(ref cond) => cond.visit(visitor),
760            Self::Operation(ref conds, _op) => {
761                for cond in conds.iter() {
762                    cond.visit(visitor);
763                }
764            },
765            Self::InParens(ref cond) => cond.visit(visitor),
766        }
767    }
768
769    /// Returns the union of all flags in the expression. This is useful for
770    /// container queries.
771    pub fn cumulative_flags(&self) -> FeatureFlags {
772        let mut result = FeatureFlags::empty();
773        self.visit(&mut |condition| match condition {
774            Self::Style(..) => result.insert(FeatureFlags::STYLE),
775            Self::Feature(f) => result.insert(f.feature_flags()),
776            Self::GeneralEnclosed(_, _, flags) => result.insert(*flags),
777            _ => {},
778        });
779        result
780    }
781
782    /// Parse a single condition, disallowing `or` expressions.
783    ///
784    /// To be used from the legacy query syntax.
785    pub fn parse_disallow_or(
786        context: &ParserContext,
787        input: &mut Parser,
788        feature_type: FeatureType,
789    ) -> Result<Self, ParseError> {
790        Self::parse_internal(context, input, feature_type, AllowOr::No)
791    }
792
793    fn parse_in_parenthesis_block(
794        context: &ParserContext,
795        input: &mut Parser,
796        feature_type: FeatureType,
797    ) -> Result<Self, ParseError> {
798        // Base case. Make sure to preserve this error as it's more generally
799        // relevant.
800        let feature_error = match input.try_parse(|input| {
801            QueryFeatureExpression::parse_in_parenthesis_block(context, input, feature_type)
802        }) {
803            Ok(expr) => return Ok(Self::Feature(expr)),
804            Err(e) => e,
805        };
806        if crate::pref!("layout.css.custom-media.enabled")
807            && let Ok(custom) = input.try_parse(|input| DashedIdent::parse(context, input))
808        {
809            return Ok(Self::Custom(custom));
810        }
811        if let Ok(inner) = Self::parse(context, input, feature_type) {
812            return Ok(Self::InParens(Box::new(inner)));
813        }
814        Err(feature_error)
815    }
816
817    /// Whether this condition matches the device and quirks mode.
818    /// https://drafts.csswg.org/mediaqueries/#evaluating
819    /// https://drafts.csswg.org/mediaqueries/#typedef-general-enclosed
820    /// Kleene 3-valued logic is adopted here due to the introduction of
821    /// <general-enclosed>.
822    pub fn matches(
823        &self,
824        context: &computed::Context,
825        custom: &mut CustomMediaEvaluator,
826        attribute_tracker: &mut AttributeTracker,
827    ) -> KleeneValue {
828        match *self {
829            Self::Custom(ref f) => custom.matches(f, context),
830            Self::Feature(ref f) => f.matches(context),
831            Self::GeneralEnclosed(ref str, ref url_data, _) => {
832                self.matches_general(str, url_data, context, custom, attribute_tracker)
833            },
834            Self::InParens(ref c) => c.matches(context, custom, attribute_tracker),
835            Self::Not(ref c) => !c.matches(context, custom, attribute_tracker),
836            Self::Style(ref c) => c.matches(context, attribute_tracker),
837            Self::MozPref(ref c) => c.matches(context),
838            Self::Operation(ref conditions, op) => {
839                debug_assert!(!conditions.is_empty(), "We never create an empty op");
840                match op {
841                    Operator::And => KleeneValue::any_false(conditions.iter(), |c| {
842                        c.matches(context, custom, attribute_tracker)
843                    }),
844                    Operator::Or => KleeneValue::any(conditions.iter(), |c| {
845                        c.matches(context, custom, attribute_tracker)
846                    }),
847                }
848            },
849        }
850    }
851
852    /// For a condition that was parsed as GeneralEnclosed, try applying custom-property
853    /// substitution and re-parse the result.
854    fn matches_general(
855        &self,
856        css_text: &str,
857        url_data: &UrlExtraData,
858        context: &computed::Context,
859        custom: &mut CustomMediaEvaluator,
860        attribute_tracker: &mut AttributeTracker,
861    ) -> KleeneValue {
862        // This only applies (currently, at least) to container queries.
863        if !context.in_container_query {
864            return KleeneValue::Unknown;
865        }
866
867        let stylist = context
868            .builder
869            .stylist
870            .expect("container query should provide a Stylist");
871
872        // TODO(Bug 2087381) - Need to propagate the stylesheet's namespaces through here
873        // in order to support namespaced `attr()` functions in container query conditions.
874        let mut parser_context = ParserContext::new(
875            Origin::Author,
876            url_data,
877            Some(CssRuleType::Container),
878            ParsingMode::DEFAULT,
879            QuirksMode::NoQuirks,
880            /* namespaces = */ Default::default(),
881            /* error_reporter = */ None,
882            /* use_counters = */ None,
883            AttrTaint::default(),
884        );
885
886        // Parse the text as a custom-property value to identify references.
887        let value = match custom_properties::SpecifiedValue::parse(
888            &parser_context,
889            &mut Parser::new(css_text),
890        ) {
891            Ok(val) => val,
892            Err(_) => return KleeneValue::Unknown,
893        };
894
895        // If no references, we're not going to end up with a new result, just bail out.
896        if !value.has_references() {
897            return KleeneValue::Unknown;
898        }
899
900        // Substitute var() functions if possible.
901        let substitution_functions = custom_properties::ComputedSubstitutionFunctions::new(
902            Some(context.inherited_custom_properties().clone()),
903            None,
904        );
905        let substitution::SubstitutionResult { css, attr_taint } = match substitution::substitute(
906            &value,
907            /* property_id */ None,
908            &substitution_functions,
909            stylist,
910            context,
911            attribute_tracker,
912        ) {
913            Ok(sub) => sub,
914            Err(_) => return KleeneValue::Unknown,
915        };
916        parser_context.attr_tainted_regions = Cow::Owned(attr_taint);
917
918        // Re-parse the result as a query-condition, and evaluate it.
919        match Self::parse(
920            &parser_context,
921            &mut Parser::new(&css),
922            FeatureType::Container,
923        ) {
924            Ok(Self::GeneralEnclosed(..)) => {
925                // If the result is still GeneralEnclosed, the query is unknown.
926                KleeneValue::Unknown
927            },
928            Ok(query) => query.matches(context, custom, attribute_tracker),
929            Err(_) => KleeneValue::Unknown,
930        }
931    }
932
933    /// Collect the attribute references in this query condition, if any.
934    pub fn collect_attribute_references(&self, references: &mut AttrReferenceSet) {
935        if let QueryCondition::Style(c) = self {
936            c.collect_attribute_references(references)
937        }
938    }
939}
940
941impl OperationParser for QueryCondition {
942    /// Parse a condition in parentheses, or `<general-enclosed>`.
943    ///
944    /// https://drafts.csswg.org/mediaqueries/#typedef-media-in-parens
945    fn parse_in_parens(
946        context: &ParserContext,
947        input: &mut Parser,
948        feature_type: FeatureType,
949    ) -> Result<Self, ParseError> {
950        input.skip_whitespace();
951        let start = input.position();
952        let start_location = input.current_source_location();
953        let mut flags = FeatureFlags::empty();
954        match *input.next()? {
955            Token::ParenthesisBlock => {
956                let nested = try_parse_block(context, input, start, start_location, |input| {
957                    Self::parse_in_parenthesis_block(context, input, feature_type)
958                });
959                if let Some(nested) = nested {
960                    return Ok(nested);
961                }
962            },
963            Token::Function(ref name) => {
964                match_ignore_ascii_case! { name,
965                    "style" if StyleQuery::enabled(feature_type) => {
966                        let query = try_parse_block(context, input, start, start_location, |input| {
967                            StyleQuery::parse(context, input, feature_type)
968                        });
969                        if let Some(query) = query {
970                            return Ok(Self::Style(query));
971                        }
972                        flags.insert(FeatureFlags::STYLE);
973                    },
974                    "-moz-pref" => {
975                        let feature = try_parse_block(context, input, start, start_location, |input| {
976                            MozPrefFeature::parse(context, input, feature_type)
977                        });
978                        if let Some(feature) = feature {
979                            return Ok(Self::MozPref(feature));
980                        }
981                    },
982                    _ => {},
983                }
984            },
985            _ => return Err(ParseError::unexpected_token()),
986        }
987        input.parse_nested_block(consume_any_value)?;
988        Ok(Self::GeneralEnclosed(
989            input.slice_from(start).to_owned(),
990            context.url_data.clone(),
991            flags,
992        ))
993    }
994
995    fn new_not(inner: Box<Self>) -> Self {
996        Self::Not(inner)
997    }
998
999    fn new_operation(conditions: Box<[Self]>, operator: Operator) -> Self {
1000        Self::Operation(conditions, operator)
1001    }
1002}