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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// Copyright 2018 Evgeniy Reizner
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::str;

use xmlparser::{
    StreamError,
};

use {
    Result,
    Stream,
    StrSpan,
};

/// A pull-based style parser.
///
/// # Errors
///
/// - Most of the `Error` types can occur.
///
/// # Notes
///
/// - Entity references must be already resolved.
/// - By the SVG spec a `style` attribute can contain any style sheet language,
///   but the library only support CSS2, which is default.
/// - Objects with `-` prefix will be ignored.
/// - All comments are automatically skipped.
///
/// # Example
///
/// ```rust
/// use svgtypes::StyleParser;
///
/// let style = "/* comment */fill:red;";
/// let mut p = StyleParser::from(style);
/// let (name, value) = p.next().unwrap().unwrap();
/// assert_eq!(name.to_str(), "fill");
/// assert_eq!(value.to_str(), "red");
/// assert_eq!(p.next().is_none(), true);
/// ```
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct StyleParser<'a> {
    stream: Stream<'a>,
}

impl<'a> From<&'a str> for StyleParser<'a> {
    fn from(v: &'a str) -> Self {
        Self::from(StrSpan::from(v))
    }
}

impl<'a> From<StrSpan<'a>> for StyleParser<'a> {
    fn from(span: StrSpan<'a>) -> Self {
        StyleParser {
            stream: Stream::from(span),
        }
    }
}

impl<'a> Iterator for StyleParser<'a> {
    type Item = Result<(StrSpan<'a>, StrSpan<'a>)>;

    fn next(&mut self) -> Option<Self::Item> {
        self.stream.skip_spaces();

        if self.stream.at_end() {
            return None;
        }

        macro_rules! try2 {
            ($expr:expr) => {
                match $expr {
                    Ok(value) => value,
                    Err(e) => {
                        return Some(Err(e.into()));
                    }
                }
            }
        }

        let c = try2!(self.stream.curr_byte());
        if c == b'/' {
            try2!(skip_comment(&mut self.stream));
            self.next()
        } else if c == b'-' {
            try2!(parse_prefix(&mut self.stream));
            self.next()
        } else if is_ident_char(c) {
            Some(parse_attribute(&mut self.stream))
        } else {
            // TODO: use custom error type
            let pos = self.stream.gen_error_pos();
            self.stream.jump_to_end();
            Some(Err(StreamError::InvalidChar(vec![c, b'/', b'-'], pos).into()))
        }
    }
}

fn skip_comment(stream: &mut Stream) -> Result<()> {
    stream.skip_string(b"/*")?;
    stream.skip_bytes(|_, c| c != b'*');
    stream.skip_string(b"*/")?;
    stream.skip_spaces();

    Ok(())
}

fn parse_attribute<'a>(stream: &mut Stream<'a>) -> Result<(StrSpan<'a>, StrSpan<'a>)> {
    let name = stream.consume_bytes(|_, c| is_ident_char(c));

    if name.is_empty() {
        // TODO: this
        // The error type is irrelevant because we will ignore it anyway.
        return Err(StreamError::UnexpectedEndOfStream.into());
    }

    stream.skip_spaces();
    stream.consume_byte(b':')?;
    stream.skip_spaces();

    let value = if stream.curr_byte()? == b'\'' {
        stream.advance(1);
        let v = stream.consume_bytes(|_, c| c != b'\'');
        stream.consume_byte(b'\'')?;
        v
    } else if stream.starts_with(b"&apos;") {
        stream.advance(6);
        let v = stream.consume_bytes(|_, c| c != b'&');
        stream.skip_string(b"&apos;")?;
        v
    } else {
        stream.consume_bytes(|_, c| c != b';' && c != b'/')
    }.trim();

    if value.len() == 0 {
        return Err(StreamError::UnexpectedEndOfStream.into());
    }

    stream.skip_spaces();

    // ';;;' is valid style data, we need to skip it
    while stream.is_curr_byte_eq(b';') {
        stream.advance(1);
        stream.skip_spaces();
    }

    Ok((name, value))
}

fn parse_prefix(stream: &mut Stream) -> Result<()> {
    // prefixed attributes are not supported, aka '-webkit-*'

    stream.advance(1); // -
    let (name, _) = parse_attribute(stream)?;
    warn!("Style attribute '-{}' is skipped.", name);

    Ok(())
}

// TODO: to xmlparser traits
fn is_ident_char(c: u8) -> bool {
    match c {
        b'0'...b'9'
        | b'A'...b'Z'
        | b'a'...b'z'
        | b'-'
        | b'_' => true,
        _ => false,
    }
}

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

    macro_rules! test {
        ($name:ident, $text:expr, $(($aname:expr, $avalue:expr)),*) => (
            #[test]
            fn $name() {
                let mut s = StyleParser::from($text);
                $(
                    let (name, value) = s.next().unwrap().unwrap();
                    assert_eq!(name.to_str(), $aname);
                    assert_eq!(value.to_str(), $avalue);
                )*

                assert_eq!(s.next().is_none(), true);
            }
        )
    }

    test!(parse_1, "fill:none; color:cyan; stroke-width:4.00",
        ("fill", "none"),
        ("color", "cyan"),
        ("stroke-width", "4.00")
    );

    test!(parse_2, "fill:none;",
        ("fill", "none")
    );

    test!(parse_3, "font-size:24px;font-family:'Arial Bold'",
        ("font-size", "24px"),
        ("font-family", "Arial Bold")
    );

    test!(parse_4, "font-size:24px; /* comment */ font-style:normal;",
        ("font-size", "24px"),
        ("font-style", "normal")
    );

    test!(parse_5, "font-size:24px;-font-style:normal;font-stretch:normal;",
        ("font-size", "24px"),
        ("font-stretch", "normal")
    );

    test!(parse_6, "fill:none;-webkit:hi",
        ("fill", "none")
    );

    test!(parse_7, "font-family:&apos;Verdana&apos;",
        ("font-family", "Verdana")
    );

    test!(parse_8, "  fill  :  none  ",
        ("fill", "none")
    );

    test!(parse_10, "/**/", );

    test!(parse_11, "font-family:Cantarell;-inkscape-font-specification:&apos;Cantarell Bold&apos;",
        ("font-family", "Cantarell")
    );

    // TODO: technically incorrect, because value with spaces should be quoted
    test!(parse_12, "font-family:Neue Frutiger 65",
        ("font-family", "Neue Frutiger 65")
    );

    test!(parse_13, "/*text*/fill:green/*text*/",
        ("fill", "green")
    );

    test!(parse_14, "  /*text*/ fill:green  /*text*/ ",
        ("fill", "green")
    );

    #[test]
    fn parse_err_1() {
        let mut s = StyleParser::from(":");
        assert_eq!(s.next().unwrap().unwrap_err().to_string(),
                   "expected '/', '-' not ':' at 1:1");
    }

    #[test]
    fn parse_err_2() {
        let mut s = StyleParser::from("name:'");
        assert_eq!(s.next().unwrap().unwrap_err().to_string(),
                   "unexpected end of stream");
    }

    #[test]
    fn parse_err_3() {
        let mut s = StyleParser::from("&\x0a96M*9");
        assert_eq!(s.next().unwrap().unwrap_err().to_string(),
                   "expected '/', '-' not '&' at 1:1");
    }

    #[test]
    fn parse_err_4() {
        let mut s = StyleParser::from("/*/**/");
        assert_eq!(s.next().unwrap().is_err(), true);
    }

    #[test]
    fn parse_err_5() {
        let mut s = StyleParser::from("&#x4B2ƿ  ;");
        assert_eq!(s.next().unwrap().unwrap_err().to_string(),
                   "expected '/', '-' not '&' at 1:1");
    }

    #[test]
    fn parse_err_6() {
        let mut s = StyleParser::from("{");
        assert_eq!(s.next().unwrap().unwrap_err().to_string(),
                   "expected '/', '-' not '{' at 1:1");
    }
}