1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
use crate::style::errors::PropertyParseErrorKind;
use crate::style::properties::{property_data_by_name, LonghandDeclaration, PerPhase, Phase};
use crate::style::values::{CssWideKeyword, Parse};
use cssparser::{AtRuleParser, ParseError, Parser};
use cssparser::{CowRcStr, DeclarationListParser, DeclarationParser};
use std::iter::repeat;

impl std::fmt::Debug for LonghandDeclaration {
    fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        Ok(())
    }
}

#[derive(Default, Debug)]
pub struct DeclarationBlock {
    declarations: Vec<LonghandDeclaration>,
    important: smallbitvec::SmallBitVec,
    any_important: PerPhase<bool>,
    any_normal: PerPhase<bool>,
}

impl DeclarationBlock {
    pub fn parse(parser: &mut Parser) -> Self {
        let mut iter = DeclarationListParser::new(
            parser,
            LonghandDeclarationParser {
                block: DeclarationBlock::default(),
            },
        );
        loop {
            let previous_len = iter.parser.block.declarations.len();
            let result = if let Some(r) = iter.next() { r } else { break };
            match result {
                Ok(()) => {}
                Err(_) => {
                    // we may not want to break the loop - look into repaairing the parser.
                    if iter.parser.block.declarations.len() == previous_len {
                        // println!("Parse error prior block length exceeded.");
                        break;
                    }
                }
            }
            debug_assert_eq!(
                iter.parser.block.declarations.len(),
                iter.parser.block.important.len()
            );
        }
        debug_assert_eq!(
            iter.parser.block.any_normal.early || iter.parser.block.any_normal.late,
            !iter.parser.block.important.all_true()
        );
        debug_assert_eq!(
            iter.parser.block.any_important.early || iter.parser.block.any_important.late,
            !iter.parser.block.important.all_false()
        );
        iter.parser.block
    }

    pub fn cascade_normal(&self, phase: &mut impl Phase) {
        self.cascade(false, self.any_normal, phase)
    }

    pub fn cascade_important(&self, phase: &mut impl Phase) {
        self.cascade(true, self.any_important, phase)
    }

    fn cascade(&self, important: bool, any: PerPhase<bool>, phase: &mut impl Phase) {
        if phase.select(any) {
            self.declarations.iter().zip(&self.important).for_each(
                move |(declaration, declaration_important)| {
                    if declaration_important == important {
                        phase.cascade(declaration)
                    }
                },
            )
        }
    }
}

struct LonghandDeclarationParser {
    block: DeclarationBlock,
}

impl<'i> DeclarationParser<'i> for LonghandDeclarationParser {
    type Declaration = ();
    type Error = PropertyParseErrorKind<'i>;

    fn parse_value<'t>(
        &mut self,
        name: CowRcStr<'i>,
        parser: &mut Parser<'i, 't>,
    ) -> Result<Self::Declaration, ParseError<'i, Self::Error>> {
        if let Some(data) = property_data_by_name(&name) {
            let previous_len = self.block.declarations.len();
            let mut parsed;
            if let Ok(keyword) = parser.r#try(CssWideKeyword::parse) {
                parsed = PerPhase::default();
                for &longhand in data.longhands {
                    self.block
                        .declarations
                        .push(LonghandDeclaration::CssWide(longhand, keyword));
                    if longhand.is_early() {
                        parsed.early = true
                    } else {
                        parsed.late = true
                    }
                }
            } else {
                parsed = (data.parse)(parser, &mut self.block.declarations)?
            }
            let important = parser.r#try(cssparser::parse_important).is_ok();
            let count = self.block.declarations.len() - previous_len;

            if count > 0 {
                self.block.important.extend(repeat(important).take(count));
                let any = if important {
                    &mut self.block.any_important
                } else {
                    &mut self.block.any_normal
                };
                any.early |= parsed.early;
                any.late |= parsed.late;
                Ok(())
            } else {
                Err(parser.new_custom_error(PropertyParseErrorKind::UnknownUnit(name)))
            }
        } else {
            Err(parser.new_custom_error(PropertyParseErrorKind::UnknownProperty(name)))
        }
    }
}

impl<'i> AtRuleParser<'i> for LonghandDeclarationParser {
    type PreludeNoBlock = ();
    type PreludeBlock = ();
    type AtRule = ();
    type Error = PropertyParseErrorKind<'i>;
}