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
use std::fmt;
use std::borrow::Cow;

use attr::AttributeList;
use escape::Escaped;

#[derive(Clone, Debug, PartialEq, Eq)]
/// An HTML token, these are representations of everything needed to generate
/// an [HTML document](https://www.w3.org/TR/html/syntax.html#writing).
///
/// By convention, [`Token::Text`](#variant.Text) should be preferred over
/// [`Token::RawText`](#variant.RawText) when a piece of text can be
/// represented by both. For instance, use `Text` when tokenizing whitespaces
/// or line-breaks, but use `RawText` for representing all text inside
/// a `<style>` tag.
///
/// When `Display`ing a `Token`, the output stream is assumed to be Unicode, and
/// therefore only five characters are escaped: `&`, `<`, `>`, `"`, and `'`
/// ([ref](http://stackoverflow.com/a/7382028)).
pub enum Token<'a> {
    /// A [start tag](https://www.w3.org/TR/html/syntax.html#syntax-start-tag)
    /// token.
    StartTag {
        /// The element's [tag
        /// name](https://www.w3.org/TR/html/syntax.html#syntax-tag-name).
        name: Cow<'a, str>,

        /// Any attributes for the start tag.
        attrs: AttributeList<'a>,

        /// Marker indicating the tag should be self-closing, such as `<br />`
        /// (although `br` is a [void
        /// element](https://www.w3.org/TR/html/syntax.html#void-elements) so
        /// this has no effect on it).
        self_closing: bool,
    },

    /// An [end tag](https://www.w3.org/TR/html/syntax.html#syntax-end-tag)
    /// token.
    EndTag {
        /// The element's [tag
        /// name](https://www.w3.org/TR/html/syntax.html#syntax-tag-name).
        name: Cow<'a, str>,
    },

    /// The text contained will be escaped on `Display`.
    Text(Cow<'a, str>),

    /// The text contained will be `Display`ed as-is.
    RawText(Cow<'a, str>),

    /// Comments contained within `<!--` and `-->`. No validation is done to
    /// ensure that the text conforms to the [html comment
    /// syntax](https://www.w3.org/TR/html/syntax.html#syntax-comments).
    Comment(Cow<'a, str>),

    /// The [HTML5 DOCTYPE
    /// declaration](https://www.w3.org/TR/html/syntax.html#syntax-doctype)
    /// (`<!DOCTYPE html>`)
    DOCTYPE,
}

impl<'a> Token<'a> {
    /// Create a [`StartTag`](#variant.StartTag) token with specified element
    /// name and attributes, use [`closed()`](#method.closed) to set the
    /// [`self_closing`](#variant.StartTag.field.self_closing) flag.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[macro_use] extern crate hamlet;
    /// # fn main() {
    /// assert_eq!(
    ///     hamlet::Token::start_tag("script", attrs!()),
    ///     hamlet::Token::StartTag {
    ///         name: std::borrow::Cow::Borrowed("script"),
    ///         attrs: attrs!(),
    ///         self_closing: false,
    ///     });
    /// # }
    /// ```
    pub fn start_tag<S>(name: S, attrs: AttributeList<'a>) -> Token<'a>
        where S: Into<Cow<'a, str>>
    {
        Token::StartTag {
            name: name.into(),
            attrs: attrs,
            self_closing: false,
        }
    }

    /// Create an [`EndTag`](#variant.EndTag) token with specified element
    /// name.
    ///
    /// # Examples
    ///
    /// ```rust
    /// assert_eq!(
    ///     hamlet::Token::end_tag("script"),
    ///     hamlet::Token::EndTag {
    ///         name: std::borrow::Cow::Borrowed("script"),
    ///     });
    /// ```
    pub fn end_tag<S>(name: S) -> Token<'a>
        where S: Into<Cow<'a, str>>
    {
        Token::EndTag { name: name.into() }
    }

    /// Create a [`Text`](#variant.Text) token with specified text content.
    ///
    /// # Examples
    ///
    /// ```rust
    /// assert_eq!(
    ///     hamlet::Token::text("hello world"),
    ///     hamlet::Token::Text(std::borrow::Cow::Borrowed("hello world")));
    /// ```
    pub fn text<S>(s: S) -> Token<'a>
        where S: Into<Cow<'a, str>>
    {
        Token::Text(s.into())
    }


    /// Create a [`RawText`](#variant.RawText) token with specified raw text
    /// content.
    ///
    /// # Examples
    ///
    /// ```rust
    /// assert_eq!(
    ///     hamlet::Token::raw_text("hello world"),
    ///     hamlet::Token::RawText(std::borrow::Cow::Borrowed("hello world")));
    /// ```
    pub fn raw_text<S>(s: S) -> Token<'a>
        where S: Into<Cow<'a, str>>
    {
        Token::RawText(s.into())
    }

    /// Create a [`Comment`](#variant.Comment) token with specified comment
    /// content.
    ///
    /// # Examples
    ///
    /// ```rust
    /// assert_eq!(
    ///     hamlet::Token::comment("hello world"),
    ///     hamlet::Token::Comment(std::borrow::Cow::Borrowed("hello world")));
    /// ```
    pub fn comment<S>(s: S) -> Token<'a>
        where S: Into<Cow<'a, str>>
    {
        Token::Comment(s.into())
    }

    /// If `self` is a [`StartTag`](#variant.StartTag), returns a copy with
    /// [`self_closing`](#variant.StartTag.field.self_closing) set to `true`;
    /// otherwise, returns `self`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[macro_use] extern crate hamlet;
    /// # fn main() {
    /// assert_eq!(
    ///     hamlet::Token::start_tag("br", attrs!()).closed(),
    ///     hamlet::Token::StartTag {
    ///         name: std::borrow::Cow::Borrowed("br"),
    ///         attrs: attrs!(),
    ///         self_closing: true,
    ///     });
    /// # }
    /// ```
    ///
    /// ```rust
    /// assert_eq!(
    ///     hamlet::Token::text("hello world").closed(),
    ///     hamlet::Token::Text(std::borrow::Cow::Borrowed("hello world")));
    /// ```
    pub fn closed(self) -> Token<'a> {
        if let Token::StartTag { name, attrs, .. } = self {
            Token::StartTag {
                name: name,
                attrs: attrs,
                self_closing: true,
            }
        } else {
            self
        }
    }
}

impl<'a> fmt::Display for Token<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Token::StartTag { ref name, ref attrs, self_closing } => {
                try!(write!(f, "<{}", name));
                for attr in attrs.iter() {
                    try!(write!(f, " {}", attr));
                }
                if self_closing {
                    write!(f, " />")
                } else {
                    write!(f, ">")
                }
            }
            Token::EndTag { ref name } => write!(f, "</{}>", name),
            Token::Text(ref text) => write!(f, "{}", Escaped(text)),
            Token::RawText(ref text) => write!(f, "{}", text),
            Token::Comment(ref text) => write!(f, "<!--{}-->", text),
            Token::DOCTYPE => write!(f, "<!DOCTYPE html>"),
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn token_variants() {
        use Token;
        use attr::AttributeList;

        let start_tag = Token::start_tag("tag", AttributeList::empty());
        assert_eq!(format!("{}", start_tag), "<tag>");

        let end_tag = Token::end_tag("tag");
        assert_eq!(format!("{}", end_tag), "</tag>");

        let text = Token::text("<bomb>");
        assert_eq!(format!("{}", text), "&lt;bomb&gt;");

        let raw_text = Token::raw_text("<bomb>");
        assert_eq!(format!("{}", raw_text), "<bomb>");

        let comment = Token::comment("Multi\nline\ncomment");
        assert_eq!(format!("{}", comment), "<!--Multi\nline\ncomment-->");

        assert_eq!(format!("{}", Token::DOCTYPE), "<!DOCTYPE html>");
    }
}