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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! This module implements parsers for Markdown hyperlinks.
#![allow(dead_code)]

use crate::take_until_unbalanced;
use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::combinator::*;
use nom::error::ErrorKind;

/// Parse a markdown link.
/// This parser expects to start at the beginning of the link `[` to succeed. It
/// returns either `Ok((i, (link_text, link_destination, link_title)))` or some
/// error.
/// ```
/// use parse_hyperlinks::parser::markdown::md_link;
/// assert_eq!(
///   md_link(r#"[name](<destination> "title")abc"#),
///   Ok(("abc", ("name", "destination".to_string(), "title")))
/// );
/// ```
pub fn md_link(i: &str) -> nom::IResult<&str, (&str, String, &str)> {
    let (i, link_text) = md_link_text(i)?;
    let (i, (link_destination, link_title)) = md_link_destination_enclosed(i)?;
    Ok((i, (link_text, link_destination, link_title)))
}

/// Matches a markdown link reference.
/// The parser expects to start at the beginning of link's line.
/// It returns either `Ok((i, (link_text, link_destination, link_title)))` or
/// some error.
/// ```
/// use parse_hyperlinks::parser::markdown::md_link_ref;
/// assert_eq!(
///   md_link_ref("   [name]: <destination> 'title'\nabc"),
///   Ok(("\nabc", ("name", "destination".to_string(), "title")))
/// );
/// ```
pub fn md_link_ref(i: &str) -> nom::IResult<&str, (&str, String, &str)> {
    // Consume up to three spaces.
    let (i, _) = nom::bytes::complete::take_while_m_n(0, 3, |c| c == ' ')(i)?;
    let (i, link_text) = md_link_ref_text(i)?;
    let (i, _) = verify(nom::character::complete::multispace1, |s: &str| {
        s.find("\n\n").is_none()
    })(i)?;
    let (i, link_destination) = md_link_destination(i)?;
    if let Ok((i, _)) = verify(
        nom::character::complete::multispace1::<_, (_, ErrorKind)>,
        |s: &str| s.find("\n\n").is_none(),
    )(i)
    {
        let (i, link_title) = verify(md_link_title, |s: &str| s.find("\n\n").is_none())(i)?;
        Ok((i, (link_text, link_destination, link_title)))
    } else {
        Ok((i, (link_text, link_destination, "")))
    }
}

/// [CommonMark Spec](https://spec.commonmark.org/0.29/#link-text)
///
/// Brackets are allowed in the
/// [link text](https://spec.commonmark.org/0.29/#link-text) only if (a) they are
/// backslash-escaped or (b) they appear as a matched pair of brackets, with
/// an open bracket `[`, a sequence of zero or more inlines, and a close
/// bracket `]`.
fn md_link_text(i: &str) -> nom::IResult<&str, &str> {
    nom::sequence::delimited(tag("["), take_until_unbalanced('[', ']'), tag("]"))(i)
}

/// CommonMark Spec: A [link reference definition] consists of a [link
/// label], indented up to three spaces, followed by a colon (`:`), optional
/// [whitespace] (including up to one [line ending]), a [link destination],
/// optional [whitespace] (including up to one [line ending]), and an
/// optional [link title], which if it is present must be separated from the
/// [link destination] by [whitespace]. No further [non-whitespace
/// characters] may occur on the line.
///
/// [link reference definition]: https://spec.commonmark.org/0.29/#link-reference-definition
/// [link label]: https://spec.commonmark.org/0.29/#link-label
/// [whitespace]: https://spec.commonmark.org/0.29/#whitespace
/// [line ending]: https://spec.commonmark.org/0.29/#line-ending
/// [link destination]: https://spec.commonmark.org/0.29/#link-destination
/// [whitespace]: https://spec.commonmark.org/0.29/#whitespace
/// [line ending]: https://spec.commonmark.org/0.29/#line-ending
/// [link title]: https://spec.commonmark.org/0.29/#link-title
/// [link destination]: https://spec.commonmark.org/0.29/#link-destination
/// [whitespace]: https://spec.commonmark.org/0.29/#whitespace
/// [non-whitespace characters]: https://spec.commonmark.org/0.29/#non-whitespace-character
fn md_link_ref_text(i: &str) -> nom::IResult<&str, &str> {
    nom::sequence::delimited(tag("["), take_until_unbalanced('[', ']'), tag("]:"))(i)
}

/// This is a wrapper around `md_parse_link_destination()`. It takes its result
/// and transforms the escaped characters `\\`, \<` and `\>` into `\`, `<` and
/// `>` with the help of `md_escaped_link_destination_transform()`.
fn md_link_destination(i: &str) -> nom::IResult<&str, String> {
    match md_parse_link_destination(i) {
        Ok((i, ld)) => {
            let ld = if let Ok((_, ld_trans)) = md_escaped_link_destination_transform(ld) {
                ld_trans
            } else {
                ld.to_string()
            };
            Ok((i, ld))
        }
        std::result::Result::Err(nom::Err::Error(nom::error::Error { input: _, code })) => {
            Err(nom::Err::Error(nom::error::Error::new(i, code)))
        }
        Err(_) => Err(nom::Err::Error(nom::error::Error::new(
            i,
            ErrorKind::EscapedTransform,
        ))),
    }
}

/// A [link destination](https://spec.commonmark.org/0.29/#link-destination)
/// consists of either
/// - a sequence of zero or more characters between an opening `<` and a
///   closing `>` that contains no line breaks or unescaped `<` or `>`
///   characters (TODO remark: this implementation is not as strict: it allows
///   nested `<>` and line breaks), or
/// - a nonempty sequence of characters that does not start with `<`, does
///   not include ASCII space or control characters, (TODO remark: various
///   control characters are not checked) and includes parentheses only if (a)
///   they are backslash-escaped or (b) they are part of a balanced pair of
///   unescaped parentheses. (Implementations may impose limits on parentheses
///   nesting to avoid performance issues, but at least three levels of nesting
///   should be supported.)
fn md_parse_link_destination(i: &str) -> nom::IResult<&str, &str> {
    alt((
        nom::sequence::delimited(
            tag("<"),
            nom::bytes::complete::escaped(
                nom::character::complete::none_of(r#"\<>"#),
                '\\',
                nom::character::complete::one_of(r#"<>"#),
            ),
            tag(">"),
        ),
        map_parser(
            nom::bytes::complete::is_not(" \t\r\n"),
            all_consuming(take_until_unbalanced('(', ')')),
        ),
    ))(i)
}

/// Replace the following escaped characters:
///     \\\<\>
/// with:
///     \<>
/// Preserves usual whitespace, but removes `\ `.
fn md_escaped_link_destination_transform(i: &str) -> nom::IResult<&str, String> {
    nom::bytes::complete::escaped_transform(
        nom::bytes::complete::is_not("\\"),
        '\\',
        alt((
            value("\\", tag("\\")),
            value("<", tag("<")),
            value(">", tag(">")),
        )),
    )(i)
}

/// Matches `md_link_destination` in parenthesis.
fn md_link_destination_enclosed(i: &str) -> nom::IResult<&str, (String, &str)> {
    let (rest, inner) =
        nom::sequence::delimited(tag("("), take_until_unbalanced('(', ')'), tag(")"))(i)?;
    let (i, link_destination) = md_link_destination(inner)?;
    if let Ok((i, _)) = nom::character::complete::multispace1::<_, (_, ErrorKind)>(i) {
        let (_, link_title) = md_link_title(i)?;
        Ok((rest, (link_destination, link_title)))
    } else {
        Ok((rest, (link_destination, "")))
    }
}

/// [CommonMark Spec](https://spec.commonmark.org/0.29/#link-title)
/// A [link title](https://spec.commonmark.org/0.29/#link-title) consists of either
///
///  - a sequence of zero or more characters between straight double-quote
///    characters (`"`), including a `"` character only if it is
///    backslash-escaped, or
///  - a sequence of zero or more characters between straight single-quote
///    characters (`'`), including a `'` character only if it is
///    backslash-escaped, or
///  - a sequence of zero or more characters between matching parentheses
///    (`(...)`), including a `(` or `)` character only if it is
///    backslash-escaped.
///
///  Although [link titles](https://spec.commonmark.org/0.29/#link-title) may
///  span multiple lines, they may not contain a [blank
///  line](https://spec.commonmark.org/0.29/#blank-line).
fn md_link_title(i: &str) -> nom::IResult<&str, &str> {
    verify(
        alt((
            nom::sequence::delimited(tag("("), take_until_unbalanced('(', ')'), tag(")")),
            nom::sequence::delimited(
                tag("'"),
                nom::bytes::complete::escaped(
                    nom::character::complete::none_of(r#"\'"#),
                    '\\',
                    nom::character::complete::one_of(r#"n"'()"#),
                ),
                tag("'"),
            ),
            nom::sequence::delimited(
                tag("\""),
                nom::bytes::complete::escaped(
                    nom::character::complete::none_of(r#"\""#),
                    '\\',
                    nom::character::complete::one_of(r#"n"'()"#),
                ),
                tag("\""),
            ),
        )),
        |s: &str| s.find("\n\n").is_none(),
    )(i)
}

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

    #[test]
    fn test_md_link() {
        assert_eq!(
            md_link("[text](url)abc"),
            Ok(("abc", ("text", "url".to_string(), "")))
        );
        assert_eq!(
            md_link("[text[i]](url)abc"),
            Ok(("abc", ("text[i]", "url".to_string(), "")))
        );
        assert_eq!(
            md_link("[text[i]](ur(l))abc"),
            Ok(("abc", ("text[i]", "ur(l)".to_string(), "")))
        );
        assert_eq!(
            md_link("[text(url)"),
            Err(nom::Err::Error(nom::error::Error::new("", ErrorKind::Tag)))
        );
        assert_eq!(
            md_link("[text](<url>)abc"),
            Ok(("abc", ("text", "url".to_string(), "")))
        );
        assert_eq!(
            md_link("[text](<url> \"link title\")abc"),
            Ok(("abc", ("text", "url".to_string(), "link title")))
        );
        assert_eq!(
            md_link("[text](url \"link title\")abc"),
            Ok(("abc", ("text", "url".to_string(), "link title")))
        );
    }

    #[test]
    fn test_md_link_ref() {
        assert_eq!(
            md_link_ref("[text]: url\n\"abc\""),
            Ok(("", ("text", "url".to_string(), "abc")))
        );
        assert_eq!(
            md_link_ref("   [text]: url\n\"abc\""),
            Ok(("", ("text", "url".to_string(), "abc")))
        );
        assert_eq!(
            md_link_ref("abc[text]: url\n\"abc\""),
            Err(nom::Err::Error(nom::error::Error::new(
                "abc[text]: url\n\"abc\"",
                ErrorKind::Tag
            )))
        );
        assert_eq!(
            md_link_ref("    [text]: url\n\"abc\""),
            Err(nom::Err::Error(nom::error::Error::new(
                " [text]: url\n\"abc\"",
                ErrorKind::Tag
            )))
        );
        // Nested brackets.
        assert_eq!(
            md_link_ref("[text[i]]: ur(l)url"),
            Ok(("", ("text[i]", "ur(l)url".to_string(), "")))
        );
        // Nested but balanced.
        assert_eq!(
            md_link_ref("[text[i]]: ur(l)(url"),
            Err(nom::Err::Error(nom::error::Error::new(
                "ur(l)(url",
                ErrorKind::TakeUntil
            )))
        );
        // Whitespace can have one newline.
        assert_eq!(
            md_link_ref("[text]: \nurl"),
            Ok(("", ("text", "url".to_string(), "")))
        );
        // But only one newline is allowed.
        assert_eq!(
            md_link_ref("[text]: \n\nurl"),
            Err(nom::Err::Error(nom::error::Error::new(
                " \n\nurl",
                ErrorKind::Verify
            )))
        );
        assert_eq!(
            md_link_ref("[text: url"),
            Err(nom::Err::Error(nom::error::Error::new("", ErrorKind::Tag)))
        );
        assert_eq!(
            md_link_ref("[text] url"),
            Err(nom::Err::Error(nom::error::Error::new(
                "] url",
                ErrorKind::Tag
            )))
        );
        assert_eq!(
            md_link_ref("[text]: url \"link title\"\nabc"),
            Ok(("\nabc", ("text", "url".to_string(), "link title")))
        );
        assert_eq!(
            md_link_ref("[text]: url \"link\ntitle\"\nabc"),
            Ok(("\nabc", ("text", "url".to_string(), "link\ntitle")))
        );
        assert_eq!(
            md_link_ref("[text]: url \"link\n\ntitle\"\nabc"),
            Err(nom::Err::Error(nom::error::Error::new(
                "\"link\n\ntitle\"\nabc",
                ErrorKind::Verify
            )))
        );
        assert_eq!(
            md_link_ref("[text]:\nurl \"link\ntitle\"\nabc"),
            Ok(("\nabc", ("text", "url".to_string(), "link\ntitle")))
        );
        assert_eq!(
            md_link_ref("[text]:\n\nurl \"link title\"\nabc"),
            Err(nom::Err::Error(nom::error::Error::new(
                "\n\nurl \"link title\"\nabc",
                ErrorKind::Verify
            )))
        );
    }

    #[test]
    fn test_md_link_text() {
        assert_eq!(md_link_text("[text](url)"), Ok(("(url)", "text")));
        assert_eq!(md_link_text("[text[i]](url)"), Ok(("(url)", "text[i]")));
        assert_eq!(
            md_link_text("[text(url)"),
            Err(nom::Err::Error(nom::error::Error::new("", ErrorKind::Tag)))
        );
    }

    #[test]
    fn test_md_link_ref_text() {
        assert_eq!(md_link_ref_text("[text]: url"), Ok((" url", "text")));
        assert_eq!(md_link_ref_text("[text[i]]: url"), Ok((" url", "text[i]")));
        assert_eq!(
            md_link_ref_text("[text: url"),
            Err(nom::Err::Error(nom::error::Error::new("", ErrorKind::Tag)))
        );
        assert_eq!(
            md_link_ref_text("[t[ext: url"),
            Err(nom::Err::Error(nom::error::Error::new(
                "t[ext: url",
                ErrorKind::TakeUntil
            )))
        );
    }

    #[test]
    fn test_md_link_destination() {
        assert_eq!(
            md_link_destination("<url>abc"),
            Ok(("abc", "url".to_string()))
        );
        assert_eq!(
            md_link_destination(r#"<u\<r\>l>abc"#),
            Ok(("abc", r#"u<r>l"#.to_string()))
        );
    }

    #[test]
    fn test_md_parse_link_destination() {
        assert_eq!(md_parse_link_destination("<url>abc"), Ok(("abc", "url")));
        assert_eq!(
            md_parse_link_destination(r#"<u\<r\>l>abc"#),
            Ok(("abc", r#"u\<r\>l"#))
        );
        assert_eq!(
            md_parse_link_destination("<url 2>abc"),
            Ok(("abc", "url 2"))
        );
        assert_eq!(md_parse_link_destination("url abc"), Ok((" abc", "url")));
        assert_eq!(
            md_parse_link_destination("<url(1)> abc"),
            Ok((" abc", "url(1)"))
        );
        assert_eq!(
            md_parse_link_destination("ur()l abc"),
            Ok((" abc", "ur()l"))
        );
        assert_eq!(
            md_link_title("<url>>abc"),
            Err(nom::Err::Error(nom::error::Error::new(
                "<url>>abc",
                ErrorKind::Tag
            )))
        );
        assert_eq!(
            md_link_title("<u<rl>abc"),
            Err(nom::Err::Error(nom::error::Error::new(
                "<u<rl>abc",
                ErrorKind::Tag
            )))
        );
    }

    #[test]
    fn test_md_escaped_link_destination_transform() {
        assert_eq!(
            md_escaped_link_destination_transform(""),
            Ok(("", "".to_string()))
        );
        // Different than the link destination version.
        assert_eq!(
            md_escaped_link_destination_transform("   "),
            Ok(("", "   ".to_string()))
        );
        assert_eq!(
            md_escaped_link_destination_transform(r#"abc`:<>abc"#),
            Ok(("", r#"abc`:<>abc"#.to_string()))
        );
        assert_eq!(
            md_escaped_link_destination_transform(r#"\<\>\\"#),
            Ok(("", r#"<>\"#.to_string()))
        );
    }

    #[test]
    fn test_md_link_title() {
        assert_eq!(md_link_title("(title)abc"), Ok(("abc", "title")));
        assert_eq!(md_link_title("(ti(t)le)abc"), Ok(("abc", "ti(t)le")));
        assert_eq!(
            md_link_title(r#""123\"456"abc"#),
            Ok(("abc", r#"123\"456"#))
        );
        assert_eq!(
            md_link_title(r#""tu\nv\"wxy"abc"#),
            Ok(("abc", r#"tu\nv\"wxy"#))
        );
        assert_eq!(
            md_link_title(r#"'tu\nv\'wxy'abc"#),
            Ok(("abc", r#"tu\nv\'wxy"#))
        );
        assert_eq!(
            md_link_title("(ti\n\ntle)abc"),
            Err(nom::Err::Error(nom::error::Error::new(
                "(ti\n\ntle)abc",
                ErrorKind::Verify
            )))
        );
    }
}