Skip to main content

style/properties/
shorthands.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//! Manual shorthand parsing and serialization
6#![allow(missing_docs)]
7
8use crate::parser::{Parse, ParserContext};
9use crate::values::specified;
10use cssparser::Parser;
11use std::fmt::{self, Write};
12use style_traits::{
13    CssWriter, KeywordsCollectFn, ParseError, SpecifiedValueInfo, StyleParseErrorKind, ToCss,
14    values::SequenceWriter,
15};
16
17macro_rules! expanded {
18    ( $( $name: ident: $value: expr ),+ ) => {
19        expanded!( $( $name: $value, )+ )
20    };
21    ( $( $name: ident: $value: expr, )+ ) => {
22        Longhands {
23            $(
24                $name: $crate::properties::MaybeBoxed::maybe_boxed($value),
25            )+
26        }
27    }
28}
29pub(crate) use expanded;
30
31macro_rules! try_parse_one {
32    ($context: expr, $input: expr, $var: ident, $parse_path: path) => {
33        if $var.is_none() {
34            if let Ok(value) = $input.try_parse(|i| $parse_path($context, i)) {
35                $var = Some(value);
36                continue;
37            }
38        }
39    };
40    ($input: expr, $var: ident, $parse_path: path) => {
41        if $var.is_none() {
42            if let Ok(value) = $input.try_parse(|i| $parse_path(i)) {
43                $var = Some(value);
44                continue;
45            }
46        }
47    };
48}
49
50macro_rules! unwrap_or_initial {
51    ($prop: ident) => {
52        unwrap_or_initial!($prop, $prop)
53    };
54    ($prop: ident, $expr: expr) => {
55        $expr.unwrap_or_else(|| $prop::get_initial_specified_value())
56    };
57}
58
59/// Serializes a border shorthand value composed of width/style/color.
60pub fn serialize_directional_border<W>(
61    dest: &mut CssWriter<W>,
62    width: &specified::BorderSideWidth,
63    style: &specified::BorderStyle,
64    color: &specified::Color,
65) -> fmt::Result
66where
67    W: Write,
68{
69    use specified::{BorderSideWidth, BorderStyle, Color};
70    let has_style = *style != BorderStyle::None;
71    let has_color = *color != Color::CurrentColor;
72    let has_width = *width != BorderSideWidth::medium();
73    if !has_style && !has_color && !has_width {
74        return width.to_css(dest);
75    }
76    let mut writer = SequenceWriter::new(dest, " ");
77    if has_width {
78        writer.item(width)?;
79    }
80    if has_style {
81        writer.item(style)?;
82    }
83    if has_color {
84        writer.item(color)?;
85    }
86    Ok(())
87}
88
89pub fn parse_border(
90    context: &ParserContext,
91    input: &mut Parser,
92) -> Result<
93    (
94        specified::BorderSideWidth,
95        specified::BorderStyle,
96        specified::Color,
97    ),
98    ParseError,
99> {
100    use crate::values::specified::{BorderSideWidth, BorderStyle, Color};
101    let mut color = None;
102    let mut style = None;
103    let mut width = None;
104    let mut parsed = 0;
105    loop {
106        parsed += 1;
107        try_parse_one!(context, input, width, BorderSideWidth::parse);
108        try_parse_one!(input, style, BorderStyle::parse);
109        try_parse_one!(context, input, color, Color::parse);
110        parsed -= 1;
111        break;
112    }
113    if parsed == 0 {
114        return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
115    }
116    Ok((
117        width.unwrap_or(BorderSideWidth::medium()),
118        style.unwrap_or(BorderStyle::None),
119        color.unwrap_or(Color::CurrentColor),
120    ))
121}
122
123pub mod border_block {
124    use super::*;
125    pub use crate::properties::generated::shorthands::border_block::*;
126
127    pub fn parse_value(
128        context: &ParserContext,
129        input: &mut Parser,
130    ) -> Result<Longhands, ParseError> {
131        let (width, style, color) = super::parse_border(context, input)?;
132        Ok(Longhands {
133            border_block_start_width: width.clone(),
134            border_block_start_style: style,
135            border_block_start_color: color.clone(),
136            border_block_end_width: width,
137            border_block_end_style: style,
138            border_block_end_color: color,
139        })
140    }
141
142    impl<'a> ToCss for LonghandsToSerialize<'a> {
143        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
144        where
145            W: fmt::Write,
146        {
147            // FIXME: Should serialize empty if start != end, right?
148            super::serialize_directional_border(
149                dest,
150                self.border_block_start_width,
151                self.border_block_start_style,
152                self.border_block_start_color,
153            )
154        }
155    }
156}
157
158pub mod border_inline {
159    use super::*;
160    pub use crate::properties::generated::shorthands::border_inline::*;
161
162    pub fn parse_value(
163        context: &ParserContext,
164        input: &mut Parser,
165    ) -> Result<Longhands, ParseError> {
166        let (width, style, color) = super::parse_border(context, input)?;
167        Ok(Longhands {
168            border_inline_start_width: width.clone(),
169            border_inline_start_style: style,
170            border_inline_start_color: color.clone(),
171            border_inline_end_width: width,
172            border_inline_end_style: style,
173            border_inline_end_color: color,
174        })
175    }
176
177    impl<'a> ToCss for LonghandsToSerialize<'a> {
178        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
179        where
180            W: fmt::Write,
181        {
182            // FIXME: Should serialize empty if start != end, right?
183            super::serialize_directional_border(
184                dest,
185                self.border_inline_start_width,
186                self.border_inline_start_style,
187                self.border_inline_start_color,
188            )
189        }
190    }
191}
192
193pub mod border_radius {
194    pub use crate::properties::generated::shorthands::border_radius::*;
195
196    use super::*;
197    use crate::values::generics::border::BorderCornerRadius;
198    use crate::values::generics::rect::Rect;
199    use crate::values::specified::BorderRadius;
200
201    pub fn parse_value(
202        context: &ParserContext,
203        input: &mut Parser,
204    ) -> Result<Longhands, ParseError> {
205        let radii = BorderRadius::parse(context, input)?;
206        Ok(expanded! {
207            border_top_left_radius: radii.top_left,
208            border_top_right_radius: radii.top_right,
209            border_bottom_right_radius: radii.bottom_right,
210            border_bottom_left_radius: radii.bottom_left,
211        })
212    }
213
214    impl<'a> ToCss for LonghandsToSerialize<'a> {
215        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
216        where
217            W: fmt::Write,
218        {
219            let LonghandsToSerialize {
220                border_top_left_radius: BorderCornerRadius(tl),
221                border_top_right_radius: BorderCornerRadius(tr),
222                border_bottom_right_radius: BorderCornerRadius(br),
223                border_bottom_left_radius: BorderCornerRadius(bl),
224            } = *self;
225
226            let widths = Rect::new(tl.width(), tr.width(), br.width(), bl.width());
227            let heights = Rect::new(tl.height(), tr.height(), br.height(), bl.height());
228
229            BorderRadius::serialize_rects(widths, heights, dest)
230        }
231    }
232}
233
234pub mod corner_shape {
235    pub use crate::properties::generated::shorthands::corner_shape::*;
236
237    use super::*;
238    use crate::values::generics::rect::Rect;
239    use crate::values::specified::CornerShape;
240
241    /// Parses 1-4 `<corner-shape-value>` tokens with the standard CSS 4-side
242    /// shorthand expansion (top, right, bottom, left).
243    pub fn parse_value(
244        context: &ParserContext,
245        input: &mut Parser,
246    ) -> Result<Longhands, ParseError> {
247        let rect = Rect::parse_with(context, input, CornerShape::parse)?;
248        Ok(expanded! {
249            corner_top_left_shape: rect.0,
250            corner_top_right_shape: rect.1,
251            corner_bottom_right_shape: rect.2,
252            corner_bottom_left_shape: rect.3,
253        })
254    }
255
256    impl<'a> ToCss for LonghandsToSerialize<'a> {
257        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
258        where
259            W: fmt::Write,
260        {
261            Rect::new(
262                self.corner_top_left_shape,
263                self.corner_top_right_shape,
264                self.corner_bottom_right_shape,
265                self.corner_bottom_left_shape,
266            )
267            .to_css(dest)
268        }
269    }
270}
271
272pub mod border_image {
273    pub use crate::properties::generated::shorthands::border_image::*;
274
275    use super::*;
276    use crate::properties::longhands::{
277        border_image_outset, border_image_repeat, border_image_slice, border_image_source,
278        border_image_width,
279    };
280
281    pub fn parse_value(
282        context: &ParserContext,
283        input: &mut Parser,
284    ) -> Result<Longhands, ParseError> {
285        let mut outset = border_image_outset::get_initial_specified_value();
286        let mut repeat = border_image_repeat::get_initial_specified_value();
287        let mut slice = border_image_slice::get_initial_specified_value();
288        let mut source = border_image_source::get_initial_specified_value();
289        let mut width = border_image_width::get_initial_specified_value();
290        let mut any = false;
291        let mut parsed_slice = false;
292        let mut parsed_source = false;
293        let mut parsed_repeat = false;
294        loop {
295            if !parsed_slice
296                && let Ok(value) =
297                    input.try_parse(|input| border_image_slice::parse(context, input))
298            {
299                parsed_slice = true;
300                any = true;
301                slice = value;
302                // Parse border image width and outset, if applicable.
303                let maybe_width_outset: Result<_, ParseError> = input.try_parse(|input| {
304                    input.expect_delim('/')?;
305
306                    // Parse border image width, if applicable.
307                    let w = input
308                        .try_parse(|input| border_image_width::parse(context, input))
309                        .ok();
310
311                    // Parse border image outset if applicable.
312                    let o = input
313                        .try_parse(|input| {
314                            input.expect_delim('/')?;
315                            border_image_outset::parse(context, input)
316                        })
317                        .ok();
318                    if w.is_none() && o.is_none() {
319                        return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
320                    }
321                    Ok((w, o))
322                });
323                if let Ok((w, o)) = maybe_width_outset {
324                    if let Some(w) = w {
325                        width = w;
326                    }
327                    if let Some(o) = o {
328                        outset = o;
329                    }
330                }
331                continue;
332            }
333            if !parsed_source
334                && let Ok(value) =
335                    input.try_parse(|input| border_image_source::parse(context, input))
336            {
337                source = value;
338                parsed_source = true;
339                any = true;
340                continue;
341            }
342            if !parsed_repeat
343                && let Ok(value) =
344                    input.try_parse(|input| border_image_repeat::parse(context, input))
345            {
346                repeat = value;
347                parsed_repeat = true;
348                any = true;
349                continue;
350            }
351            break;
352        }
353        if !any {
354            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
355        }
356        Ok(expanded! {
357           border_image_outset: outset,
358           border_image_repeat: repeat,
359           border_image_slice: slice,
360           border_image_source: source,
361           border_image_width: width,
362        })
363    }
364
365    impl<'a> ToCss for LonghandsToSerialize<'a> {
366        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
367        where
368            W: fmt::Write,
369        {
370            let mut has_any = false;
371            let has_source =
372                *self.border_image_source != border_image_source::get_initial_specified_value();
373            has_any = has_any || has_source;
374            let has_slice =
375                *self.border_image_slice != border_image_slice::get_initial_specified_value();
376            has_any = has_any || has_slice;
377            let has_outset =
378                *self.border_image_outset != border_image_outset::get_initial_specified_value();
379            has_any = has_any || has_outset;
380            let has_width =
381                *self.border_image_width != border_image_width::get_initial_specified_value();
382            has_any = has_any || has_width;
383            let has_repeat =
384                *self.border_image_repeat != border_image_repeat::get_initial_specified_value();
385            has_any = has_any || has_repeat;
386            if has_source || !has_any {
387                self.border_image_source.to_css(dest)?;
388                if !has_any {
389                    return Ok(());
390                }
391            }
392            let needs_slice = has_slice || has_width || has_outset;
393            if needs_slice {
394                if has_source {
395                    dest.write_char(' ')?;
396                }
397                self.border_image_slice.to_css(dest)?;
398                if has_width || has_outset {
399                    dest.write_str(" /")?;
400                    if has_width {
401                        dest.write_char(' ')?;
402                        self.border_image_width.to_css(dest)?;
403                    }
404                    if has_outset {
405                        dest.write_str(" / ")?;
406                        self.border_image_outset.to_css(dest)?;
407                    }
408                }
409            }
410            if has_repeat {
411                if has_source || needs_slice {
412                    dest.write_char(' ')?;
413                }
414                self.border_image_repeat.to_css(dest)?;
415            }
416            Ok(())
417        }
418    }
419}
420
421pub mod border {
422    pub use crate::properties::generated::shorthands::border::*;
423
424    use super::*;
425    pub use crate::properties::generated::shorthands::border_left;
426    use crate::properties::longhands::{
427        border_image_outset, border_image_repeat, border_image_slice, border_image_source,
428        border_image_width,
429    };
430
431    pub fn parse_value(
432        context: &ParserContext,
433        input: &mut Parser,
434    ) -> Result<Longhands, ParseError> {
435        let (width, style, color) = super::parse_border(context, input)?;
436        Ok(expanded! {
437            border_top_width: width.clone(),
438            border_top_style: style,
439            border_top_color: color.clone(),
440            border_right_width: width.clone(),
441            border_right_style: style,
442            border_right_color: color.clone(),
443            border_bottom_width: width.clone(),
444            border_bottom_style: style,
445            border_bottom_color: color.clone(),
446            border_left_width: width.clone(),
447            border_left_style: style,
448            border_left_color: color.clone(),
449
450            // The 'border' shorthand resets 'border-image' to its initial value.
451            // See https://drafts.csswg.org/css-backgrounds-3/#the-border-shorthands
452            border_image_outset: border_image_outset::get_initial_specified_value(),
453            border_image_repeat: border_image_repeat::get_initial_specified_value(),
454            border_image_slice: border_image_slice::get_initial_specified_value(),
455            border_image_source: border_image_source::get_initial_specified_value(),
456            border_image_width: border_image_width::get_initial_specified_value(),
457        })
458    }
459
460    impl<'a> ToCss for LonghandsToSerialize<'a> {
461        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
462        where
463            W: fmt::Write,
464        {
465            use crate::properties::longhands;
466
467            // If any of the border-image longhands differ from their initial specified values we should not
468            // invoke serialize_directional_border(), so there is no point in continuing on to compute all_equal.
469            if *self.border_image_outset
470                != longhands::border_image_outset::get_initial_specified_value()
471            {
472                return Ok(());
473            }
474            if *self.border_image_repeat
475                != longhands::border_image_repeat::get_initial_specified_value()
476            {
477                return Ok(());
478            }
479            if *self.border_image_slice
480                != longhands::border_image_slice::get_initial_specified_value()
481            {
482                return Ok(());
483            }
484            if *self.border_image_source
485                != longhands::border_image_source::get_initial_specified_value()
486            {
487                return Ok(());
488            }
489            if *self.border_image_width
490                != longhands::border_image_width::get_initial_specified_value()
491            {
492                return Ok(());
493            }
494
495            let all_equal = {
496                let border_top_width = self.border_top_width;
497                let border_top_style = self.border_top_style;
498                let border_top_color = self.border_top_color;
499                let border_right_width = self.border_right_width;
500                let border_right_style = self.border_right_style;
501                let border_right_color = self.border_right_color;
502                let border_bottom_width = self.border_bottom_width;
503                let border_bottom_style = self.border_bottom_style;
504                let border_bottom_color = self.border_bottom_color;
505                let border_left_width = self.border_left_width;
506                let border_left_style = self.border_left_style;
507                let border_left_color = self.border_left_color;
508
509                border_top_width == border_right_width
510                    && border_right_width == border_bottom_width
511                    && border_bottom_width == border_left_width
512                    && border_top_style == border_right_style
513                    && border_right_style == border_bottom_style
514                    && border_bottom_style == border_left_style
515                    && border_top_color == border_right_color
516                    && border_right_color == border_bottom_color
517                    && border_bottom_color == border_left_color
518            };
519
520            // If all longhands are all present, then all sides should be the same,
521            // so we can just one set of color/style/width
522            if !all_equal {
523                return Ok(());
524            }
525            super::serialize_directional_border(
526                dest,
527                self.border_left_width,
528                self.border_left_style,
529                self.border_left_color,
530            )
531        }
532    }
533
534    // We need to implement this by hand because deriving this would also derive border-image,
535    // which this property only resets. Just use the same as border-left for simplicity.
536    impl SpecifiedValueInfo for Longhands {
537        const SUPPORTED_TYPES: u8 = border_left::Longhands::SUPPORTED_TYPES;
538
539        fn collect_completion_keywords(f: KeywordsCollectFn) {
540            border_left::Longhands::collect_completion_keywords(f);
541        }
542    }
543}
544
545#[cfg(feature = "gecko")]
546pub mod container {
547    use super::*;
548    pub use crate::properties::generated::shorthands::container::*;
549
550    use crate::values::specified::{ContainerName, ContainerType};
551
552    pub fn parse_value(
553        context: &ParserContext,
554        input: &mut Parser,
555    ) -> Result<Longhands, ParseError> {
556        // See https://github.com/w3c/csswg-drafts/issues/7180 for why we don't match the spec.
557        let container_name = ContainerName::parse(context, input)?;
558        let container_type = if input.try_parse(|input| input.expect_delim('/')).is_ok() {
559            ContainerType::parse(context, input)?
560        } else {
561            ContainerType::NORMAL
562        };
563        Ok(expanded! {
564            container_name: container_name,
565            container_type: container_type,
566        })
567    }
568
569    impl<'a> ToCss for LonghandsToSerialize<'a> {
570        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
571        where
572            W: fmt::Write,
573        {
574            self.container_name.to_css(dest)?;
575            if !self.container_type.is_normal() {
576                dest.write_str(" / ")?;
577                self.container_type.to_css(dest)?;
578            }
579            Ok(())
580        }
581    }
582}
583
584pub mod vertical_align {
585    use super::*;
586    pub use crate::properties::generated::shorthands::vertical_align::*;
587
588    use crate::values::specified::{AlignmentBaseline, BaselineShift, BaselineSource};
589
590    pub fn parse_value(
591        context: &ParserContext,
592        input: &mut Parser,
593    ) -> Result<Longhands, ParseError> {
594        let mut baseline_source = None;
595        let mut alignment_baseline = None;
596        let mut baseline_shift = None;
597        let mut parsed = 0;
598
599        loop {
600            parsed += 1;
601
602            try_parse_one!(input, baseline_source, BaselineSource::parse_non_auto);
603            try_parse_one!(input, alignment_baseline, AlignmentBaseline::parse);
604            try_parse_one!(context, input, baseline_shift, BaselineShift::parse);
605
606            parsed -= 1;
607            break;
608        }
609
610        if parsed == 0 {
611            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
612        }
613
614        Ok(expanded! {
615            baseline_source: baseline_source.unwrap_or(BaselineSource::Auto),
616            alignment_baseline: alignment_baseline.unwrap_or(AlignmentBaseline::Baseline),
617            baseline_shift: baseline_shift.unwrap_or(BaselineShift::zero()),
618        })
619    }
620
621    impl<'a> ToCss for LonghandsToSerialize<'a> {
622        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
623        where
624            W: fmt::Write,
625        {
626            let mut writer = SequenceWriter::new(dest, " ");
627            if *self.baseline_source != BaselineSource::Auto {
628                writer.item(self.baseline_source)?;
629            }
630            if *self.alignment_baseline != AlignmentBaseline::Baseline {
631                writer.item(self.alignment_baseline)?;
632            }
633            if *self.baseline_shift != BaselineShift::zero() {
634                writer.item(self.baseline_shift)?;
635            }
636            if !writer.has_written() {
637                self.alignment_baseline.to_css(dest)?;
638            }
639            Ok(())
640        }
641    }
642}
643
644#[cfg(feature = "gecko")]
645pub mod offset {
646    use super::*;
647    use crate::Zero;
648    pub use crate::properties::generated::shorthands::offset::*;
649    use crate::values::specified::{
650        LengthPercentage, OffsetPath, OffsetPosition, OffsetRotate, PositionOrAuto,
651    };
652
653    pub fn parse_value(
654        context: &ParserContext,
655        input: &mut Parser,
656    ) -> Result<Longhands, ParseError> {
657        let offset_position = input.try_parse(|i| OffsetPosition::parse(context, i)).ok();
658        let offset_path = input.try_parse(|i| OffsetPath::parse(context, i)).ok();
659
660        // Must have one of [offset-position, offset-path].
661        // FIXME: The syntax is out-of-date after the update of the spec.
662        if offset_position.is_none() && offset_path.is_none() {
663            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
664        }
665
666        let mut offset_distance = None;
667        let mut offset_rotate = None;
668        // offset-distance and offset-rotate are grouped with offset-path.
669        if offset_path.is_some() {
670            loop {
671                if offset_distance.is_none()
672                    && let Ok(value) = input.try_parse(|i| LengthPercentage::parse(context, i))
673                {
674                    offset_distance = Some(value);
675                }
676
677                if offset_rotate.is_none()
678                    && let Ok(value) = input.try_parse(|i| OffsetRotate::parse(context, i))
679                {
680                    offset_rotate = Some(value);
681                    continue;
682                }
683                break;
684            }
685        }
686
687        let offset_anchor = input
688            .try_parse(|i| {
689                i.expect_delim('/')?;
690                PositionOrAuto::parse(context, i)
691            })
692            .ok();
693
694        Ok(expanded! {
695            offset_position: offset_position.unwrap_or(OffsetPosition::normal()),
696            offset_path: offset_path.unwrap_or(OffsetPath::none()),
697            offset_distance: offset_distance.unwrap_or(LengthPercentage::zero()),
698            offset_rotate: offset_rotate.unwrap_or(OffsetRotate::auto()),
699            offset_anchor: offset_anchor.unwrap_or(PositionOrAuto::auto()),
700        })
701    }
702
703    impl<'a> ToCss for LonghandsToSerialize<'a> {
704        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
705        where
706            W: fmt::Write,
707        {
708            // The basic concept is: we must serialize offset-position or offset-path group.
709            // offset-path group means "offset-path offset-distance offset-rotate".
710            let must_serialize_path = *self.offset_path != OffsetPath::None
711                || (!self.offset_distance.is_zero() || !self.offset_rotate.is_auto());
712            let position_is_default = matches!(self.offset_position, OffsetPosition::Normal);
713            if !position_is_default || !must_serialize_path {
714                self.offset_position.to_css(dest)?;
715            }
716
717            if must_serialize_path {
718                if !position_is_default {
719                    dest.write_char(' ')?;
720                }
721                self.offset_path.to_css(dest)?;
722            }
723
724            if !self.offset_distance.is_zero() {
725                dest.write_char(' ')?;
726                self.offset_distance.to_css(dest)?;
727            }
728
729            if !self.offset_rotate.is_auto() {
730                dest.write_char(' ')?;
731                self.offset_rotate.to_css(dest)?;
732            }
733
734            if *self.offset_anchor != PositionOrAuto::auto() {
735                dest.write_str(" / ")?;
736                self.offset_anchor.to_css(dest)?;
737            }
738            Ok(())
739        }
740    }
741}
742
743pub mod columns {
744    pub use crate::properties::generated::shorthands::columns::*;
745
746    use super::*;
747    use crate::properties::longhands::{column_count, column_width};
748
749    pub fn parse_value(
750        context: &ParserContext,
751        input: &mut Parser,
752    ) -> Result<Longhands, ParseError> {
753        let mut column_count = None;
754        let mut column_width = None;
755        let mut autos = 0;
756
757        loop {
758            if input
759                .try_parse(|input| input.expect_ident_matching("auto"))
760                .is_ok()
761            {
762                // Leave the options to None, 'auto' is the initial value.
763                autos += 1;
764                continue;
765            }
766
767            if column_count.is_none()
768                && let Ok(value) = input.try_parse(|input| column_count::parse(context, input))
769            {
770                column_count = Some(value);
771                continue;
772            }
773
774            if column_width.is_none()
775                && let Ok(value) = input.try_parse(|input| column_width::parse(context, input))
776            {
777                column_width = Some(value);
778                continue;
779            }
780
781            break;
782        }
783
784        let values = autos + column_count.iter().len() + column_width.iter().len();
785        if values == 0 || values > 2 {
786            Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError))
787        } else {
788            Ok(expanded! {
789                column_count: unwrap_or_initial!(column_count),
790                column_width: unwrap_or_initial!(column_width),
791            })
792        }
793    }
794
795    impl<'a> ToCss for LonghandsToSerialize<'a> {
796        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
797        where
798            W: fmt::Write,
799        {
800            if self.column_width.is_auto() {
801                return self.column_count.to_css(dest);
802            }
803            self.column_width.to_css(dest)?;
804            if !self.column_count.is_auto() {
805                dest.write_char(' ')?;
806                self.column_count.to_css(dest)?;
807            }
808            Ok(())
809        }
810    }
811}
812
813#[cfg(feature = "gecko")]
814pub mod column_rule {
815    pub use crate::properties::generated::shorthands::column_rule::*;
816
817    use super::*;
818    use crate::properties::longhands::column_rule_color;
819    use crate::properties::longhands::{column_rule_style, column_rule_width};
820
821    pub fn parse_value(
822        context: &ParserContext,
823        input: &mut Parser,
824    ) -> Result<Longhands, ParseError> {
825        let mut column_rule_width = None;
826        let mut column_rule_style = None;
827        let mut column_rule_color = None;
828        let mut parsed = 0;
829        loop {
830            parsed += 1;
831            try_parse_one!(context, input, column_rule_width, column_rule_width::parse);
832            try_parse_one!(context, input, column_rule_style, column_rule_style::parse);
833            try_parse_one!(context, input, column_rule_color, column_rule_color::parse);
834            parsed -= 1;
835            break;
836        }
837        if parsed == 0 {
838            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
839        }
840        Ok(expanded! {
841            column_rule_width: unwrap_or_initial!(column_rule_width),
842            column_rule_style: unwrap_or_initial!(column_rule_style),
843            column_rule_color: unwrap_or_initial!(column_rule_color),
844        })
845    }
846}
847
848pub mod text_wrap {
849    pub use crate::properties::generated::shorthands::text_wrap::*;
850
851    use super::*;
852    use crate::properties::longhands::{text_wrap_mode, text_wrap_style};
853
854    pub fn parse_value(
855        context: &ParserContext,
856        input: &mut Parser,
857    ) -> Result<Longhands, ParseError> {
858        let mut mode = None;
859        let mut style = None;
860        let mut parsed = 0;
861        loop {
862            parsed += 1;
863            try_parse_one!(context, input, mode, text_wrap_mode::parse);
864            try_parse_one!(context, input, style, text_wrap_style::parse);
865            parsed -= 1;
866            break;
867        }
868        if parsed == 0 {
869            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
870        }
871        Ok(expanded! {
872            text_wrap_mode: unwrap_or_initial!(text_wrap_mode, mode),
873            text_wrap_style: unwrap_or_initial!(text_wrap_style, style),
874        })
875    }
876
877    impl<'a> ToCss for LonghandsToSerialize<'a> {
878        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
879        where
880            W: fmt::Write,
881        {
882            use text_wrap_mode::computed_value::T as Mode;
883            use text_wrap_style::computed_value::T as Style;
884
885            if matches!(self.text_wrap_style, &Style::Auto) {
886                return self.text_wrap_mode.to_css(dest);
887            }
888
889            if *self.text_wrap_mode != Mode::Wrap {
890                self.text_wrap_mode.to_css(dest)?;
891                dest.write_char(' ')?;
892            }
893
894            self.text_wrap_style.to_css(dest)
895        }
896    }
897}
898
899pub mod white_space {
900    pub use crate::properties::generated::shorthands::white_space::*;
901
902    use super::*;
903    use crate::properties::longhands::{text_wrap_mode, white_space_collapse};
904
905    pub fn parse_value(
906        context: &ParserContext,
907        input: &mut Parser,
908    ) -> Result<Longhands, ParseError> {
909        use text_wrap_mode::computed_value::T as Wrap;
910        use white_space_collapse::computed_value::T as Collapse;
911
912        fn parse_special_shorthands(input: &mut Parser) -> Result<Longhands, ParseError> {
913            let (mode, collapse) = try_match_ident_ignore_ascii_case! { input,
914                "normal" => (Wrap::Wrap, Collapse::Collapse),
915                "pre" => (Wrap::Nowrap, Collapse::Preserve),
916                "pre-wrap" => (Wrap::Wrap, Collapse::Preserve),
917                "pre-line" => (Wrap::Wrap, Collapse::PreserveBreaks),
918            };
919            Ok(expanded! {
920                text_wrap_mode: mode,
921                white_space_collapse: collapse,
922            })
923        }
924
925        if let Ok(result) = input.try_parse(parse_special_shorthands) {
926            return Ok(result);
927        }
928
929        let mut wrap = None;
930        let mut collapse = None;
931        let mut parsed = 0;
932
933        loop {
934            parsed += 1;
935            try_parse_one!(context, input, wrap, text_wrap_mode::parse);
936            try_parse_one!(context, input, collapse, white_space_collapse::parse);
937            parsed -= 1;
938            break;
939        }
940
941        if parsed == 0 {
942            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
943        }
944
945        Ok(expanded! {
946            text_wrap_mode: unwrap_or_initial!(text_wrap_mode, wrap),
947            white_space_collapse: unwrap_or_initial!(white_space_collapse, collapse),
948        })
949    }
950
951    impl<'a> ToCss for LonghandsToSerialize<'a> {
952        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
953        where
954            W: fmt::Write,
955        {
956            use text_wrap_mode::computed_value::T as Wrap;
957            use white_space_collapse::computed_value::T as Collapse;
958
959            match *self.text_wrap_mode {
960                Wrap::Wrap => match *self.white_space_collapse {
961                    Collapse::Collapse => return dest.write_str("normal"),
962                    Collapse::Preserve => return dest.write_str("pre-wrap"),
963                    Collapse::PreserveBreaks => return dest.write_str("pre-line"),
964                    _ => (),
965                },
966                Wrap::Nowrap => {
967                    if let Collapse::Preserve = *self.white_space_collapse {
968                        return dest.write_str("pre");
969                    }
970                },
971            }
972
973            let mut has_value = false;
974            if *self.white_space_collapse != Collapse::Collapse {
975                self.white_space_collapse.to_css(dest)?;
976                has_value = true;
977            }
978
979            if *self.text_wrap_mode != Wrap::Wrap {
980                if has_value {
981                    dest.write_char(' ')?;
982                }
983                self.text_wrap_mode.to_css(dest)?;
984            }
985
986            Ok(())
987        }
988    }
989
990    impl SpecifiedValueInfo for Longhands {
991        fn collect_completion_keywords(f: KeywordsCollectFn) {
992            // Collect keywords from our longhands.
993            text_wrap_mode::SpecifiedValue::collect_completion_keywords(f);
994            white_space_collapse::SpecifiedValue::collect_completion_keywords(f);
995
996            // Add the special values supported only by the shorthand
997            // (see parse_special_shorthands() above).
998            f(&["normal", "pre", "pre-wrap", "pre-line"])
999        }
1000    }
1001}
1002
1003#[cfg(feature = "gecko")]
1004pub mod _webkit_text_stroke {
1005    pub use crate::properties::generated::shorthands::_webkit_text_stroke::*;
1006
1007    use super::*;
1008    use crate::properties::longhands::{_webkit_text_stroke_color, _webkit_text_stroke_width};
1009
1010    pub fn parse_value(
1011        context: &ParserContext,
1012        input: &mut Parser,
1013    ) -> Result<Longhands, ParseError> {
1014        let mut color = None;
1015        let mut width = None;
1016        let mut parsed = 0;
1017        loop {
1018            parsed += 1;
1019            try_parse_one!(context, input, color, _webkit_text_stroke_color::parse);
1020            try_parse_one!(context, input, width, _webkit_text_stroke_width::parse);
1021            parsed -= 1;
1022            break;
1023        }
1024        if parsed == 0 {
1025            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
1026        }
1027        Ok(expanded! {
1028            _webkit_text_stroke_color: unwrap_or_initial!(_webkit_text_stroke_color, color),
1029            _webkit_text_stroke_width: unwrap_or_initial!(_webkit_text_stroke_width, width),
1030        })
1031    }
1032}
1033
1034pub mod list_style {
1035    pub use crate::properties::generated::shorthands::list_style::*;
1036
1037    use super::*;
1038    use crate::properties::longhands::{list_style_image, list_style_position, list_style_type};
1039    use crate::values::specified::Image;
1040    use selectors::parser::SelectorParseErrorKind;
1041
1042    pub fn parse_value(
1043        context: &ParserContext,
1044        input: &mut Parser,
1045    ) -> Result<Longhands, ParseError> {
1046        // `none` is ambiguous until we've finished parsing the shorthands, so we count the number
1047        // of times we see it.
1048        let mut nones = 0u8;
1049        let (mut image, mut position, mut list_style_type) = (None, None, None);
1050        let mut parsed = 0;
1051        loop {
1052            parsed += 1;
1053
1054            if input
1055                .try_parse(|input| input.expect_ident_matching("none"))
1056                .is_ok()
1057            {
1058                nones += 1;
1059                if nones > 2 {
1060                    return Err(ParseError::custom(SelectorParseErrorKind::UnexpectedIdent));
1061                }
1062                continue;
1063            }
1064
1065            try_parse_one!(context, input, image, list_style_image::parse);
1066            try_parse_one!(context, input, position, list_style_position::parse);
1067            // list-style-type must be checked the last, because it accepts
1068            // arbitrary identifier for custom counter style, and thus may
1069            // affect values of list-style-position.
1070            try_parse_one!(context, input, list_style_type, list_style_type::parse);
1071
1072            parsed -= 1;
1073            break;
1074        }
1075
1076        let position = unwrap_or_initial!(list_style_position, position);
1077
1078        if parsed == 0 {
1079            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
1080        }
1081
1082        // If there are two `none`s, then we can't have a type or image; if there is one `none`,
1083        // then we can't have both a type *and* an image; if there is no `none` then we're fine as
1084        // long as we parsed something.
1085        use self::list_style_type::SpecifiedValue as ListStyleType;
1086        match (nones, list_style_type, image) {
1087            (2, None, None) => Ok(expanded! {
1088                list_style_position: position,
1089                list_style_image: Image::None,
1090                list_style_type: ListStyleType::none(),
1091            }),
1092            (1, None, Some(image)) => Ok(expanded! {
1093                list_style_position: position,
1094                list_style_image: image,
1095                list_style_type: ListStyleType::none(),
1096            }),
1097            (1, Some(list_style_type), None) => Ok(expanded! {
1098                list_style_position: position,
1099                list_style_image: Image::None,
1100                list_style_type: list_style_type,
1101            }),
1102            (1, None, None) => Ok(expanded! {
1103                list_style_position: position,
1104                list_style_image: Image::None,
1105                list_style_type: ListStyleType::none(),
1106            }),
1107            (0, list_style_type, image) => Ok(expanded! {
1108                list_style_position: position,
1109                list_style_image: unwrap_or_initial!(list_style_image, image),
1110                list_style_type: unwrap_or_initial!(list_style_type),
1111            }),
1112            _ => Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError)),
1113        }
1114    }
1115
1116    impl<'a> ToCss for LonghandsToSerialize<'a> {
1117        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1118        where
1119            W: fmt::Write,
1120        {
1121            use list_style_image::SpecifiedValue as ListStyleImage;
1122            use list_style_position::SpecifiedValue as ListStylePosition;
1123            use list_style_type::SpecifiedValue as ListStyleType;
1124
1125            let mut writer = SequenceWriter::new(dest, " ");
1126            if *self.list_style_position != ListStylePosition::Outside
1127                || self.list_style_type.is_name(&atom!("outside"))
1128            {
1129                writer.item(self.list_style_position)?;
1130            }
1131            if *self.list_style_image != ListStyleImage::None {
1132                writer.item(self.list_style_image)?;
1133            }
1134            if *self.list_style_type != ListStyleType::disc() {
1135                writer.item(self.list_style_type)?;
1136            }
1137            if !writer.has_written() {
1138                self.list_style_position.to_css(dest)?;
1139            }
1140            Ok(())
1141        }
1142    }
1143}
1144
1145pub mod gap {
1146    pub use crate::properties::generated::shorthands::gap::*;
1147
1148    use super::*;
1149    use crate::properties::longhands::{column_gap, row_gap};
1150
1151    pub fn parse_value(
1152        context: &ParserContext,
1153        input: &mut Parser,
1154    ) -> Result<Longhands, ParseError> {
1155        let r_gap = row_gap::parse(context, input)?;
1156        let c_gap = input
1157            .try_parse(|input| column_gap::parse(context, input))
1158            .unwrap_or(r_gap.clone());
1159
1160        Ok(expanded! {
1161            row_gap: r_gap,
1162            column_gap: c_gap,
1163        })
1164    }
1165
1166    impl<'a> ToCss for LonghandsToSerialize<'a> {
1167        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1168        where
1169            W: fmt::Write,
1170        {
1171            self.row_gap.to_css(dest)?;
1172            if self.row_gap != self.column_gap {
1173                dest.write_char(' ')?;
1174                self.column_gap.to_css(dest)?;
1175            }
1176            Ok(())
1177        }
1178    }
1179}
1180
1181#[cfg(feature = "gecko")]
1182pub mod marker {
1183    pub use crate::properties::generated::shorthands::marker::*;
1184
1185    use super::*;
1186    use crate::values::specified::url::UrlOrNone;
1187
1188    pub fn parse_value(
1189        context: &ParserContext,
1190        input: &mut Parser,
1191    ) -> Result<Longhands, ParseError> {
1192        let url = UrlOrNone::parse(context, input)?;
1193
1194        Ok(expanded! {
1195            marker_start: url.clone(),
1196            marker_mid: url.clone(),
1197            marker_end: url,
1198        })
1199    }
1200
1201    impl<'a> ToCss for LonghandsToSerialize<'a> {
1202        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1203        where
1204            W: fmt::Write,
1205        {
1206            if self.marker_start == self.marker_mid && self.marker_mid == self.marker_end {
1207                self.marker_start.to_css(dest)
1208            } else {
1209                Ok(())
1210            }
1211        }
1212    }
1213}
1214
1215pub mod flex_flow {
1216    pub use crate::properties::generated::shorthands::flex_flow::*;
1217
1218    use super::*;
1219    use crate::properties::longhands::{flex_direction, flex_wrap};
1220
1221    pub fn parse_value(
1222        context: &ParserContext,
1223        input: &mut Parser,
1224    ) -> Result<Longhands, ParseError> {
1225        let mut parsed = 0;
1226        let mut direction = None;
1227        let mut wrap = None;
1228        loop {
1229            parsed += 1;
1230            try_parse_one!(context, input, direction, flex_direction::parse);
1231            try_parse_one!(context, input, wrap, flex_wrap::parse);
1232            parsed -= 1;
1233            break;
1234        }
1235        if parsed == 0 {
1236            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
1237        }
1238        Ok(expanded! {
1239            flex_direction: unwrap_or_initial!(flex_direction, direction),
1240            flex_wrap: unwrap_or_initial!(flex_wrap, wrap),
1241        })
1242    }
1243
1244    impl<'a> ToCss for LonghandsToSerialize<'a> {
1245        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1246        where
1247            W: fmt::Write,
1248        {
1249            if *self.flex_direction == flex_direction::get_initial_specified_value()
1250                && *self.flex_wrap != flex_wrap::get_initial_specified_value()
1251            {
1252                return self.flex_wrap.to_css(dest);
1253            }
1254            self.flex_direction.to_css(dest)?;
1255            if *self.flex_wrap != flex_wrap::get_initial_specified_value() {
1256                dest.write_char(' ')?;
1257                self.flex_wrap.to_css(dest)?;
1258            }
1259            Ok(())
1260        }
1261    }
1262}
1263
1264pub mod flex {
1265    pub use crate::properties::generated::shorthands::flex::*;
1266
1267    use super::*;
1268    use crate::properties::longhands::flex_basis::SpecifiedValue as FlexBasis;
1269    use crate::values::specified::NonNegativeNumber;
1270
1271    fn parse_flexibility(
1272        context: &ParserContext,
1273        input: &mut Parser,
1274    ) -> Result<(NonNegativeNumber, Option<NonNegativeNumber>), ParseError> {
1275        let grow = NonNegativeNumber::parse(context, input)?;
1276        let shrink = input
1277            .try_parse(|i| NonNegativeNumber::parse(context, i))
1278            .ok();
1279        Ok((grow, shrink))
1280    }
1281
1282    pub fn parse_value(
1283        context: &ParserContext,
1284        input: &mut Parser,
1285    ) -> Result<Longhands, ParseError> {
1286        let mut grow = None;
1287        let mut shrink = None;
1288        let mut basis = None;
1289
1290        if input
1291            .try_parse(|input| input.expect_ident_matching("none"))
1292            .is_ok()
1293        {
1294            return Ok(expanded! {
1295                flex_grow: NonNegativeNumber::new(0.0),
1296                flex_shrink: NonNegativeNumber::new(0.0),
1297                flex_basis: FlexBasis::auto(),
1298            });
1299        }
1300        loop {
1301            if grow.is_none()
1302                && let Ok((flex_grow, flex_shrink)) =
1303                    input.try_parse(|i| parse_flexibility(context, i))
1304            {
1305                grow = Some(flex_grow);
1306                shrink = flex_shrink;
1307                continue;
1308            }
1309            if basis.is_none()
1310                && let Ok(value) = input.try_parse(|input| FlexBasis::parse(context, input))
1311            {
1312                basis = Some(value);
1313                continue;
1314            }
1315            break;
1316        }
1317
1318        if grow.is_none() && basis.is_none() {
1319            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
1320        }
1321        Ok(expanded! {
1322            flex_grow: grow.unwrap_or(NonNegativeNumber::new(1.0)),
1323            flex_shrink: shrink.unwrap_or(NonNegativeNumber::new(1.0)),
1324            flex_basis: basis.unwrap_or(FlexBasis::zero_percent()),
1325        })
1326    }
1327}
1328
1329pub mod place_content {
1330    pub use crate::properties::generated::shorthands::place_content::*;
1331
1332    use super::*;
1333    use crate::values::specified::align::ContentDistribution;
1334
1335    pub fn parse_value(
1336        context: &ParserContext,
1337        input: &mut Parser,
1338    ) -> Result<Longhands, ParseError> {
1339        let align_content = ContentDistribution::parse_block(context, input)?;
1340        let justify_content =
1341            input.try_parse(|input| ContentDistribution::parse_inline(context, input));
1342
1343        let justify_content = match justify_content {
1344            Ok(v) => v,
1345            Err(..) => {
1346                if !align_content.is_baseline_position() {
1347                    align_content
1348                } else {
1349                    ContentDistribution::start()
1350                }
1351            },
1352        };
1353
1354        Ok(expanded! {
1355            align_content: align_content,
1356            justify_content: justify_content,
1357        })
1358    }
1359
1360    impl<'a> ToCss for LonghandsToSerialize<'a> {
1361        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1362        where
1363            W: fmt::Write,
1364        {
1365            self.align_content.to_css(dest)?;
1366            if self.align_content != self.justify_content {
1367                dest.write_char(' ')?;
1368                self.justify_content.to_css(dest)?;
1369            }
1370            Ok(())
1371        }
1372    }
1373}
1374
1375pub mod place_self {
1376    pub use crate::properties::generated::shorthands::place_self::*;
1377
1378    use super::*;
1379    use crate::values::specified::align::SelfAlignment;
1380
1381    pub fn parse_value(
1382        context: &ParserContext,
1383        input: &mut Parser,
1384    ) -> Result<Longhands, ParseError> {
1385        let align = SelfAlignment::parse_block(context, input)?;
1386        let justify = input.try_parse(|input| SelfAlignment::parse_inline(context, input));
1387
1388        let justify = match justify {
1389            Ok(v) => v,
1390            Err(..) => {
1391                debug_assert!(align.is_valid_on_both_axes());
1392                align
1393            },
1394        };
1395
1396        Ok(expanded! {
1397            align_self: align,
1398            justify_self: justify,
1399        })
1400    }
1401
1402    impl<'a> ToCss for LonghandsToSerialize<'a> {
1403        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1404        where
1405            W: fmt::Write,
1406        {
1407            self.align_self.to_css(dest)?;
1408            if self.align_self != self.justify_self {
1409                dest.write_char(' ')?;
1410                self.justify_self.to_css(dest)?;
1411            }
1412            Ok(())
1413        }
1414    }
1415}
1416
1417pub mod place_items {
1418    pub use crate::properties::generated::shorthands::place_items::*;
1419
1420    use super::*;
1421    use crate::values::specified::align::{ItemPlacement, JustifyItems};
1422
1423    pub fn parse_value(
1424        context: &ParserContext,
1425        input: &mut Parser,
1426    ) -> Result<Longhands, ParseError> {
1427        let align = ItemPlacement::parse_block(context, input)?;
1428        let justify = input
1429            .try_parse(|input| ItemPlacement::parse_inline(context, input))
1430            .unwrap_or(align);
1431
1432        Ok(expanded! {
1433            align_items: align,
1434            justify_items: JustifyItems(justify),
1435        })
1436    }
1437
1438    impl<'a> ToCss for LonghandsToSerialize<'a> {
1439        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1440        where
1441            W: fmt::Write,
1442        {
1443            self.align_items.to_css(dest)?;
1444            if self.align_items != &self.justify_items.0 {
1445                dest.write_char(' ')?;
1446                self.justify_items.to_css(dest)?;
1447            }
1448            Ok(())
1449        }
1450    }
1451}
1452
1453pub mod grid_row {
1454    pub use crate::properties::generated::shorthands::grid_row::*;
1455
1456    use super::*;
1457    use crate::Zero;
1458    use crate::values::specified::GridLine;
1459
1460    pub fn parse_value(
1461        context: &ParserContext,
1462        input: &mut Parser,
1463    ) -> Result<Longhands, ParseError> {
1464        let start = input.try_parse(|i| GridLine::parse(context, i))?;
1465        let end = if input.try_parse(|i| i.expect_delim('/')).is_ok() {
1466            GridLine::parse(context, input)?
1467        } else {
1468            let mut line = GridLine::auto();
1469            if start.line_num.is_zero() && !start.is_span {
1470                line.ident = start.ident.clone();
1471            }
1472
1473            line
1474        };
1475
1476        Ok(expanded! {
1477            grid_row_start: start,
1478            grid_row_end: end,
1479        })
1480    }
1481
1482    impl<'a> ToCss for LonghandsToSerialize<'a> {
1483        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1484        where
1485            W: fmt::Write,
1486        {
1487            self.grid_row_start.to_css(dest)?;
1488            if self.grid_row_start.can_omit(self.grid_row_end) {
1489                return Ok(());
1490            }
1491            dest.write_str(" / ")?;
1492            self.grid_row_end.to_css(dest)
1493        }
1494    }
1495}
1496
1497pub mod grid_column {
1498    pub use crate::properties::generated::shorthands::grid_column::*;
1499
1500    use super::*;
1501    use crate::Zero;
1502    use crate::values::specified::GridLine;
1503
1504    pub fn parse_value(
1505        context: &ParserContext,
1506        input: &mut Parser,
1507    ) -> Result<Longhands, ParseError> {
1508        let start = input.try_parse(|i| GridLine::parse(context, i))?;
1509        let end = if input.try_parse(|i| i.expect_delim('/')).is_ok() {
1510            GridLine::parse(context, input)?
1511        } else {
1512            let mut line = GridLine::auto();
1513            if start.line_num.is_zero() && !start.is_span {
1514                line.ident = start.ident.clone();
1515            }
1516
1517            line
1518        };
1519
1520        Ok(expanded! {
1521            grid_column_start: start,
1522            grid_column_end: end,
1523        })
1524    }
1525
1526    impl<'a> ToCss for LonghandsToSerialize<'a> {
1527        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1528        where
1529            W: fmt::Write,
1530        {
1531            self.grid_column_start.to_css(dest)?;
1532            if self.grid_column_start.can_omit(self.grid_column_end) {
1533                return Ok(());
1534            }
1535            dest.write_str(" / ")?;
1536            self.grid_column_end.to_css(dest)
1537        }
1538    }
1539}
1540
1541pub mod grid_area {
1542    pub use crate::properties::generated::shorthands::grid_area::*;
1543
1544    use super::*;
1545    use crate::Zero;
1546    use crate::values::specified::GridLine;
1547
1548    pub fn parse_value(
1549        context: &ParserContext,
1550        input: &mut Parser,
1551    ) -> Result<Longhands, ParseError> {
1552        fn line_with_ident_from(other: &GridLine) -> GridLine {
1553            let mut this = GridLine::auto();
1554            if other.line_num.is_zero() && !other.is_span {
1555                this.ident = other.ident.clone();
1556            }
1557
1558            this
1559        }
1560
1561        let row_start = input.try_parse(|i| GridLine::parse(context, i))?;
1562        let (column_start, row_end, column_end) =
1563            if input.try_parse(|i| i.expect_delim('/')).is_ok() {
1564                let column_start = GridLine::parse(context, input)?;
1565                let (row_end, column_end) = if input.try_parse(|i| i.expect_delim('/')).is_ok() {
1566                    let row_end = GridLine::parse(context, input)?;
1567                    let column_end = if input.try_parse(|i| i.expect_delim('/')).is_ok() {
1568                        GridLine::parse(context, input)?
1569                    } else {
1570                        line_with_ident_from(&column_start)
1571                    };
1572
1573                    (row_end, column_end)
1574                } else {
1575                    let row_end = line_with_ident_from(&row_start);
1576                    let column_end = line_with_ident_from(&column_start);
1577                    (row_end, column_end)
1578                };
1579
1580                (column_start, row_end, column_end)
1581            } else {
1582                let line = line_with_ident_from(&row_start);
1583                (line.clone(), line.clone(), line)
1584            };
1585
1586        Ok(expanded! {
1587            grid_row_start: row_start,
1588            grid_row_end: row_end,
1589            grid_column_start: column_start,
1590            grid_column_end: column_end,
1591        })
1592    }
1593
1594    impl<'a> ToCss for LonghandsToSerialize<'a> {
1595        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1596        where
1597            W: fmt::Write,
1598        {
1599            self.grid_row_start.to_css(dest)?;
1600            let mut trailing_values = 3;
1601            if self.grid_column_start.can_omit(self.grid_column_end) {
1602                trailing_values -= 1;
1603                if self.grid_row_start.can_omit(self.grid_row_end) {
1604                    trailing_values -= 1;
1605                    if self.grid_row_start.can_omit(self.grid_column_start) {
1606                        trailing_values -= 1;
1607                    }
1608                }
1609            }
1610            let values = [
1611                &self.grid_column_start,
1612                &self.grid_row_end,
1613                &self.grid_column_end,
1614            ];
1615            for value in values.iter().take(trailing_values) {
1616                dest.write_str(" / ")?;
1617                value.to_css(dest)?;
1618            }
1619            Ok(())
1620        }
1621    }
1622}
1623
1624pub mod position_try {
1625    pub use crate::properties::generated::shorthands::position_try::*;
1626
1627    use super::*;
1628    use crate::values::specified::position::{PositionTryFallbacks, PositionTryOrder};
1629
1630    pub fn parse_value(
1631        context: &ParserContext,
1632        input: &mut Parser,
1633    ) -> Result<Longhands, ParseError> {
1634        let order = input.try_parse(PositionTryOrder::parse).ok();
1635        let fallbacks = PositionTryFallbacks::parse(context, input)?;
1636        Ok(expanded! {
1637            position_try_order: order.unwrap_or(PositionTryOrder::normal()),
1638            position_try_fallbacks: fallbacks,
1639        })
1640    }
1641
1642    impl<'a> ToCss for LonghandsToSerialize<'a> {
1643        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1644        where
1645            W: fmt::Write,
1646        {
1647            if !self.position_try_order.is_normal() {
1648                self.position_try_order.to_css(dest)?;
1649                dest.write_char(' ')?;
1650            }
1651            self.position_try_fallbacks.to_css(dest)
1652        }
1653    }
1654}
1655
1656#[cfg(feature = "gecko")]
1657pub mod scroll_timeline {
1658    pub use crate::properties::generated::shorthands::scroll_timeline::*;
1659
1660    use super::*;
1661    use crate::properties::longhands::{scroll_timeline_axis, scroll_timeline_name};
1662
1663    pub fn parse_value(
1664        context: &ParserContext,
1665        input: &mut Parser,
1666    ) -> Result<Longhands, ParseError> {
1667        let mut names = Vec::with_capacity(1);
1668        let mut axes = Vec::with_capacity(1);
1669        input.parse_comma_separated(|input| {
1670            let name = scroll_timeline_name::single_value::parse(context, input)?;
1671            let axis = input.try_parse(|i| scroll_timeline_axis::single_value::parse(context, i));
1672
1673            names.push(name);
1674            axes.push(axis.unwrap_or_default());
1675
1676            Ok(())
1677        })?;
1678
1679        Ok(expanded! {
1680            scroll_timeline_name: scroll_timeline_name::SpecifiedValue(names.into()),
1681            scroll_timeline_axis: scroll_timeline_axis::SpecifiedValue(axes.into()),
1682        })
1683    }
1684
1685    impl<'a> ToCss for LonghandsToSerialize<'a> {
1686        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1687        where
1688            W: fmt::Write,
1689        {
1690            if self.scroll_timeline_name.0.len() != self.scroll_timeline_axis.0.len() {
1691                return Ok(());
1692            }
1693            let mut first = true;
1694            for (name, axis) in std::iter::zip(
1695                self.scroll_timeline_name.0.iter(),
1696                self.scroll_timeline_axis.0.iter(),
1697            ) {
1698                if !first {
1699                    dest.write_str(", ")?;
1700                }
1701                name.to_css(dest)?;
1702                if !axis.is_default() {
1703                    dest.write_char(' ')?;
1704                    axis.to_css(dest)?;
1705                }
1706                first = false;
1707            }
1708            Ok(())
1709        }
1710    }
1711}
1712
1713#[cfg(feature = "gecko")]
1714pub mod view_timeline {
1715    pub use crate::properties::generated::shorthands::view_timeline::*;
1716
1717    use super::*;
1718    use crate::properties::longhands::{
1719        view_timeline_axis, view_timeline_inset, view_timeline_name,
1720    };
1721
1722    pub fn parse_value(
1723        context: &ParserContext,
1724        input: &mut Parser,
1725    ) -> Result<Longhands, ParseError> {
1726        let mut names = Vec::with_capacity(1);
1727        let mut axes = Vec::with_capacity(1);
1728        let mut insets = Vec::with_capacity(1);
1729        input.parse_comma_separated(|input| {
1730            let name = view_timeline_name::single_value::parse(context, input)?;
1731            let mut axis = None;
1732            let mut inset = None;
1733
1734            loop {
1735                try_parse_one!(
1736                    context,
1737                    input,
1738                    axis,
1739                    view_timeline_axis::single_value::parse
1740                );
1741                try_parse_one!(
1742                    context,
1743                    input,
1744                    inset,
1745                    view_timeline_inset::single_value::parse
1746                );
1747                break;
1748            }
1749
1750            names.push(name);
1751            axes.push(axis.unwrap_or_default());
1752            insets.push(inset.unwrap_or_default());
1753
1754            Ok(())
1755        })?;
1756
1757        Ok(expanded! {
1758            view_timeline_name: view_timeline_name::SpecifiedValue(names.into()),
1759            view_timeline_axis: view_timeline_axis::SpecifiedValue(axes.into()),
1760            view_timeline_inset: view_timeline_inset::SpecifiedValue(insets.into()),
1761        })
1762    }
1763
1764    impl<'a> ToCss for LonghandsToSerialize<'a> {
1765        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1766        where
1767            W: fmt::Write,
1768        {
1769            use itertools::izip;
1770            if self.view_timeline_name.0.len() != self.view_timeline_axis.0.len()
1771                || self.view_timeline_name.0.len() != self.view_timeline_inset.0.len()
1772            {
1773                return Ok(());
1774            }
1775            let mut first = true;
1776            for (name, axis, inset) in izip!(
1777                self.view_timeline_name.0.iter(),
1778                self.view_timeline_axis.0.iter(),
1779                self.view_timeline_inset.0.iter(),
1780            ) {
1781                if !first {
1782                    dest.write_str(", ")?;
1783                }
1784                name.to_css(dest)?;
1785                if !axis.is_default() {
1786                    dest.write_char(' ')?;
1787                    axis.to_css(dest)?;
1788                }
1789                if !inset.is_auto() {
1790                    dest.write_char(' ')?;
1791                    inset.to_css(dest)?;
1792                }
1793                first = false;
1794            }
1795            Ok(())
1796        }
1797    }
1798}
1799
1800#[cfg(feature = "gecko")]
1801pub mod animation_range {
1802    pub use crate::properties::generated::shorthands::animation_range::*;
1803
1804    use super::*;
1805    use crate::properties::longhands::{animation_range_end, animation_range_start};
1806    use crate::values::specified::LengthPercentage;
1807
1808    pub fn parse_value(
1809        context: &ParserContext,
1810        input: &mut Parser,
1811    ) -> Result<Longhands, ParseError> {
1812        let mut starts = Vec::with_capacity(1);
1813        let mut ends = Vec::with_capacity(1);
1814        input.parse_comma_separated(|input| {
1815            let start = animation_range_start::single_value::parse(context, input)?;
1816            let end = input
1817                .try_parse(|i| animation_range_end::single_value::parse(context, i))
1818                .unwrap_or_else(|_| {
1819                    use crate::values::generics::animation::AnimationRangeEnd;
1820                    use crate::values::specified::animation::{
1821                        AnimationRangeValue, TimelineRangeName,
1822                    };
1823
1824                    // If `<animation-range-start>` includes a timeline range name,
1825                    // `animation-range-end` is set to that same timeline range name and 100%.
1826                    // Otherwise, any omitted longhand is set to its initial value.
1827                    let name = if start.0.name.is_none() {
1828                        TimelineRangeName::Normal
1829                    } else {
1830                        start.0.name
1831                    };
1832                    AnimationRangeEnd(AnimationRangeValue::new(
1833                        name,
1834                        LengthPercentage::hundred_percent(),
1835                    ))
1836                });
1837
1838            starts.push(start);
1839            ends.push(end);
1840            Ok(())
1841        })?;
1842
1843        Ok(expanded! {
1844            animation_range_start: animation_range_start::SpecifiedValue(starts.into()),
1845            animation_range_end: animation_range_end::SpecifiedValue(ends.into()),
1846        })
1847    }
1848
1849    impl<'a> ToCss for LonghandsToSerialize<'a> {
1850        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1851        where
1852            W: fmt::Write,
1853        {
1854            use crate::values::specified::length::EqualsPercentage;
1855            let starts = &self.animation_range_start.0;
1856            let ends = &self.animation_range_end.0;
1857            if starts.len() != ends.len() {
1858                return Ok(());
1859            }
1860
1861            for (i, (start, end)) in std::iter::zip(starts.iter(), ends.iter()).enumerate() {
1862                if i != 0 {
1863                    dest.write_str(", ")?;
1864                }
1865                start.to_css(dest)?;
1866                let can_omit_end = (start.0.name == end.0.name && end.0.lp.equals_percentage(1.0))
1867                    || (start.0.name.is_none() && end.0.name.is_normal());
1868                if !can_omit_end {
1869                    dest.write_char(' ')?;
1870                    end.to_css(dest)?;
1871                }
1872            }
1873            Ok(())
1874        }
1875    }
1876}
1877
1878pub mod transition {
1879    pub use crate::properties::generated::shorthands::transition::*;
1880
1881    use super::*;
1882    use crate::properties::longhands::{
1883        transition_behavior, transition_delay, transition_duration, transition_property,
1884        transition_timing_function,
1885    };
1886    use crate::values::specified::TransitionProperty;
1887
1888    pub fn parse_value(
1889        context: &ParserContext,
1890        input: &mut Parser,
1891    ) -> Result<Longhands, ParseError> {
1892        struct SingleTransition {
1893            transition_property: transition_property::SingleSpecifiedValue,
1894            transition_duration: transition_duration::SingleSpecifiedValue,
1895            transition_timing_function: transition_timing_function::SingleSpecifiedValue,
1896            transition_delay: transition_delay::SingleSpecifiedValue,
1897            transition_behavior: transition_behavior::SingleSpecifiedValue,
1898        }
1899
1900        fn parse_one_transition(
1901            context: &ParserContext,
1902            input: &mut Parser,
1903            first: bool,
1904        ) -> Result<SingleTransition, ParseError> {
1905            let mut property = None;
1906            let mut duration = None;
1907            let mut timing_function = None;
1908            let mut delay = None;
1909            let mut behavior = None;
1910
1911            let mut parsed = 0;
1912            loop {
1913                parsed += 1;
1914
1915                try_parse_one!(
1916                    context,
1917                    input,
1918                    duration,
1919                    transition_duration::single_value::parse
1920                );
1921                try_parse_one!(
1922                    context,
1923                    input,
1924                    timing_function,
1925                    transition_timing_function::single_value::parse
1926                );
1927                try_parse_one!(context, input, delay, transition_delay::single_value::parse);
1928                try_parse_one!(
1929                    context,
1930                    input,
1931                    behavior,
1932                    transition_behavior::single_value::parse
1933                );
1934                if property.is_none() {
1935                    if let Ok(value) = input.try_parse(|i| TransitionProperty::parse(context, i)) {
1936                        property = Some(value);
1937                        continue;
1938                    }
1939
1940                    if first && input.try_parse(|i| i.expect_ident_matching("none")).is_ok() {
1941                        property = Some(TransitionProperty::none());
1942                        continue;
1943                    }
1944                }
1945
1946                parsed -= 1;
1947                break;
1948            }
1949
1950            if parsed != 0 {
1951                Ok(SingleTransition {
1952                    transition_property: property.unwrap_or_else(
1953                        transition_property::single_value::get_initial_specified_value,
1954                    ),
1955                    transition_duration: duration.unwrap_or_else(
1956                        transition_duration::single_value::get_initial_specified_value,
1957                    ),
1958                    transition_timing_function: timing_function.unwrap_or_else(
1959                        transition_timing_function::single_value::get_initial_specified_value,
1960                    ),
1961                    transition_delay: delay.unwrap_or_else(
1962                        transition_delay::single_value::get_initial_specified_value,
1963                    ),
1964                    transition_behavior: behavior.unwrap_or_else(
1965                        transition_behavior::single_value::get_initial_specified_value,
1966                    ),
1967                })
1968            } else {
1969                Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError))
1970            }
1971        }
1972
1973        let mut first = true;
1974        let mut has_transition_property_none = false;
1975        let results = input.parse_comma_separated(|i| {
1976            if has_transition_property_none {
1977                return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
1978            }
1979            let transition = parse_one_transition(context, i, first)?;
1980            first = false;
1981            has_transition_property_none = transition.transition_property.is_none();
1982            Ok(transition)
1983        })?;
1984
1985        let len = results.len();
1986        let mut property = Vec::with_capacity(len);
1987        let mut duration = Vec::with_capacity(len);
1988        let mut timing_function = Vec::with_capacity(len);
1989        let mut delay = Vec::with_capacity(len);
1990        let mut behavior = Vec::with_capacity(len);
1991        for result in results {
1992            property.push(result.transition_property);
1993            duration.push(result.transition_duration);
1994            timing_function.push(result.transition_timing_function);
1995            delay.push(result.transition_delay);
1996            behavior.push(result.transition_behavior);
1997        }
1998
1999        Ok(Longhands {
2000            transition_property: transition_property::SpecifiedValue(property.into()),
2001            transition_duration: transition_duration::SpecifiedValue(duration.into()),
2002            transition_timing_function: transition_timing_function::SpecifiedValue(
2003                timing_function.into(),
2004            ),
2005            transition_delay: transition_delay::SpecifiedValue(delay.into()),
2006            transition_behavior: transition_behavior::SpecifiedValue(behavior.into()),
2007        })
2008    }
2009
2010    impl<'a> ToCss for LonghandsToSerialize<'a> {
2011        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
2012        where
2013            W: fmt::Write,
2014        {
2015            use crate::Zero;
2016            use style_traits::values::SequenceWriter;
2017
2018            let len = self.transition_property.0.len();
2019            debug_assert_ne!(
2020                len, 0,
2021                "We should always have at least one transition-property, even if none"
2022            );
2023            if self.transition_duration.0.len() != len {
2024                return Ok(());
2025            }
2026            if self.transition_delay.0.len() != len {
2027                return Ok(());
2028            }
2029            if self.transition_timing_function.0.len() != len {
2030                return Ok(());
2031            }
2032            if self.transition_behavior.0.len() != len {
2033                return Ok(());
2034            }
2035            for i in 0..len {
2036                if i != 0 {
2037                    dest.write_str(", ")?;
2038                }
2039
2040                let has_duration = !self.transition_duration.0[i].is_zero();
2041                let has_timing = !self.transition_timing_function.0[i].is_ease();
2042                let has_delay = !self.transition_delay.0[i].is_zero();
2043                let has_behavior = !self.transition_behavior.0[i].is_normal();
2044                let has_any = has_duration || has_timing || has_delay || has_behavior;
2045
2046                let mut writer = SequenceWriter::new(dest, " ");
2047                if !self.transition_property.0[i].is_all() || !has_any {
2048                    writer.item(&self.transition_property.0[i])?;
2049                }
2050                if has_duration || has_delay {
2051                    writer.item(&self.transition_duration.0[i])?;
2052                }
2053                if has_timing {
2054                    writer.item(&self.transition_timing_function.0[i])?;
2055                }
2056                if has_delay {
2057                    writer.item(&self.transition_delay.0[i])?;
2058                }
2059                if has_behavior {
2060                    writer.item(&self.transition_behavior.0[i])?;
2061                }
2062            }
2063            Ok(())
2064        }
2065    }
2066}
2067
2068pub mod outline {
2069    pub use crate::properties::generated::shorthands::outline::*;
2070
2071    use super::*;
2072    use crate::properties::longhands::{outline_color, outline_style, outline_width};
2073
2074    pub fn parse_value(
2075        context: &ParserContext,
2076        input: &mut Parser,
2077    ) -> Result<Longhands, ParseError> {
2078        let _unused = context;
2079        let mut color = None;
2080        let mut style = None;
2081        let mut width = None;
2082        let mut parsed = 0;
2083        loop {
2084            parsed += 1;
2085            try_parse_one!(context, input, color, specified::Color::parse);
2086            try_parse_one!(context, input, style, outline_style::parse);
2087            try_parse_one!(context, input, width, outline_width::parse);
2088            parsed -= 1;
2089            break;
2090        }
2091        if parsed == 0 {
2092            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
2093        }
2094        Ok(expanded! {
2095            outline_color: unwrap_or_initial!(outline_color, color),
2096            outline_style: unwrap_or_initial!(outline_style, style),
2097            outline_width: unwrap_or_initial!(outline_width, width),
2098        })
2099    }
2100
2101    impl<'a> ToCss for LonghandsToSerialize<'a> {
2102        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
2103        where
2104            W: fmt::Write,
2105        {
2106            let mut writer = SequenceWriter::new(dest, " ");
2107            if *self.outline_color != outline_color::get_initial_specified_value() {
2108                writer.item(self.outline_color)?;
2109            }
2110            if *self.outline_style != outline_style::get_initial_specified_value() {
2111                writer.item(self.outline_style)?;
2112            }
2113            if *self.outline_width != outline_width::get_initial_specified_value() {
2114                writer.item(self.outline_width)?;
2115            }
2116            if !writer.has_written() {
2117                self.outline_style.to_css(dest)?;
2118            }
2119            Ok(())
2120        }
2121    }
2122}
2123
2124pub mod background_position {
2125    pub use crate::properties::generated::shorthands::background_position::*;
2126
2127    use super::*;
2128    use crate::properties::longhands::{background_position_x, background_position_y};
2129    use crate::values::specified::AllowQuirks;
2130    use crate::values::specified::position::Position;
2131
2132    pub fn parse_value(
2133        context: &ParserContext,
2134        input: &mut Parser,
2135    ) -> Result<Longhands, ParseError> {
2136        let mut position_x = Vec::with_capacity(1);
2137        let mut position_y = Vec::with_capacity(1);
2138        let mut any = false;
2139
2140        input.parse_comma_separated(|input| {
2141            let value = Position::parse_three_value_quirky(context, input, AllowQuirks::Yes)?;
2142            position_x.push(value.horizontal);
2143            position_y.push(value.vertical);
2144            any = true;
2145            Ok(())
2146        })?;
2147        if !any {
2148            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
2149        }
2150
2151        Ok(expanded! {
2152            background_position_x: background_position_x::SpecifiedValue(position_x.into()),
2153            background_position_y: background_position_y::SpecifiedValue(position_y.into()),
2154        })
2155    }
2156
2157    impl<'a> ToCss for LonghandsToSerialize<'a> {
2158        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
2159        where
2160            W: fmt::Write,
2161        {
2162            let len = self.background_position_x.0.len();
2163            if len == 0 || len != self.background_position_y.0.len() {
2164                return Ok(());
2165            }
2166            for i in 0..len {
2167                Position {
2168                    horizontal: self.background_position_x.0[i].clone(),
2169                    vertical: self.background_position_y.0[i].clone(),
2170                }
2171                .to_css(dest)?;
2172
2173                if i < len - 1 {
2174                    dest.write_str(", ")?;
2175                }
2176            }
2177            Ok(())
2178        }
2179    }
2180}
2181
2182pub mod background {
2183    pub use crate::properties::generated::shorthands::background::*;
2184
2185    use super::*;
2186    use crate::properties::longhands::background_clip;
2187    use crate::properties::longhands::background_clip::single_value::computed_value::T as Clip;
2188    use crate::properties::longhands::background_origin::single_value::computed_value::T as Origin;
2189    use crate::properties::longhands::{
2190        background_attachment, background_color, background_image, background_origin,
2191        background_size,
2192    };
2193    use crate::properties::longhands::{
2194        background_position_x, background_position_y, background_repeat,
2195    };
2196    use crate::values::specified::{AllowQuirks, Color, Position, PositionComponent};
2197
2198    pub fn parse_value(
2199        context: &ParserContext,
2200        input: &mut Parser,
2201    ) -> Result<Longhands, ParseError> {
2202        let mut background_color = None;
2203
2204        let mut background_image = Vec::with_capacity(1);
2205        let mut background_position_x = Vec::with_capacity(1);
2206        let mut background_position_y = Vec::with_capacity(1);
2207        let mut background_repeat = Vec::with_capacity(1);
2208        let mut background_size = Vec::with_capacity(1);
2209        let mut background_attachment = Vec::with_capacity(1);
2210        let mut background_origin = Vec::with_capacity(1);
2211        let mut background_clip = Vec::with_capacity(1);
2212        input.parse_comma_separated(|input| {
2213            if background_color.is_some() {
2214                return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
2215            }
2216
2217            let mut image = None;
2218            let mut position = None;
2219            let mut repeat = None;
2220            let mut size = None;
2221            let mut attachment = None;
2222            let mut origin = None;
2223            let mut clip = None;
2224            let mut parsed = 0;
2225            loop {
2226                parsed += 1;
2227                try_parse_one!(context, input, background_color, Color::parse);
2228                if position.is_none()
2229                    && let Ok(value) = input.try_parse(|input| {
2230                        Position::parse_three_value_quirky(context, input, AllowQuirks::No)
2231                    })
2232                {
2233                    position = Some(value);
2234
2235                    size = input
2236                        .try_parse(|input| {
2237                            input.expect_delim('/')?;
2238                            background_size::single_value::parse(context, input)
2239                        })
2240                        .ok();
2241
2242                    continue;
2243                }
2244                try_parse_one!(context, input, image, background_image::single_value::parse);
2245                try_parse_one!(
2246                    context,
2247                    input,
2248                    repeat,
2249                    background_repeat::single_value::parse
2250                );
2251                try_parse_one!(
2252                    context,
2253                    input,
2254                    attachment,
2255                    background_attachment::single_value::parse
2256                );
2257                try_parse_one!(
2258                    context,
2259                    input,
2260                    origin,
2261                    background_origin::single_value::parse
2262                );
2263                try_parse_one!(context, input, clip, background_clip::single_value::parse);
2264                parsed -= 1;
2265                break;
2266            }
2267            if parsed == 0 {
2268                return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
2269            }
2270            if clip.is_none()
2271                && let Some(origin) = origin
2272            {
2273                clip = Some(background_clip::single_value::SpecifiedValue::from(origin));
2274            }
2275            if let Some(position) = position {
2276                background_position_x.push(position.horizontal);
2277                background_position_y.push(position.vertical);
2278            } else {
2279                background_position_x.push(PositionComponent::zero());
2280                background_position_y.push(PositionComponent::zero());
2281            }
2282            if let Some(bg_image) = image {
2283                background_image.push(bg_image);
2284            } else {
2285                background_image
2286                    .push(background_image::single_value::get_initial_specified_value());
2287            }
2288            if let Some(bg_repeat) = repeat {
2289                background_repeat.push(bg_repeat);
2290            } else {
2291                background_repeat
2292                    .push(background_repeat::single_value::get_initial_specified_value());
2293            }
2294            if let Some(bg_size) = size {
2295                background_size.push(bg_size);
2296            } else {
2297                background_size.push(background_size::single_value::get_initial_specified_value());
2298            }
2299            if let Some(bg_attachment) = attachment {
2300                background_attachment.push(bg_attachment);
2301            } else {
2302                background_attachment
2303                    .push(background_attachment::single_value::get_initial_specified_value());
2304            }
2305            if let Some(bg_origin) = origin {
2306                background_origin.push(bg_origin);
2307            } else {
2308                background_origin
2309                    .push(background_origin::single_value::get_initial_specified_value());
2310            }
2311            if let Some(bg_clip) = clip {
2312                background_clip.push(bg_clip);
2313            } else {
2314                background_clip.push(background_clip::single_value::get_initial_specified_value());
2315            }
2316            Ok(())
2317        })?;
2318
2319        Ok(expanded! {
2320            background_color: background_color.unwrap_or(Color::transparent()),
2321            background_image: background_image::SpecifiedValue(background_image.into()),
2322            background_position_x: background_position_x::SpecifiedValue(background_position_x.into()),
2323            background_position_y: background_position_y::SpecifiedValue(background_position_y.into()),
2324            background_repeat: background_repeat::SpecifiedValue(background_repeat.into()),
2325            background_size: background_size::SpecifiedValue(background_size.into()),
2326            background_attachment: background_attachment::SpecifiedValue(background_attachment.into()),
2327            background_origin: background_origin::SpecifiedValue(background_origin.into()),
2328            background_clip: background_clip::SpecifiedValue(background_clip.into()),
2329        })
2330    }
2331
2332    impl<'a> ToCss for LonghandsToSerialize<'a> {
2333        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
2334        where
2335            W: fmt::Write,
2336        {
2337            let len = self.background_image.0.len();
2338            if len == 0 {
2339                return Ok(());
2340            }
2341            if len != self.background_image.0.len() {
2342                return Ok(());
2343            }
2344            if len != self.background_position_x.0.len() {
2345                return Ok(());
2346            }
2347            if len != self.background_position_y.0.len() {
2348                return Ok(());
2349            }
2350            if len != self.background_size.0.len() {
2351                return Ok(());
2352            }
2353            if len != self.background_repeat.0.len() {
2354                return Ok(());
2355            }
2356            if len != self.background_origin.0.len() {
2357                return Ok(());
2358            }
2359            if len != self.background_clip.0.len() {
2360                return Ok(());
2361            }
2362            if len != self.background_attachment.0.len() {
2363                return Ok(());
2364            }
2365
2366            for i in 0..len {
2367                let image = &self.background_image.0[i];
2368                let position_x = &self.background_position_x.0[i];
2369                let position_y = &self.background_position_y.0[i];
2370                let repeat = &self.background_repeat.0[i];
2371                let size = &self.background_size.0[i];
2372                let attachment = &self.background_attachment.0[i];
2373                let origin = &self.background_origin.0[i];
2374                let clip = &self.background_clip.0[i];
2375
2376                if i != 0 {
2377                    dest.write_str(", ")?;
2378                }
2379
2380                let mut writer = SequenceWriter::new(dest, " ");
2381                if *image != background_image::single_value::get_initial_specified_value() {
2382                    writer.item(image)?;
2383                }
2384
2385                if *position_x != PositionComponent::zero()
2386                    || *position_y != PositionComponent::zero()
2387                    || *size != background_size::single_value::get_initial_specified_value()
2388                {
2389                    writer.write_item(|dest| {
2390                        Position {
2391                            horizontal: position_x.clone(),
2392                            vertical: position_y.clone(),
2393                        }
2394                        .to_css(dest)?;
2395                        if *size != background_size::single_value::get_initial_specified_value() {
2396                            dest.write_str(" / ")?;
2397                            size.to_css(dest)?;
2398                        }
2399                        Ok(())
2400                    })?;
2401                }
2402                if *repeat != background_repeat::single_value::get_initial_specified_value() {
2403                    writer.item(repeat)?;
2404                }
2405                if *attachment != background_attachment::single_value::get_initial_specified_value()
2406                {
2407                    writer.item(attachment)?;
2408                }
2409
2410                if *origin != Origin::PaddingBox || *clip != Clip::BorderBox {
2411                    writer.item(origin)?;
2412                    if *clip != From::from(*origin) {
2413                        writer.item(clip)?;
2414                    }
2415                }
2416
2417                if i == len - 1
2418                    && *self.background_color != background_color::get_initial_specified_value()
2419                {
2420                    writer.item(self.background_color)?;
2421                }
2422
2423                if !writer.has_written() {
2424                    image.to_css(dest)?;
2425                }
2426            }
2427
2428            Ok(())
2429        }
2430    }
2431}
2432
2433pub mod font {
2434    pub use crate::properties::generated::shorthands::font::*;
2435
2436    use super::*;
2437    use crate::properties::longhands::{
2438        font_family, font_feature_settings, font_kerning, font_language_override,
2439        font_optical_sizing, font_size, font_size_adjust, font_style, font_variant_alternates,
2440        font_variant_caps, font_variant_east_asian, font_variant_emoji, font_variant_ligatures,
2441        font_variant_numeric, font_variant_position, font_variation_settings, font_weight,
2442        font_width,
2443    };
2444    use crate::values::specified::font::SystemFont;
2445    use crate::values::specified::font::{
2446        FontFamily, FontSize, FontStyle, FontWeight, FontWidth, FontWidthKeyword, LineHeight,
2447    };
2448
2449    pub fn parse_value(
2450        context: &ParserContext,
2451        input: &mut Parser,
2452    ) -> Result<Longhands, ParseError> {
2453        let mut nb_normals = 0;
2454        let mut style = None;
2455        let mut variant_caps = None;
2456        let mut weight = None;
2457        let mut width = None;
2458        if let Ok(sys) = input.try_parse(|i| SystemFont::parse(context, i)) {
2459            return Ok(Longhands {
2460                font_family: font_family::SpecifiedValue::system_font(sys),
2461                font_size: font_size::SpecifiedValue::system_font(sys),
2462                font_style: font_style::SpecifiedValue::system_font(sys),
2463                font_width: font_width::SpecifiedValue::system_font(sys),
2464                font_weight: font_weight::SpecifiedValue::system_font(sys),
2465                line_height: LineHeight::normal(),
2466                font_kerning: font_kerning::get_initial_specified_value(),
2467                font_language_override: font_language_override::get_initial_specified_value(),
2468                font_size_adjust: font_size_adjust::get_initial_specified_value(),
2469                font_variant_alternates: font_variant_alternates::get_initial_specified_value(),
2470                font_variant_east_asian: font_variant_east_asian::get_initial_specified_value(),
2471                font_variant_emoji: font_variant_emoji::get_initial_specified_value(),
2472                font_variant_ligatures: font_variant_ligatures::get_initial_specified_value(),
2473                font_variant_numeric: font_variant_numeric::get_initial_specified_value(),
2474                font_variant_position: font_variant_position::get_initial_specified_value(),
2475                font_feature_settings: font_feature_settings::get_initial_specified_value(),
2476                font_optical_sizing: font_optical_sizing::get_initial_specified_value(),
2477                font_variant_caps: font_variant_caps::get_initial_specified_value(),
2478                font_variation_settings: font_variation_settings::get_initial_specified_value(),
2479            });
2480        }
2481
2482        let size;
2483        loop {
2484            if input
2485                .try_parse(|input| input.expect_ident_matching("normal"))
2486                .is_ok()
2487            {
2488                nb_normals += 1;
2489                continue;
2490            }
2491            try_parse_one!(context, input, style, font_style::parse);
2492            try_parse_one!(context, input, weight, font_weight::parse);
2493            if variant_caps.is_none()
2494                && input
2495                    .try_parse(|input| input.expect_ident_matching("small-caps"))
2496                    .is_ok()
2497            {
2498                variant_caps = Some(font_variant_caps::SpecifiedValue::SmallCaps);
2499                continue;
2500            }
2501            try_parse_one!(input, width, FontWidthKeyword::parse);
2502            size = FontSize::parse(context, input)?;
2503            break;
2504        }
2505
2506        let line_height = if input.try_parse(|input| input.expect_delim('/')).is_ok() {
2507            Some(LineHeight::parse(context, input)?)
2508        } else {
2509            None
2510        };
2511
2512        #[inline]
2513        fn count<T>(opt: &Option<T>) -> u8 {
2514            if opt.is_some() { 1 } else { 0 }
2515        }
2516
2517        if (count(&style) + count(&weight) + count(&variant_caps) + count(&width) + nb_normals) > 4
2518        {
2519            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
2520        }
2521
2522        let family = FontFamily::parse(context, input)?;
2523        let width = width.map(FontWidth::Keyword);
2524        Ok(Longhands {
2525            font_style: unwrap_or_initial!(font_style, style),
2526            font_weight: unwrap_or_initial!(font_weight, weight),
2527            font_width: unwrap_or_initial!(font_width, width),
2528            font_variant_caps: unwrap_or_initial!(font_variant_caps, variant_caps),
2529            font_size: size,
2530            line_height: line_height.unwrap_or(LineHeight::normal()),
2531            font_family: family,
2532            font_optical_sizing: font_optical_sizing::get_initial_specified_value(),
2533            font_variation_settings: font_variation_settings::get_initial_specified_value(),
2534            font_kerning: font_kerning::get_initial_specified_value(),
2535            font_language_override: font_language_override::get_initial_specified_value(),
2536            font_size_adjust: font_size_adjust::get_initial_specified_value(),
2537            font_variant_alternates: font_variant_alternates::get_initial_specified_value(),
2538            font_variant_east_asian: font_variant_east_asian::get_initial_specified_value(),
2539            font_variant_emoji: font_variant_emoji::get_initial_specified_value(),
2540            font_variant_ligatures: font_variant_ligatures::get_initial_specified_value(),
2541            font_variant_numeric: font_variant_numeric::get_initial_specified_value(),
2542            font_variant_position: font_variant_position::get_initial_specified_value(),
2543            font_feature_settings: font_feature_settings::get_initial_specified_value(),
2544        })
2545    }
2546
2547    enum CheckSystemResult {
2548        AllSystem(SystemFont),
2549        SomeSystem,
2550        None,
2551    }
2552
2553    impl<'a> ToCss for LonghandsToSerialize<'a> {
2554        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
2555        where
2556            W: fmt::Write,
2557        {
2558            match self.check_system() {
2559                CheckSystemResult::AllSystem(sys) => return sys.to_css(dest),
2560                CheckSystemResult::SomeSystem => return Ok(()),
2561                CheckSystemResult::None => {},
2562            }
2563
2564            #[cfg(feature = "gecko")]
2565            if self.font_optical_sizing != &font_optical_sizing::get_initial_specified_value() {
2566                return Ok(());
2567            }
2568            #[cfg(feature = "servo")]
2569            if let Some(v) = self.font_optical_sizing {
2570                if v != &font_optical_sizing::get_initial_specified_value() {
2571                    return Ok(());
2572                }
2573            }
2574            #[cfg(feature = "gecko")]
2575            if self.font_variation_settings
2576                != &font_variation_settings::get_initial_specified_value()
2577            {
2578                return Ok(());
2579            }
2580            #[cfg(feature = "servo")]
2581            if let Some(v) = self.font_variation_settings {
2582                if v != &font_variation_settings::get_initial_specified_value() {
2583                    return Ok(());
2584                }
2585            }
2586            #[cfg(feature = "gecko")]
2587            if self.font_variant_emoji != &font_variant_emoji::get_initial_specified_value() {
2588                return Ok(());
2589            }
2590            #[cfg(feature = "servo")]
2591            if let Some(v) = self.font_variant_emoji {
2592                if v != &font_variant_emoji::get_initial_specified_value() {
2593                    return Ok(());
2594                }
2595            }
2596
2597            if self.font_kerning != &font_kerning::get_initial_specified_value() {
2598                return Ok(());
2599            }
2600            if self.font_language_override != &font_language_override::get_initial_specified_value()
2601            {
2602                return Ok(());
2603            }
2604            #[cfg(feature = "gecko")]
2605            if self.font_size_adjust != &font_size_adjust::get_initial_specified_value() {
2606                return Ok(());
2607            }
2608            #[cfg(feature = "servo")]
2609            if let Some(v) = self.font_size_adjust {
2610                if v != &font_size_adjust::get_initial_specified_value() {
2611                    return Ok(());
2612                }
2613            }
2614            if self.font_variant_alternates
2615                != &font_variant_alternates::get_initial_specified_value()
2616            {
2617                return Ok(());
2618            }
2619            if self.font_variant_east_asian
2620                != &font_variant_east_asian::get_initial_specified_value()
2621            {
2622                return Ok(());
2623            }
2624            if self.font_variant_ligatures != &font_variant_ligatures::get_initial_specified_value()
2625            {
2626                return Ok(());
2627            }
2628            if self.font_variant_numeric != &font_variant_numeric::get_initial_specified_value() {
2629                return Ok(());
2630            }
2631            if self.font_variant_position != &font_variant_position::get_initial_specified_value() {
2632                return Ok(());
2633            }
2634            if self.font_feature_settings != &font_feature_settings::get_initial_specified_value() {
2635                return Ok(());
2636            }
2637
2638            let font_width = match self.font_width {
2639                FontWidth::Keyword(kw) => *kw,
2640                FontWidth::Width(percentage) => {
2641                    let computed = match percentage.compute() {
2642                        Some(v) => v,
2643                        None => return Ok(()),
2644                    };
2645                    match FontWidthKeyword::from_percentage(computed.0) {
2646                        Some(kw) => kw,
2647                        None => return Ok(()),
2648                    }
2649                },
2650                FontWidth::System(..) => return Ok(()),
2651            };
2652
2653            if self.font_variant_caps != &font_variant_caps::get_initial_specified_value()
2654                && *self.font_variant_caps != font_variant_caps::SpecifiedValue::SmallCaps
2655            {
2656                return Ok(());
2657            }
2658
2659            if self.font_style != &font_style::get_initial_specified_value() {
2660                self.font_style.to_css(dest)?;
2661                dest.write_char(' ')?;
2662            }
2663            if self.font_variant_caps != &font_variant_caps::get_initial_specified_value() {
2664                self.font_variant_caps.to_css(dest)?;
2665                dest.write_char(' ')?;
2666            }
2667
2668            if self.font_weight != &FontWeight::normal()
2669                && self.font_weight != &FontWeight::from_gecko_keyword(400)
2670            {
2671                self.font_weight.to_css(dest)?;
2672                dest.write_char(' ')?;
2673            }
2674
2675            if font_width != FontWidthKeyword::Normal {
2676                font_width.to_css(dest)?;
2677                dest.write_char(' ')?;
2678            }
2679
2680            self.font_size.to_css(dest)?;
2681
2682            if *self.line_height != LineHeight::normal() {
2683                dest.write_str(" / ")?;
2684                self.line_height.to_css(dest)?;
2685            }
2686
2687            dest.write_char(' ')?;
2688            self.font_family.to_css(dest)?;
2689
2690            Ok(())
2691        }
2692    }
2693
2694    impl<'a> LonghandsToSerialize<'a> {
2695        fn check_system(&self) -> CheckSystemResult {
2696            let mut sys = None;
2697            let mut all = true;
2698
2699            macro_rules! check {
2700                ($v:expr) => {
2701                    match $v.get_system() {
2702                        Some(s) => {
2703                            debug_assert!(sys.is_none() || s == sys.unwrap());
2704                            sys = Some(s);
2705                        },
2706                        None => {
2707                            all = false;
2708                        },
2709                    }
2710                };
2711                ($e:expr, $($es:expr),+) => { check!($e); check!($($es),*); };
2712            }
2713
2714            check!(
2715                self.font_family,
2716                self.font_size,
2717                self.font_style,
2718                self.font_width,
2719                self.font_weight
2720            );
2721
2722            if self.line_height != &LineHeight::normal() {
2723                all = false
2724            }
2725            if all {
2726                CheckSystemResult::AllSystem(sys.unwrap())
2727            } else if sys.is_some() {
2728                CheckSystemResult::SomeSystem
2729            } else {
2730                CheckSystemResult::None
2731            }
2732        }
2733    }
2734
2735    impl SpecifiedValueInfo for Longhands {
2736        const SUPPORTED_TYPES: u8 = FontStyle::SUPPORTED_TYPES
2737            | FontWeight::SUPPORTED_TYPES
2738            | FontWidth::SUPPORTED_TYPES
2739            | font_variant_caps::SpecifiedValue::SUPPORTED_TYPES
2740            | FontSize::SUPPORTED_TYPES
2741            | FontFamily::SUPPORTED_TYPES;
2742
2743        fn collect_completion_keywords(f: KeywordsCollectFn) {
2744            FontStyle::collect_completion_keywords(f);
2745            FontWeight::collect_completion_keywords(f);
2746            FontWidth::collect_completion_keywords(f);
2747            font_variant_caps::SpecifiedValue::collect_completion_keywords(f);
2748            FontSize::collect_completion_keywords(f);
2749            FontFamily::collect_completion_keywords(f);
2750            SystemFont::collect_completion_keywords(f);
2751        }
2752    }
2753}
2754
2755pub mod font_variant {
2756    pub use crate::properties::generated::shorthands::font_variant::*;
2757
2758    use super::*;
2759    use crate::properties::longhands::{
2760        font_variant_alternates, font_variant_caps, font_variant_east_asian, font_variant_emoji,
2761        font_variant_ligatures, font_variant_numeric, font_variant_position,
2762    };
2763    use crate::properties::{LonghandId, NonCustomPropertyId};
2764    use crate::values::specified::FontVariantLigatures;
2765
2766    pub fn parse_value(
2767        context: &ParserContext,
2768        input: &mut Parser,
2769    ) -> Result<Longhands, ParseError> {
2770        let mut ligatures = None;
2771        let mut caps = None;
2772        let mut alternates = None;
2773        let mut numeric = None;
2774        let mut east_asian = None;
2775        let mut position = None;
2776        let mut emoji = None;
2777        let emoji_enabled = NonCustomPropertyId::from(LonghandId::FontVariantEmoji)
2778            .allowed_in_ignoring_rule_type(context);
2779
2780        if input
2781            .try_parse(|input| input.expect_ident_matching("normal"))
2782            .is_ok()
2783        {
2784        } else if input
2785            .try_parse(|input| input.expect_ident_matching("none"))
2786            .is_ok()
2787        {
2788            ligatures = Some(FontVariantLigatures::NONE);
2789        } else {
2790            let mut parsed = 0;
2791            loop {
2792                parsed += 1;
2793                if input
2794                    .try_parse(|input| input.expect_ident_matching("normal"))
2795                    .is_ok()
2796                    || input
2797                        .try_parse(|input| input.expect_ident_matching("none"))
2798                        .is_ok()
2799                {
2800                    return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
2801                }
2802                try_parse_one!(context, input, ligatures, font_variant_ligatures::parse);
2803                try_parse_one!(context, input, caps, font_variant_caps::parse);
2804                try_parse_one!(context, input, alternates, font_variant_alternates::parse);
2805                try_parse_one!(context, input, numeric, font_variant_numeric::parse);
2806                try_parse_one!(context, input, east_asian, font_variant_east_asian::parse);
2807                try_parse_one!(context, input, position, font_variant_position::parse);
2808                if emoji_enabled {
2809                    try_parse_one!(context, input, emoji, font_variant_emoji::parse);
2810                }
2811                parsed -= 1;
2812                break;
2813            }
2814
2815            if parsed == 0 {
2816                return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
2817            }
2818        }
2819
2820        Ok(expanded! {
2821            font_variant_ligatures: unwrap_or_initial!(font_variant_ligatures, ligatures),
2822            font_variant_caps: unwrap_or_initial!(font_variant_caps, caps),
2823            font_variant_alternates: unwrap_or_initial!(font_variant_alternates, alternates),
2824            font_variant_numeric: unwrap_or_initial!(font_variant_numeric, numeric),
2825            font_variant_east_asian: unwrap_or_initial!(font_variant_east_asian, east_asian),
2826            font_variant_position: unwrap_or_initial!(font_variant_position, position),
2827            font_variant_emoji: unwrap_or_initial!(font_variant_emoji, emoji),
2828        })
2829    }
2830
2831    impl<'a> ToCss for LonghandsToSerialize<'a> {
2832        #[allow(unused_assignments)]
2833        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
2834        where
2835            W: fmt::Write,
2836        {
2837            let has_none_ligatures = self.font_variant_ligatures == &FontVariantLigatures::NONE;
2838
2839            // `font-variant-emoji` may be disabled in Servo, in which case it's not part of the
2840            // shorthand.
2841            #[cfg(feature = "gecko")]
2842            let emoji = Some(self.font_variant_emoji);
2843            #[cfg(feature = "servo")]
2844            let emoji = self.font_variant_emoji;
2845
2846            let total_subprops = 6 + emoji.is_some() as usize;
2847            let mut nb_normals = 0;
2848            macro_rules! count_normal {
2849                ($e: expr, $p: ident) => {
2850                    if *$e == $p::get_initial_specified_value() {
2851                        nb_normals += 1;
2852                    }
2853                };
2854                ($v: ident) => {
2855                    count_normal!(self.$v, $v);
2856                };
2857            }
2858            count_normal!(font_variant_ligatures);
2859            count_normal!(font_variant_caps);
2860            count_normal!(font_variant_alternates);
2861            count_normal!(font_variant_numeric);
2862            count_normal!(font_variant_east_asian);
2863            count_normal!(font_variant_position);
2864            if let Some(emoji) = emoji {
2865                count_normal!(emoji, font_variant_emoji);
2866            }
2867
2868            if nb_normals == total_subprops {
2869                return dest.write_str("normal");
2870            }
2871            if has_none_ligatures {
2872                if nb_normals == total_subprops - 1 {
2873                    dest.write_str("none")?;
2874                }
2875                return Ok(());
2876            }
2877
2878            let mut writer = SequenceWriter::new(dest, " ");
2879            macro_rules! write {
2880                ($e: expr, $p: ident) => {
2881                    if *$e != $p::get_initial_specified_value() {
2882                        writer.item($e)?;
2883                    }
2884                };
2885                ($v: ident) => {
2886                    write!(self.$v, $v);
2887                };
2888            }
2889
2890            write!(font_variant_ligatures);
2891            write!(font_variant_caps);
2892            write!(font_variant_alternates);
2893            write!(font_variant_numeric);
2894            write!(font_variant_east_asian);
2895            write!(font_variant_position);
2896            if let Some(emoji) = emoji {
2897                write!(emoji, font_variant_emoji);
2898            }
2899            Ok(())
2900        }
2901    }
2902}
2903
2904pub mod font_synthesis {
2905    pub use crate::properties::generated::shorthands::font_synthesis::*;
2906
2907    use super::*;
2908    use crate::values::specified::{FontSynthesis, FontSynthesisStyle};
2909
2910    pub fn parse_value(
2911        _context: &ParserContext,
2912        input: &mut Parser,
2913    ) -> Result<Longhands, ParseError> {
2914        let mut weight = FontSynthesis::None;
2915        let mut style = FontSynthesisStyle::None;
2916        let mut small_caps = FontSynthesis::None;
2917        let mut position = FontSynthesis::None;
2918
2919        if input
2920            .try_parse(|input| input.expect_ident_matching("none"))
2921            .is_err()
2922        {
2923            let mut has_custom_value = false;
2924            while !input.is_exhausted() {
2925                try_match_ident_ignore_ascii_case! { input,
2926                    "weight" if weight == FontSynthesis::None => {
2927                        has_custom_value = true;
2928                        weight = FontSynthesis::Auto;
2929                        continue;
2930                    },
2931                    "style" if style == FontSynthesisStyle::None => {
2932                        has_custom_value = true;
2933                        style = FontSynthesisStyle::Auto;
2934                        continue;
2935                    },
2936                    "small-caps" if small_caps == FontSynthesis::None => {
2937                        has_custom_value = true;
2938                        small_caps = FontSynthesis::Auto;
2939                        continue;
2940                    },
2941                    "position" if position == FontSynthesis::None => {
2942                        has_custom_value = true;
2943                        position = FontSynthesis::Auto;
2944                        continue;
2945                    },
2946                    "oblique-only" if style == FontSynthesisStyle::None => {
2947                        has_custom_value = true;
2948                        style = FontSynthesisStyle::ObliqueOnly;
2949                        continue;
2950                    },
2951                }
2952            }
2953            if !has_custom_value {
2954                return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
2955            }
2956        }
2957
2958        Ok(expanded! {
2959            font_synthesis_weight: weight,
2960            font_synthesis_style: style,
2961            font_synthesis_small_caps: small_caps,
2962            font_synthesis_position: position,
2963        })
2964    }
2965
2966    impl<'a> ToCss for LonghandsToSerialize<'a> {
2967        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
2968        where
2969            W: fmt::Write,
2970        {
2971            let mut writer = SequenceWriter::new(dest, " ");
2972            if self.font_synthesis_weight == &FontSynthesis::Auto {
2973                writer.raw_item("weight")?;
2974            }
2975            if self.font_synthesis_style != &FontSynthesisStyle::None {
2976                if self.font_synthesis_style == &FontSynthesisStyle::Auto {
2977                    writer.raw_item("style")?;
2978                } else {
2979                    writer.raw_item("oblique-only")?;
2980                }
2981            }
2982            if self.font_synthesis_small_caps == &FontSynthesis::Auto {
2983                writer.raw_item("small-caps")?;
2984            }
2985            if self.font_synthesis_position == &FontSynthesis::Auto {
2986                writer.raw_item("position")?;
2987            }
2988            if !writer.has_written() {
2989                writer.raw_item("none")?;
2990            }
2991            Ok(())
2992        }
2993    }
2994
2995    // The shorthand takes the sub-property names of the longhands, and not the
2996    // 'auto' keyword like they do, so we can't automatically derive this.
2997    impl SpecifiedValueInfo for Longhands {
2998        fn collect_completion_keywords(f: KeywordsCollectFn) {
2999            f(&[
3000                "none",
3001                "oblique-only",
3002                "small-caps",
3003                "position",
3004                "style",
3005                "weight",
3006            ]);
3007        }
3008    }
3009}
3010
3011pub mod text_box {
3012    pub use crate::properties::generated::shorthands::text_box::*;
3013
3014    use super::*;
3015    use crate::values::specified::{TextBoxEdge, TextBoxTrim};
3016
3017    pub fn parse_value(
3018        context: &ParserContext,
3019        input: &mut Parser,
3020    ) -> Result<Longhands, ParseError> {
3021        let mut trim = None;
3022        let mut edge = None;
3023
3024        if input
3025            .try_parse(|input| input.expect_ident_matching("normal"))
3026            .is_ok()
3027        {
3028            return Ok(Longhands {
3029                text_box_trim: TextBoxTrim::NONE,
3030                text_box_edge: TextBoxEdge::Auto,
3031            });
3032        }
3033
3034        loop {
3035            try_parse_one!(context, input, trim, TextBoxTrim::parse);
3036            try_parse_one!(context, input, edge, TextBoxEdge::parse);
3037            break;
3038        }
3039
3040        if trim.is_none() && edge.is_none() {
3041            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
3042        }
3043
3044        // From https://drafts.csswg.org/css-inline-3/#text-box-shorthand:
3045        // > Omitting the 'text-box-trim' value sets it to 'trim-both'
3046        // > (not the initial value), while omitting the 'text-box-edge'
3047        // > value sets it to auto (the initial value).
3048        Ok(Longhands {
3049            text_box_trim: trim.unwrap_or(TextBoxTrim::TRIM_BOTH),
3050            text_box_edge: edge.unwrap_or(TextBoxEdge::Auto),
3051        })
3052    }
3053
3054    impl<'a> ToCss for LonghandsToSerialize<'a> {
3055        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
3056        where
3057            W: fmt::Write,
3058        {
3059            if *self.text_box_trim == TextBoxTrim::NONE && *self.text_box_edge == TextBoxEdge::Auto
3060            {
3061                return dest.write_str("normal");
3062            }
3063
3064            let mut writer = SequenceWriter::new(dest, " ");
3065            if *self.text_box_trim != specified::TextBoxTrim::TRIM_BOTH {
3066                writer.item(self.text_box_trim)?;
3067            }
3068            if *self.text_box_edge != specified::TextBoxEdge::Auto {
3069                writer.item(self.text_box_edge)?;
3070            }
3071            if !writer.has_written() {
3072                self.text_box_trim.to_css(dest)?;
3073            }
3074            Ok(())
3075        }
3076    }
3077}
3078
3079pub mod text_emphasis {
3080    pub use crate::properties::generated::shorthands::text_emphasis::*;
3081
3082    use super::*;
3083    use crate::properties::longhands::{text_emphasis_color, text_emphasis_style};
3084
3085    pub fn parse_value(
3086        context: &ParserContext,
3087        input: &mut Parser,
3088    ) -> Result<Longhands, ParseError> {
3089        let mut color = None;
3090        let mut style = None;
3091        let mut parsed = 0;
3092        loop {
3093            parsed += 1;
3094            try_parse_one!(context, input, color, text_emphasis_color::parse);
3095            try_parse_one!(context, input, style, text_emphasis_style::parse);
3096            parsed -= 1;
3097            break;
3098        }
3099        if parsed == 0 {
3100            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
3101        }
3102        Ok(expanded! {
3103            text_emphasis_color: unwrap_or_initial!(text_emphasis_color, color),
3104            text_emphasis_style: unwrap_or_initial!(text_emphasis_style, style),
3105        })
3106    }
3107}
3108
3109pub mod text_decoration {
3110    pub use crate::properties::generated::shorthands::text_decoration::*;
3111
3112    use super::*;
3113    use crate::properties::longhands::text_decoration_thickness;
3114    use crate::properties::longhands::{
3115        text_decoration_color, text_decoration_line, text_decoration_style,
3116    };
3117
3118    pub fn parse_value(
3119        context: &ParserContext,
3120        input: &mut Parser,
3121    ) -> Result<Longhands, ParseError> {
3122        let mut line = None;
3123        let mut style = None;
3124        let mut color = None;
3125        let mut thickness = None;
3126
3127        let mut parsed = 0;
3128        loop {
3129            parsed += 1;
3130            try_parse_one!(context, input, line, text_decoration_line::parse);
3131            try_parse_one!(context, input, style, text_decoration_style::parse);
3132            try_parse_one!(context, input, color, text_decoration_color::parse);
3133            try_parse_one!(context, input, thickness, text_decoration_thickness::parse);
3134            parsed -= 1;
3135            break;
3136        }
3137
3138        if parsed == 0 {
3139            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
3140        }
3141
3142        Ok(expanded! {
3143            text_decoration_line: unwrap_or_initial!(text_decoration_line, line),
3144            text_decoration_style: unwrap_or_initial!(text_decoration_style, style),
3145            text_decoration_color: unwrap_or_initial!(text_decoration_color, color),
3146            text_decoration_thickness: unwrap_or_initial!(text_decoration_thickness, thickness),
3147        })
3148    }
3149
3150    impl<'a> ToCss for LonghandsToSerialize<'a> {
3151        #[allow(unused)]
3152        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
3153        where
3154            W: fmt::Write,
3155        {
3156            use crate::values::specified::Color;
3157            use crate::values::specified::TextDecorationLine;
3158
3159            let is_solid_style =
3160                *self.text_decoration_style == text_decoration_style::SpecifiedValue::Solid;
3161            let is_current_color = *self.text_decoration_color == Color::CurrentColor;
3162            let is_auto_thickness = self.text_decoration_thickness.is_auto();
3163            let is_none = *self.text_decoration_line == TextDecorationLine::none();
3164
3165            let mut writer = SequenceWriter::new(dest, " ");
3166            if (is_solid_style && is_current_color && is_auto_thickness) || !is_none {
3167                writer.item(self.text_decoration_line)?;
3168            }
3169            if !is_auto_thickness {
3170                writer.item(self.text_decoration_thickness)?;
3171            }
3172            if !is_solid_style {
3173                writer.item(self.text_decoration_style)?;
3174            }
3175            if !is_current_color {
3176                writer.item(self.text_decoration_color)?;
3177            }
3178            Ok(())
3179        }
3180    }
3181}
3182
3183pub mod animation {
3184    pub use crate::properties::generated::shorthands::animation::*;
3185
3186    use super::*;
3187    use crate::properties::longhands::{
3188        animation_delay, animation_direction, animation_duration, animation_fill_mode,
3189        animation_iteration_count, animation_name, animation_play_state, animation_range_end,
3190        animation_range_start, animation_timeline, animation_timing_function,
3191    };
3192
3193    pub fn parse_value(
3194        context: &ParserContext,
3195        input: &mut Parser,
3196    ) -> Result<Longhands, ParseError> {
3197        struct SingleAnimation {
3198            animation_name: animation_name::SingleSpecifiedValue,
3199            animation_duration: animation_duration::SingleSpecifiedValue,
3200            animation_timing_function: animation_timing_function::SingleSpecifiedValue,
3201            animation_delay: animation_delay::SingleSpecifiedValue,
3202            animation_iteration_count: animation_iteration_count::SingleSpecifiedValue,
3203            animation_direction: animation_direction::SingleSpecifiedValue,
3204            animation_fill_mode: animation_fill_mode::SingleSpecifiedValue,
3205            animation_play_state: animation_play_state::SingleSpecifiedValue,
3206        }
3207
3208        fn parse_one_animation(
3209            context: &ParserContext,
3210            input: &mut Parser,
3211        ) -> Result<SingleAnimation, ParseError> {
3212            let mut name = None;
3213            let mut duration = None;
3214            let mut timing_function = None;
3215            let mut delay = None;
3216            let mut iteration_count = None;
3217            let mut direction = None;
3218            let mut fill_mode = None;
3219            let mut play_state = None;
3220
3221            let mut parsed = 0;
3222            loop {
3223                parsed += 1;
3224                try_parse_one!(
3225                    context,
3226                    input,
3227                    duration,
3228                    animation_duration::single_value::parse
3229                );
3230                try_parse_one!(
3231                    context,
3232                    input,
3233                    timing_function,
3234                    animation_timing_function::single_value::parse
3235                );
3236                try_parse_one!(context, input, delay, animation_delay::single_value::parse);
3237                try_parse_one!(
3238                    context,
3239                    input,
3240                    iteration_count,
3241                    animation_iteration_count::single_value::parse
3242                );
3243                try_parse_one!(
3244                    context,
3245                    input,
3246                    direction,
3247                    animation_direction::single_value::parse
3248                );
3249                try_parse_one!(
3250                    context,
3251                    input,
3252                    fill_mode,
3253                    animation_fill_mode::single_value::parse
3254                );
3255                try_parse_one!(
3256                    context,
3257                    input,
3258                    play_state,
3259                    animation_play_state::single_value::parse
3260                );
3261                try_parse_one!(context, input, name, animation_name::single_value::parse);
3262                parsed -= 1;
3263                break;
3264            }
3265
3266            if parsed == 0 {
3267                return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
3268            }
3269            Ok(SingleAnimation {
3270                animation_name: name
3271                    .unwrap_or_else(animation_name::single_value::get_initial_specified_value),
3272                animation_duration: duration
3273                    .unwrap_or_else(animation_duration::single_value::get_initial_specified_value),
3274                animation_timing_function: timing_function.unwrap_or_else(
3275                    animation_timing_function::single_value::get_initial_specified_value,
3276                ),
3277                animation_delay: delay
3278                    .unwrap_or_else(animation_delay::single_value::get_initial_specified_value),
3279                animation_iteration_count: iteration_count.unwrap_or_else(
3280                    animation_iteration_count::single_value::get_initial_specified_value,
3281                ),
3282                animation_direction: direction
3283                    .unwrap_or_else(animation_direction::single_value::get_initial_specified_value),
3284                animation_fill_mode: fill_mode
3285                    .unwrap_or_else(animation_fill_mode::single_value::get_initial_specified_value),
3286                animation_play_state: play_state.unwrap_or_else(
3287                    animation_play_state::single_value::get_initial_specified_value,
3288                ),
3289            })
3290        }
3291
3292        let mut names = vec![];
3293        let mut durations = vec![];
3294        let mut timing_functions = vec![];
3295        let mut delays = vec![];
3296        let mut iteration_counts = vec![];
3297        let mut directions = vec![];
3298        let mut fill_modes = vec![];
3299        let mut play_states = vec![];
3300
3301        let results = input.parse_comma_separated(|i| parse_one_animation(context, i))?;
3302        for result in results.into_iter() {
3303            names.push(result.animation_name);
3304            durations.push(result.animation_duration);
3305            timing_functions.push(result.animation_timing_function);
3306            delays.push(result.animation_delay);
3307            iteration_counts.push(result.animation_iteration_count);
3308            directions.push(result.animation_direction);
3309            fill_modes.push(result.animation_fill_mode);
3310            play_states.push(result.animation_play_state);
3311        }
3312
3313        Ok(expanded! {
3314            animation_name: animation_name::SpecifiedValue(names.into()),
3315            animation_duration: animation_duration::SpecifiedValue(durations.into()),
3316            animation_timing_function: animation_timing_function::SpecifiedValue(timing_functions.into()),
3317            animation_delay: animation_delay::SpecifiedValue(delays.into()),
3318            animation_iteration_count: animation_iteration_count::SpecifiedValue(iteration_counts.into()),
3319            animation_direction: animation_direction::SpecifiedValue(directions.into()),
3320            animation_fill_mode: animation_fill_mode::SpecifiedValue(fill_modes.into()),
3321            animation_play_state: animation_play_state::SpecifiedValue(play_states.into()),
3322            animation_timeline: animation_timeline::SpecifiedValue(
3323                vec![animation_timeline::single_value::get_initial_specified_value()].into()
3324            ),
3325            // The animation-range properties are reset-only sub-properties of the animation
3326            // shorthand.
3327            // https://drafts.csswg.org/scroll-animations-1/#named-range-animation-declaration
3328            animation_range_start: animation_range_start::SpecifiedValue(
3329                vec![animation_range_start::single_value::get_initial_specified_value()].into()
3330            ),
3331            animation_range_end: animation_range_end::SpecifiedValue(
3332                vec![animation_range_end::single_value::get_initial_specified_value()].into()
3333            ),
3334        })
3335    }
3336
3337    impl<'a> ToCss for LonghandsToSerialize<'a> {
3338        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
3339        where
3340            W: fmt::Write,
3341        {
3342            use crate::Zero;
3343            use crate::values::specified::easing::TimingFunction;
3344            use crate::values::specified::{
3345                AnimationDirection, AnimationFillMode, AnimationPlayState,
3346            };
3347            use style_traits::values::SequenceWriter;
3348
3349            let len = self.animation_name.0.len();
3350            if len == 0 {
3351                return Ok(());
3352            }
3353
3354            if len != self.animation_duration.0.len() {
3355                return Ok(());
3356            }
3357            if len != self.animation_timing_function.0.len() {
3358                return Ok(());
3359            }
3360            if len != self.animation_delay.0.len() {
3361                return Ok(());
3362            }
3363            if len != self.animation_iteration_count.0.len() {
3364                return Ok(());
3365            }
3366            if len != self.animation_direction.0.len() {
3367                return Ok(());
3368            }
3369            if len != self.animation_fill_mode.0.len() {
3370                return Ok(());
3371            }
3372            if len != self.animation_play_state.0.len() {
3373                return Ok(());
3374            }
3375
3376            // We don't serialize animation-timeline, animation-range-start and animation-range-end
3377            // if any of them are not the initial value.
3378            if self
3379                .animation_timeline
3380                .is_some_and(|v| v.0.len() != 1 || !v.0[0].is_auto())
3381            {
3382                return Ok(());
3383            }
3384            if self
3385                .animation_range_start
3386                .is_some_and(|v| v.0.len() != 1 || !v.0[0].0.is_normal())
3387            {
3388                return Ok(());
3389            }
3390            if self
3391                .animation_range_end
3392                .is_some_and(|v| v.0.len() != 1 || !v.0[0].0.is_normal())
3393            {
3394                return Ok(());
3395            }
3396
3397            for i in 0..len {
3398                if i != 0 {
3399                    dest.write_str(", ")?;
3400                }
3401
3402                let has_duration = !self.animation_duration.0[i].is_auto()
3403                    && !self.animation_duration.0[i].is_zero();
3404                let has_timing_function = !self.animation_timing_function.0[i].is_ease();
3405                let has_delay = !self.animation_delay.0[i].is_zero();
3406                let has_iteration_count = !self.animation_iteration_count.0[i].is_one();
3407                let has_direction =
3408                    !matches!(self.animation_direction.0[i], AnimationDirection::Normal);
3409                let has_fill_mode =
3410                    !matches!(self.animation_fill_mode.0[i], AnimationFillMode::None);
3411                let has_play_state =
3412                    !matches!(self.animation_play_state.0[i], AnimationPlayState::Running);
3413                let animation_name = &self.animation_name.0[i];
3414                let has_name = !animation_name.is_none();
3415
3416                let mut writer = SequenceWriter::new(dest, " ");
3417
3418                if has_duration || has_delay {
3419                    writer.item(&self.animation_duration.0[i])?;
3420                }
3421
3422                if has_timing_function || TimingFunction::match_keywords(animation_name) {
3423                    writer.item(&self.animation_timing_function.0[i])?;
3424                }
3425
3426                if has_delay {
3427                    writer.item(&self.animation_delay.0[i])?;
3428                }
3429                if has_iteration_count {
3430                    writer.item(&self.animation_iteration_count.0[i])?;
3431                }
3432
3433                if has_direction || AnimationDirection::match_keywords(animation_name) {
3434                    writer.item(&self.animation_direction.0[i])?;
3435                }
3436
3437                if has_fill_mode || AnimationFillMode::match_keywords(animation_name) {
3438                    writer.item(&self.animation_fill_mode.0[i])?;
3439                }
3440
3441                if has_play_state || AnimationPlayState::match_keywords(animation_name) {
3442                    writer.item(&self.animation_play_state.0[i])?;
3443                }
3444
3445                if has_name || !writer.has_written() {
3446                    writer.item(animation_name)?;
3447                }
3448            }
3449            Ok(())
3450        }
3451    }
3452}
3453
3454pub mod mask {
3455    pub use crate::properties::generated::shorthands::mask::*;
3456
3457    use super::*;
3458    use crate::parser::Parse;
3459    use crate::properties::longhands::{
3460        mask_clip, mask_composite, mask_mode, mask_origin, mask_position_x, mask_position_y,
3461        mask_repeat,
3462    };
3463    use crate::properties::longhands::{mask_image, mask_size};
3464    use crate::values::specified::{Position, PositionComponent};
3465
3466    pub fn parse_value(
3467        context: &ParserContext,
3468        input: &mut Parser,
3469    ) -> Result<Longhands, ParseError> {
3470        let mut mask_image = Vec::with_capacity(1);
3471        let mut mask_mode = Vec::with_capacity(1);
3472        let mut mask_position_x = Vec::with_capacity(1);
3473        let mut mask_position_y = Vec::with_capacity(1);
3474        let mut mask_size = Vec::with_capacity(1);
3475        let mut mask_repeat = Vec::with_capacity(1);
3476        let mut mask_origin = Vec::with_capacity(1);
3477        let mut mask_clip = Vec::with_capacity(1);
3478        let mut mask_composite = Vec::with_capacity(1);
3479
3480        input.parse_comma_separated(|input| {
3481            let mut image = None;
3482            let mut mode = None;
3483            let mut position = None;
3484            let mut size = None;
3485            let mut repeat = None;
3486            let mut origin = None;
3487            let mut clip = None;
3488            let mut composite = None;
3489            let mut parsed = 0;
3490            loop {
3491                parsed += 1;
3492
3493                try_parse_one!(context, input, image, mask_image::single_value::parse);
3494                if position.is_none()
3495                    && let Ok(value) = input.try_parse(|input| Position::parse(context, input))
3496                {
3497                    position = Some(value);
3498                    size = input
3499                        .try_parse(|input| {
3500                            input.expect_delim('/')?;
3501                            mask_size::single_value::parse(context, input)
3502                        })
3503                        .ok();
3504
3505                    continue;
3506                }
3507                try_parse_one!(context, input, repeat, mask_repeat::single_value::parse);
3508                try_parse_one!(context, input, origin, mask_origin::single_value::parse);
3509                try_parse_one!(context, input, clip, mask_clip::single_value::parse);
3510                try_parse_one!(
3511                    context,
3512                    input,
3513                    composite,
3514                    mask_composite::single_value::parse
3515                );
3516                try_parse_one!(context, input, mode, mask_mode::single_value::parse);
3517
3518                parsed -= 1;
3519                break;
3520            }
3521            if clip.is_none()
3522                && let Some(origin) = origin
3523            {
3524                clip = Some(mask_clip::single_value::SpecifiedValue::from(origin));
3525            }
3526            if parsed == 0 {
3527                return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
3528            }
3529            if let Some(position) = position {
3530                mask_position_x.push(position.horizontal);
3531                mask_position_y.push(position.vertical);
3532            } else {
3533                mask_position_x.push(PositionComponent::zero());
3534                mask_position_y.push(PositionComponent::zero());
3535            }
3536            if let Some(m_image) = image {
3537                mask_image.push(m_image);
3538            } else {
3539                mask_image.push(mask_image::single_value::get_initial_specified_value());
3540            }
3541            if let Some(m_mode) = mode {
3542                mask_mode.push(m_mode);
3543            } else {
3544                mask_mode.push(mask_mode::single_value::get_initial_specified_value());
3545            }
3546            if let Some(m_size) = size {
3547                mask_size.push(m_size);
3548            } else {
3549                mask_size.push(mask_size::single_value::get_initial_specified_value());
3550            }
3551            if let Some(m_repeat) = repeat {
3552                mask_repeat.push(m_repeat);
3553            } else {
3554                mask_repeat.push(mask_repeat::single_value::get_initial_specified_value());
3555            }
3556            if let Some(m_origin) = origin {
3557                mask_origin.push(m_origin);
3558            } else {
3559                mask_origin.push(mask_origin::single_value::get_initial_specified_value());
3560            }
3561            if let Some(m_clip) = clip {
3562                mask_clip.push(m_clip);
3563            } else {
3564                mask_clip.push(mask_clip::single_value::get_initial_specified_value());
3565            }
3566            if let Some(m_composite) = composite {
3567                mask_composite.push(m_composite);
3568            } else {
3569                mask_composite.push(mask_composite::single_value::get_initial_specified_value());
3570            }
3571            Ok(())
3572        })?;
3573
3574        Ok(expanded! {
3575           mask_image: mask_image::SpecifiedValue(mask_image.into()),
3576           mask_mode: mask_mode::SpecifiedValue(mask_mode.into()),
3577           mask_position_x: mask_position_x::SpecifiedValue(mask_position_x.into()),
3578           mask_position_y: mask_position_y::SpecifiedValue(mask_position_y.into()),
3579           mask_size: mask_size::SpecifiedValue(mask_size.into()),
3580           mask_repeat: mask_repeat::SpecifiedValue(mask_repeat.into()),
3581           mask_origin: mask_origin::SpecifiedValue(mask_origin.into()),
3582           mask_clip: mask_clip::SpecifiedValue(mask_clip.into()),
3583           mask_composite: mask_composite::SpecifiedValue(mask_composite.into()),
3584        })
3585    }
3586
3587    impl<'a> ToCss for LonghandsToSerialize<'a> {
3588        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
3589        where
3590            W: fmt::Write,
3591        {
3592            use crate::properties::longhands::mask_clip::single_value::computed_value::T as Clip;
3593            use crate::properties::longhands::mask_origin::single_value::computed_value::T as Origin;
3594            use style_traits::values::SequenceWriter;
3595
3596            let len = self.mask_image.0.len();
3597            if len == 0 {
3598                return Ok(());
3599            }
3600            if self.mask_mode.0.len() != len {
3601                return Ok(());
3602            }
3603            if self.mask_position_x.0.len() != len {
3604                return Ok(());
3605            }
3606            if self.mask_position_y.0.len() != len {
3607                return Ok(());
3608            }
3609            if self.mask_size.0.len() != len {
3610                return Ok(());
3611            }
3612            if self.mask_repeat.0.len() != len {
3613                return Ok(());
3614            }
3615            if self.mask_origin.0.len() != len {
3616                return Ok(());
3617            }
3618            if self.mask_clip.0.len() != len {
3619                return Ok(());
3620            }
3621            if self.mask_composite.0.len() != len {
3622                return Ok(());
3623            }
3624
3625            for i in 0..len {
3626                if i > 0 {
3627                    dest.write_str(", ")?;
3628                }
3629
3630                let image = &self.mask_image.0[i];
3631                let mode = &self.mask_mode.0[i];
3632                let position_x = &self.mask_position_x.0[i];
3633                let position_y = &self.mask_position_y.0[i];
3634                let size = &self.mask_size.0[i];
3635                let repeat = &self.mask_repeat.0[i];
3636                let origin = &self.mask_origin.0[i];
3637                let clip = &self.mask_clip.0[i];
3638                let composite = &self.mask_composite.0[i];
3639
3640                let mut has_other = false;
3641                let has_image = *image != mask_image::single_value::get_initial_specified_value();
3642                has_other |= has_image;
3643                let has_mode = *mode != mask_mode::single_value::get_initial_specified_value();
3644                has_other |= has_mode;
3645                let has_size = *size != mask_size::single_value::get_initial_specified_value();
3646                has_other |= has_size;
3647                let has_repeat =
3648                    *repeat != mask_repeat::single_value::get_initial_specified_value();
3649                has_other |= has_repeat;
3650                let has_composite =
3651                    *composite != mask_composite::single_value::get_initial_specified_value();
3652                has_other |= has_composite;
3653                let has_position = *position_x != PositionComponent::zero()
3654                    || *position_y != PositionComponent::zero();
3655                let has_origin = *origin != Origin::BorderBox;
3656                let has_clip = *clip != Clip::BorderBox;
3657
3658                if !has_other && !has_position && !has_origin && !has_clip {
3659                    return image.to_css(dest);
3660                }
3661
3662                let mut writer = SequenceWriter::new(dest, " ");
3663                if has_image {
3664                    writer.item(image)?;
3665                }
3666                if has_position || has_size {
3667                    writer.write_item(|dest| {
3668                        Position {
3669                            horizontal: position_x.clone(),
3670                            vertical: position_y.clone(),
3671                        }
3672                        .to_css(dest)?;
3673                        if has_size {
3674                            dest.write_str(" / ")?;
3675                            size.to_css(dest)?;
3676                        }
3677                        Ok(())
3678                    })?;
3679                }
3680
3681                if has_repeat {
3682                    writer.item(repeat)?;
3683                }
3684
3685                #[cfg(feature = "gecko")]
3686                {
3687                    if has_origin || (has_clip && *clip != Clip::NoClip) {
3688                        writer.item(origin)?;
3689                    }
3690                }
3691
3692                #[cfg(feature = "servo")]
3693                {
3694                    if has_origin || has_clip {
3695                        writer.item(origin)?;
3696                    }
3697                }
3698
3699                if has_clip && *clip != From::from(*origin) {
3700                    writer.item(clip)?;
3701                }
3702
3703                if has_composite {
3704                    writer.item(composite)?;
3705                }
3706
3707                if has_mode {
3708                    writer.item(mode)?;
3709                }
3710            }
3711
3712            Ok(())
3713        }
3714    }
3715}
3716
3717pub mod mask_position {
3718    pub use crate::properties::generated::shorthands::mask_position::*;
3719
3720    use super::*;
3721    use crate::properties::longhands::{mask_position_x, mask_position_y};
3722    use crate::values::specified::Position;
3723
3724    pub fn parse_value(
3725        context: &ParserContext,
3726        input: &mut Parser,
3727    ) -> Result<Longhands, ParseError> {
3728        // Vec grows from 0 to 4 by default on first push().  So allocate with capacity 1, so in
3729        // the common case of only one item we don't way overallocate, then shrink.  Note that we
3730        // always push at least one item if parsing succeeds.
3731        let mut position_x = Vec::with_capacity(1);
3732        let mut position_y = Vec::with_capacity(1);
3733        input.parse_comma_separated(|input| {
3734            let value = Position::parse(context, input)?;
3735            position_x.push(value.horizontal);
3736            position_y.push(value.vertical);
3737            Ok(())
3738        })?;
3739
3740        if position_x.is_empty() {
3741            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
3742        }
3743
3744        Ok(expanded! {
3745            mask_position_x: mask_position_x::SpecifiedValue(position_x.into()),
3746            mask_position_y: mask_position_y::SpecifiedValue(position_y.into()),
3747        })
3748    }
3749
3750    impl<'a> ToCss for LonghandsToSerialize<'a> {
3751        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
3752        where
3753            W: fmt::Write,
3754        {
3755            let len = self.mask_position_x.0.len();
3756            if len == 0 || self.mask_position_y.0.len() != len {
3757                return Ok(());
3758            }
3759
3760            for i in 0..len {
3761                Position {
3762                    horizontal: self.mask_position_x.0[i].clone(),
3763                    vertical: self.mask_position_y.0[i].clone(),
3764                }
3765                .to_css(dest)?;
3766
3767                if i < len - 1 {
3768                    dest.write_str(", ")?;
3769                }
3770            }
3771
3772            Ok(())
3773        }
3774    }
3775}
3776
3777pub mod grid_template {
3778    pub use crate::properties::generated::shorthands::grid_template::*;
3779
3780    use super::*;
3781    use crate::parser::Parse;
3782    use crate::values::generics::grid::{TrackList, TrackSize};
3783    use crate::values::generics::grid::{TrackListValue, concat_serialize_idents};
3784    use crate::values::specified::grid::parse_line_names;
3785    use crate::values::specified::position::{
3786        GridTemplateAreas, TemplateAreasArc, TemplateAreasParser,
3787    };
3788    use crate::values::specified::{GenericGridTemplateComponent, GridTemplateComponent};
3789    use servo_arc::Arc;
3790
3791    pub fn parse_grid_template(
3792        context: &ParserContext,
3793        input: &mut Parser,
3794    ) -> Result<
3795        (
3796            GridTemplateComponent,
3797            GridTemplateComponent,
3798            GridTemplateAreas,
3799        ),
3800        ParseError,
3801    > {
3802        if let Ok(x) = input.try_parse(|i| {
3803            if i.try_parse(|i| i.expect_ident_matching("none")).is_ok() {
3804                if !i.is_exhausted() {
3805                    return Err(());
3806                }
3807                return Ok((
3808                    GenericGridTemplateComponent::None,
3809                    GenericGridTemplateComponent::None,
3810                    GridTemplateAreas::None,
3811                ));
3812            }
3813            Err(())
3814        }) {
3815            return Ok(x);
3816        }
3817
3818        let first_line_names = input.try_parse(parse_line_names).unwrap_or_default();
3819        let mut areas_parser = TemplateAreasParser::default();
3820        if areas_parser.try_parse_string(input).is_ok() {
3821            let mut values = vec![];
3822            let mut line_names = vec![];
3823            line_names.push(first_line_names);
3824            loop {
3825                let size = input
3826                    .try_parse(|i| TrackSize::parse(context, i))
3827                    .unwrap_or_default();
3828                values.push(TrackListValue::TrackSize(size));
3829                let mut names = input.try_parse(parse_line_names).unwrap_or_default();
3830                let more_names = input.try_parse(parse_line_names);
3831
3832                match areas_parser.try_parse_string(input) {
3833                    Ok(()) => {
3834                        if let Ok(v) = more_names {
3835                            let mut names_vec = names.into_vec();
3836                            names_vec.extend(v);
3837                            names = names_vec.into();
3838                        }
3839                        line_names.push(names);
3840                    },
3841                    Err(e) => {
3842                        if more_names.is_ok() {
3843                            return Err(e);
3844                        }
3845                        line_names.push(names);
3846                        break;
3847                    },
3848                };
3849            }
3850
3851            if line_names.len() == values.len() {
3852                line_names.push(Default::default());
3853            }
3854
3855            let template_areas = areas_parser
3856                .finish()
3857                .map_err(|()| ParseError::custom(StyleParseErrorKind::UnspecifiedError))?;
3858            let template_rows = TrackList {
3859                values: values.into(),
3860                line_names: line_names.into(),
3861                auto_repeat_index: usize::MAX,
3862            };
3863
3864            let template_cols = if input.try_parse(|i| i.expect_delim('/')).is_ok() {
3865                let value = GridTemplateComponent::parse_without_none(context, input)?;
3866                if let GenericGridTemplateComponent::TrackList(ref list) = value
3867                    && !list.is_explicit()
3868                {
3869                    return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
3870                }
3871
3872                value
3873            } else {
3874                GridTemplateComponent::default()
3875            };
3876
3877            Ok((
3878                GenericGridTemplateComponent::TrackList(Box::new(template_rows)),
3879                template_cols,
3880                GridTemplateAreas::Areas(TemplateAreasArc(Arc::new(template_areas))),
3881            ))
3882        } else {
3883            let mut template_rows = GridTemplateComponent::parse(context, input)?;
3884            if let GenericGridTemplateComponent::TrackList(ref mut list) = template_rows {
3885                if list.line_names[0].is_empty() {
3886                    list.line_names[0] = first_line_names;
3887                } else {
3888                    return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
3889                }
3890            }
3891
3892            input.expect_delim('/')?;
3893            Ok((
3894                template_rows,
3895                GridTemplateComponent::parse(context, input)?,
3896                GridTemplateAreas::None,
3897            ))
3898        }
3899    }
3900
3901    #[inline]
3902    pub fn parse_value(
3903        context: &ParserContext,
3904        input: &mut Parser,
3905    ) -> Result<Longhands, ParseError> {
3906        let (rows, columns, areas) = parse_grid_template(context, input)?;
3907        Ok(expanded! {
3908            grid_template_rows: rows,
3909            grid_template_columns: columns,
3910            grid_template_areas: areas,
3911        })
3912    }
3913
3914    pub fn serialize_grid_template<W>(
3915        template_rows: &GridTemplateComponent,
3916        template_columns: &GridTemplateComponent,
3917        template_areas: &GridTemplateAreas,
3918        dest: &mut CssWriter<W>,
3919    ) -> fmt::Result
3920    where
3921        W: fmt::Write,
3922    {
3923        match *template_areas {
3924            GridTemplateAreas::None => {
3925                if template_rows.is_initial() && template_columns.is_initial() {
3926                    return GridTemplateComponent::default().to_css(dest);
3927                }
3928                template_rows.to_css(dest)?;
3929                dest.write_str(" / ")?;
3930                template_columns.to_css(dest)
3931            },
3932            GridTemplateAreas::Areas(ref areas) => {
3933                if areas.0.strings.len() != template_rows.track_list_len() {
3934                    return Ok(());
3935                }
3936
3937                let track_list = match *template_rows {
3938                    GenericGridTemplateComponent::TrackList(ref list) => {
3939                        if !list.is_explicit() {
3940                            return Ok(());
3941                        }
3942                        list
3943                    },
3944                    _ => return Ok(()),
3945                };
3946
3947                match *template_columns {
3948                    GenericGridTemplateComponent::TrackList(ref list) => {
3949                        if !list.is_explicit() {
3950                            return Ok(());
3951                        }
3952                    },
3953                    GenericGridTemplateComponent::Subgrid(_) => {
3954                        return Ok(());
3955                    },
3956                    _ => {},
3957                }
3958
3959                let mut names_iter = track_list.line_names.iter();
3960                for (((i, string), names), value) in areas
3961                    .0
3962                    .strings
3963                    .iter()
3964                    .enumerate()
3965                    .zip(&mut names_iter)
3966                    .zip(track_list.values.iter())
3967                {
3968                    if i > 0 {
3969                        dest.write_char(' ')?;
3970                    }
3971
3972                    if !names.is_empty() {
3973                        concat_serialize_idents("[", "] ", names, " ", dest)?;
3974                    }
3975
3976                    string.to_css(dest)?;
3977
3978                    if !value.is_initial() {
3979                        dest.write_char(' ')?;
3980                        value.to_css(dest)?;
3981                    }
3982                }
3983
3984                if let Some(names) = names_iter.next() {
3985                    concat_serialize_idents(" [", "]", names, " ", dest)?;
3986                }
3987
3988                if let GenericGridTemplateComponent::TrackList(ref list) = *template_columns {
3989                    dest.write_str(" / ")?;
3990                    list.to_css(dest)?;
3991                }
3992
3993                Ok(())
3994            },
3995        }
3996    }
3997
3998    impl<'a> ToCss for LonghandsToSerialize<'a> {
3999        #[inline]
4000        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
4001        where
4002            W: fmt::Write,
4003        {
4004            serialize_grid_template(
4005                self.grid_template_rows,
4006                self.grid_template_columns,
4007                self.grid_template_areas,
4008                dest,
4009            )
4010        }
4011    }
4012}
4013
4014pub mod grid {
4015    pub use crate::properties::generated::shorthands::grid::*;
4016
4017    use super::*;
4018    use crate::parser::Parse;
4019    use crate::properties::longhands::{grid_auto_columns, grid_auto_flow, grid_auto_rows};
4020    use crate::values::generics::grid::GridTemplateComponent;
4021    use crate::values::specified::position::{GridAutoFlow, GridTemplateAreas};
4022    use crate::values::specified::{GenericGridTemplateComponent, ImplicitGridTracks};
4023
4024    pub fn parse_value(
4025        context: &ParserContext,
4026        input: &mut Parser,
4027    ) -> Result<Longhands, ParseError> {
4028        let mut temp_rows = GridTemplateComponent::default();
4029        let mut temp_cols = GridTemplateComponent::default();
4030        let mut temp_areas = GridTemplateAreas::None;
4031        let mut auto_rows = ImplicitGridTracks::default();
4032        let mut auto_cols = ImplicitGridTracks::default();
4033        let mut flow = grid_auto_flow::get_initial_value();
4034
4035        fn parse_auto_flow(input: &mut Parser, is_row: bool) -> Result<GridAutoFlow, ParseError> {
4036            let mut track = None;
4037            let mut dense = GridAutoFlow::empty();
4038
4039            for _ in 0..2 {
4040                if input
4041                    .try_parse(|i| i.expect_ident_matching("auto-flow"))
4042                    .is_ok()
4043                {
4044                    track = if is_row {
4045                        Some(GridAutoFlow::ROW)
4046                    } else {
4047                        Some(GridAutoFlow::COLUMN)
4048                    };
4049                } else if input
4050                    .try_parse(|i| i.expect_ident_matching("dense"))
4051                    .is_ok()
4052                {
4053                    dense = GridAutoFlow::DENSE
4054                } else {
4055                    break;
4056                }
4057            }
4058
4059            if track.is_some() {
4060                Ok(track.unwrap() | dense)
4061            } else {
4062                Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError))
4063            }
4064        }
4065
4066        if let Ok((rows, cols, areas)) =
4067            input.try_parse(|i| super::grid_template::parse_grid_template(context, i))
4068        {
4069            temp_rows = rows;
4070            temp_cols = cols;
4071            temp_areas = areas;
4072        } else if let Ok(rows) = input.try_parse(|i| GridTemplateComponent::parse(context, i)) {
4073            temp_rows = rows;
4074            input.expect_delim('/')?;
4075            flow = parse_auto_flow(input, false)?;
4076            auto_cols = input
4077                .try_parse(|i| grid_auto_columns::parse(context, i))
4078                .unwrap_or_default();
4079        } else {
4080            flow = parse_auto_flow(input, true)?;
4081            auto_rows = input
4082                .try_parse(|i| grid_auto_rows::parse(context, i))
4083                .unwrap_or_default();
4084            input.expect_delim('/')?;
4085            temp_cols = GridTemplateComponent::parse(context, input)?;
4086        }
4087
4088        Ok(expanded! {
4089            grid_template_rows: temp_rows,
4090            grid_template_columns: temp_cols,
4091            grid_template_areas: temp_areas,
4092            grid_auto_rows: auto_rows,
4093            grid_auto_columns: auto_cols,
4094            grid_auto_flow: flow,
4095        })
4096    }
4097
4098    impl<'a> LonghandsToSerialize<'a> {
4099        fn is_grid_template(&self) -> bool {
4100            self.grid_auto_rows.is_initial()
4101                && self.grid_auto_columns.is_initial()
4102                && *self.grid_auto_flow == grid_auto_flow::get_initial_value()
4103        }
4104    }
4105
4106    impl<'a> ToCss for LonghandsToSerialize<'a> {
4107        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
4108        where
4109            W: fmt::Write,
4110        {
4111            if self.is_grid_template() {
4112                return super::grid_template::serialize_grid_template(
4113                    self.grid_template_rows,
4114                    self.grid_template_columns,
4115                    self.grid_template_areas,
4116                    dest,
4117                );
4118            }
4119
4120            if *self.grid_template_areas != GridTemplateAreas::None {
4121                return Ok(());
4122            }
4123
4124            if self.grid_auto_flow.contains(GridAutoFlow::COLUMN) {
4125                if !self.grid_auto_rows.is_initial() || !self.grid_template_columns.is_initial() {
4126                    return Ok(());
4127                }
4128
4129                if let GenericGridTemplateComponent::TrackList(ref list) = *self.grid_template_rows
4130                    && !list.is_explicit()
4131                {
4132                    return Ok(());
4133                }
4134
4135                self.grid_template_rows.to_css(dest)?;
4136                dest.write_str(" / auto-flow")?;
4137                if self.grid_auto_flow.contains(GridAutoFlow::DENSE) {
4138                    dest.write_str(" dense")?;
4139                }
4140
4141                if !self.grid_auto_columns.is_initial() {
4142                    dest.write_char(' ')?;
4143                    self.grid_auto_columns.to_css(dest)?;
4144                }
4145
4146                return Ok(());
4147            }
4148
4149            if !self.grid_auto_columns.is_initial() || !self.grid_template_rows.is_initial() {
4150                return Ok(());
4151            }
4152
4153            if let GenericGridTemplateComponent::TrackList(ref list) = *self.grid_template_columns
4154                && !list.is_explicit()
4155            {
4156                return Ok(());
4157            }
4158
4159            dest.write_str("auto-flow")?;
4160            if self.grid_auto_flow.contains(GridAutoFlow::DENSE) {
4161                dest.write_str(" dense")?;
4162            }
4163
4164            if !self.grid_auto_rows.is_initial() {
4165                dest.write_char(' ')?;
4166                self.grid_auto_rows.to_css(dest)?;
4167            }
4168
4169            dest.write_str(" / ")?;
4170            self.grid_template_columns.to_css(dest)?;
4171            Ok(())
4172        }
4173    }
4174}