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
//! This module implements parsers for HTML hyperlinks.
//! The code follows [HTML 5.2: 4.5.](https://www.w3.org/TR/html52/textlevel-semantics.html#the-a-element)
#![allow(dead_code)]

use html_escape::decode_html_entities;
use nom::branch::alt;
use nom::bytes::complete::is_not;
use nom::bytes::complete::tag;
use nom::character::complete::alphanumeric1;
use nom::error::Error;
use nom::error::ErrorKind;
use std::borrow::Cow;

/// Parse an HTML hyperlink.
/// The parser expects to start at the link start (`<`) to succeed.
/// ```
/// use parse_hyperlinks::parser::html::html_link;
/// use std::borrow::Cow;
///
/// assert_eq!(
///   html_link(r#"<a href="destination" title="title">name</a>abc"#),
///   Ok(("abc", (Cow::from("name"), Cow::from("destination"), Cow::from("title"))))
/// );
/// ```
/// It returns either `Ok((i, (link_name, link_destination, link_title)))` or some error.
pub fn html_link(i: &str) -> nom::IResult<&str, (Cow<str>, Cow<str>, Cow<str>)> {
    let (i, ((link_destination, link_title), link_name)) = nom::sequence::terminated(
        nom::sequence::pair(tag_a_opening, nom::bytes::complete::take_until("</a>")),
        tag("</a>"),
    )(i)?;
    let link_name = decode_html_entities(link_name);
    Ok((i, (link_name, link_destination, link_title)))
}

/// Parses a `<a ...>` opening tag and returns
/// either `Ok((i, (link_destination, link_title)))` or some error.
fn tag_a_opening(i: &str) -> nom::IResult<&str, (Cow<str>, Cow<str>)> {
    nom::sequence::delimited(
        tag("<a "),
        nom::combinator::map_parser(is_not(">"), parse_attributes),
        tag(">"),
    )(i)
}

/// Parses attributes and returns `Ok((name, value))`.
/// Boolean attributes are ignored, but silently consumed.
fn attribute(i: &str) -> nom::IResult<&str, (&str, Cow<str>)> {
    alt((
        nom::sequence::pair(
            nom::combinator::verify(alphanumeric1, |s: &str| {
                nom::character::is_alphabetic(s.as_bytes()[0])
            }),
            alt((
                nom::combinator::map(
                    nom::sequence::delimited(tag("=\""), is_not("\""), tag("\"")),
                    |s: &str| decode_html_entities(s),
                ),
                nom::combinator::map(
                    nom::sequence::delimited(tag("='"), is_not("'"), tag("'")),
                    |s: &str| decode_html_entities(s),
                ),
                nom::combinator::map(nom::sequence::preceded(tag("="), is_not(" ")), |s: &str| {
                    decode_html_entities(s)
                }),
            )),
        ),
        // Consume boolean attributes.
        nom::combinator::value(
            ("", Cow::from("")),
            nom::combinator::verify(alphanumeric1, |s: &str| {
                nom::character::is_alphabetic(s.as_bytes()[0])
            }),
        ),
    ))(i)
}

/// Parses a whitespace separated list of attributes and returns a vector of (name, value).
fn attribute_list<'a>(i: &'a str) -> nom::IResult<&'a str, Vec<(&'a str, Cow<str>)>> {
    let i = i.trim();
    nom::multi::separated_list1(nom::character::complete::multispace1, attribute)(i)
}

/// Extracts the `href` and `title` attributes and returns
/// `Ok((link_destination, link_title))`. `link_title` can be empty,
/// `link_destination` not.
fn parse_attributes(i: &str) -> nom::IResult<&str, (Cow<str>, Cow<str>)> {
    let (i, attributes) = attribute_list(i)?;
    let mut href = Cow::Borrowed("");
    let mut title = Cow::Borrowed("");

    for (name, value) in attributes {
        if name == "href" {
            // Make sure `href` is empty, it can appear only
            // once.
            if &*href != "" {
                return Err(nom::Err::Error(Error::new(name, ErrorKind::ManyMN)));
            }
            href = value;
        } else if name == "title" {
            // Make sure `title` is empty, it can appear only
            // once.
            if &*title != "" {
                return Err(nom::Err::Error(Error::new(name, ErrorKind::ManyMN)));
            }
            title = value;
        }
    }

    // Assure that `href` is not empty.
    if &*href == "" {
        return Err(nom::Err::Error(Error::new(i, ErrorKind::Eof)));
    };

    Ok((i, (href, title)))
}

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

    #[test]
    fn test_html_link() {
        let expected = (
            "abc",
            (
                Cow::from("W3Schools"),
                Cow::from("https://www.w3schools.com/"),
                Cow::from("W3S"),
            ),
        );
        assert_eq!(
            html_link(r#"<a title="W3S" href="https://www.w3schools.com/">W3Schools</a>abc"#)
                .unwrap(),
            expected
        );

        let expected = ("abc", (Cow::from("<n>"), Cow::from("h"), Cow::from("t")));
        assert_eq!(
            html_link(r#"<a title="t" href="h">&lt;n&gt;</a>abc"#).unwrap(),
            expected
        );
    }

    #[test]
    fn test_tag_a_opening() {
        let expected = (
            "abc",
            (Cow::from("http://getreu.net"), Cow::from("My blog")),
        );
        assert_eq!(
            tag_a_opening(r#"<a href="http://getreu.net" title="My blog">abc"#).unwrap(),
            expected
        );
    }

    #[test]
    fn test_parse_attributes() {
        let expected = ("", (Cow::from("http://getreu.net"), Cow::from("My blog")));
        assert_eq!(
            parse_attributes(r#"abc href="http://getreu.net" abc title="My blog" abc"#).unwrap(),
            expected
        );

        let expected = nom::Err::Error(nom::error::Error::new(
            "href",
            nom::error::ErrorKind::ManyMN,
        ));
        assert_eq!(
            parse_attributes(r#" href="http://getreu.net" href="http://blog.getreu.net" "#)
                .unwrap_err(),
            expected
        );

        let expected = nom::Err::Error(nom::error::Error::new(
            "title",
            nom::error::ErrorKind::ManyMN,
        ));
        assert_eq!(
            parse_attributes(r#" href="http://getreu.net" title="a" title="b" "#).unwrap_err(),
            expected
        );

        let expected = nom::Err::Error(nom::error::Error::new("", nom::error::ErrorKind::Eof));
        assert_eq!(
            parse_attributes(r#" title="title" "#).unwrap_err(),
            expected
        );
    }

    #[test]
    fn test_attribute_list() {
        let expected = (
            "",
            vec![
                ("", Cow::from("")),
                ("href", Cow::from("http://getreu.net")),
                ("", Cow::from("")),
                ("title", Cow::from("My blog")),
                ("", Cow::from("")),
            ],
        );
        assert_eq!(
            attribute_list(r#"abc href="http://getreu.net" abc title="My blog" abc"#).unwrap(),
            expected
        );
    }
    #[test]
    fn test_attribute() {
        let expected = (" abc", ("href", Cow::from("http://getreu.net")));
        assert_eq!(
            attribute(r#"href="http://getreu.net" abc"#).unwrap(),
            expected
        );
        assert_eq!(
            attribute(r#"href='http://getreu.net' abc"#).unwrap(),
            expected
        );
        // Only allowed when no space in value.
        assert_eq!(
            attribute(r#"href=http://getreu.net abc"#).unwrap(),
            expected
        );

        let expected = (" abc", ("href", Cow::from("http://getreu.net/<>")));
        assert_eq!(
            attribute(r#"href="http://getreu.net/&lt;&gt;" abc"#).unwrap(),
            expected
        );
        assert_eq!(
            attribute(r#"href='http://getreu.net/&lt;&gt;' abc"#).unwrap(),
            expected
        );
        // Only allowed when no space in value.
        assert_eq!(
            attribute(r#"href=http://getreu.net/&lt;&gt; abc"#).unwrap(),
            expected
        );

        let expected = (" abc", ("", Cow::from("")));
        assert_eq!(attribute("bool abc").unwrap(), expected);

        let expected = nom::Err::Error(nom::error::Error::new(
            "1name",
            nom::error::ErrorKind::Verify,
        ));
        assert_eq!(attribute("1name").unwrap_err(), expected);

        let expected = nom::Err::Error(nom::error::Error::new(
            r#"1name="http://getreu.net"#,
            nom::error::ErrorKind::Verify,
        ));
        assert_eq!(
            attribute(r#"1name="http://getreu.net"#).unwrap_err(),
            expected
        );
    }
}