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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
use super::{token_as_ident, ASTNode, CSSToken, ParseError, Span, ToStringSettings, ToStringer};
use std::boxed::Box;
use tokenizer_lib::{Token, TokenReader};

/// [A css selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors)
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Selector {
    /// Can be '*' for universal
    tag_name: Option<String>,
    /// #...
    identifier: Option<String>,
    /// .x.y.z
    class_names: Option<Vec<String>>,
    /// div h1
    descendant: Option<Box<Selector>>,
    /// div > h1
    child: Option<Box<Selector>>,
    position: Option<Span>,
}

impl ASTNode for Selector {
    fn from_reader(reader: &mut impl TokenReader<CSSToken, Span>) -> Result<Self, ParseError> {
        let mut selector: Self = Self {
            tag_name: None,
            identifier: None,
            class_names: None,
            descendant: None,
            child: None,
            position: None,
        };
        for i in 0.. {
            // Handling "descendant" parsing by checking gap/space in tokens
            let peek = reader.peek().unwrap();
            if i != 0
                && peek.0 != CSSToken::CloseAngle
                && !selector.position.as_ref().unwrap().is_adjacent(&peek.1)
            {
                let descendant = Self::from_reader(reader)?;
                selector.position.as_mut().unwrap().2 = descendant.get_position().unwrap().2;
                selector.position.as_mut().unwrap().3 = descendant.get_position().unwrap().3;
                selector.descendant = Some(Box::new(descendant));
                break;
            }
            match reader.next().unwrap() {
                Token(CSSToken::Ident(name), pos) => {
                    if let Some(_) = selector.tag_name.replace(name) {
                        return Err(ParseError {
                            reason: "Tag name specified twice".to_owned(),
                            position: pos,
                        });
                    }
                    selector.position = Some(pos);
                }
                Token(CSSToken::Asterisk, pos) => {
                    if let Some(_) = selector.tag_name.replace("*".to_owned()) {
                        return Err(ParseError {
                            reason: "Tag name specified twice".to_owned(),
                            position: pos,
                        });
                    }
                    selector.position = Some(pos);
                }
                Token(CSSToken::Dot, start_span) => {
                    let (name, end_span) = token_as_ident(reader.next().unwrap())?;
                    selector
                        .class_names
                        .get_or_insert_with(|| Vec::new())
                        .push(name);
                    if let Some(ref mut selector_position) = selector.position {
                        *selector_position = selector_position.union(&end_span);
                    } else {
                        selector.position = Some(start_span.union(&end_span));
                    }
                }
                Token(CSSToken::HashPrefixedValue(identifier), position) => {
                    if selector.identifier.replace(identifier).is_some() {
                        return Err(ParseError {
                            reason: "Cannot specify to id selectors".to_owned(),
                            position,
                        });
                    }
                    if let Some(ref mut selector_position) = selector.position {
                        *selector_position = selector_position.union(&position);
                    } else {
                        selector.position = Some(position);
                    }
                }
                Token(CSSToken::CloseAngle, position) => {
                    let child = Self::from_reader(reader)?;
                    if let Some(ref mut selector_position) = selector.position {
                        *selector_position = selector_position.union(&position);
                    } else {
                        return Err(ParseError {
                            reason: "Expected selector start, found '>'".to_owned(),
                            position,
                        });
                    }
                    selector.child = Some(Box::new(child));
                    break;
                }
                Token(token, position) => {
                    return Err(ParseError {
                        reason: format!("Expected valid selector '{:?}'", token),
                        position,
                    });
                }
            }
            if matches!(
                reader.peek(),
                Some(Token(CSSToken::OpenCurly, _)) | Some(Token(CSSToken::EOS, _))
            ) {
                break;
            }
        }
        Ok(selector)
    }

    fn to_string_from_buffer(
        &self,
        buf: &mut ToStringer<'_>,
        settings: &ToStringSettings,
        depth: u8,
    ) {
        if let Some(pos) = &self.position {
            buf.add_mapping(pos.0, pos.1, pos.4);
        }
        if let Some(name) = &self.tag_name {
            buf.push_str(name);
        }
        if let Some(id) = &self.identifier {
            buf.push('#');
            buf.push_str(id);
        }
        if let Some(class_names) = &self.class_names {
            for class_name in class_names.iter() {
                buf.push('.');
                buf.push_str(class_name);
            }
        }
        if let Some(descendant) = &self.descendant {
            buf.push(' ');
            descendant.to_string_from_buffer(buf, settings, depth);
        } else if let Some(child) = &self.child {
            if !settings.minify {
                buf.push(' ');
            }
            buf.push('>');
            if !settings.minify {
                buf.push(' ');
            }
            child.to_string_from_buffer(buf, settings, depth);
        }
    }

    fn get_position(&self) -> Option<&Span> {
        self.position.as_ref()
    }
}

impl Selector {
    /// Returns other nested under self
    pub fn nest_selector(&self, other: Self) -> Self {
        let mut new_selector = self.clone();
        // Walk down the new selector descendant and child branches until at end. Then set descendant value
        // on the tail. Uses raw pointers & unsafe due to issues with Rust borrow checker
        let mut tail: *mut Selector = &mut new_selector;
        loop {
            let cur = unsafe { &mut *tail };
            if let Some(child) = cur.descendant.as_mut().or(cur.child.as_mut()) {
                tail = &mut **child;
            } else {
                cur.descendant = Some(Box::new(other));
                break;
            }
        }
        new_selector
    }
}

#[cfg(test)]
mod selector_tests {
    use super::*;

    #[test]
    fn tag_name() {
        let selector = Selector::from_string("h1".to_owned()).unwrap();
        assert_eq!(selector.tag_name, Some("h1".to_owned()));
    }

    #[test]
    fn id() {
        let selector = Selector::from_string("#button1".to_owned()).unwrap();
        assert_eq!(selector.identifier, Some("button1".to_owned()));
    }

    #[test]
    fn class_name() {
        let selector1 = Selector::from_string(".container".to_owned()).unwrap();
        assert_eq!(selector1.class_names.unwrap()[0], "container".to_owned());
        let selector2 = Selector::from_string(".container.center-x".to_owned()).unwrap();
        assert_eq!(selector2.class_names.unwrap().len(), 2);
    }

    #[test]
    fn descendant() {
        let selector = Selector::from_string("div .button".to_owned()).unwrap();
        assert_eq!(selector.tag_name, Some("div".to_owned()));
        let descendant_selector = *selector.descendant.unwrap();
        assert_eq!(
            descendant_selector.class_names.unwrap()[0],
            "button".to_owned()
        );
    }

    #[test]
    fn child() {
        let selector = Selector::from_string("div > h1".to_owned()).unwrap();
        assert_eq!(selector.tag_name, Some("div".to_owned()));
        let child_selector = *selector.child.unwrap();
        assert_eq!(child_selector.tag_name, Some("h1".to_owned()));
    }
}