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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//! This module implements parsers for RestructuredText hyperlinks.
#![allow(dead_code)]

use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::combinator::*;
use nom::error::Error;
use nom::error::ErrorKind;
use nom::IResult;

/// Parse a RestructuredText hyperlink.
/// The parser expects to start at the link start (\`) to succeed.
/// ```
/// use parse_hyperlinks::parser::restructured_text::rst_link;
/// assert_eq!(
///   rst_link("`name <destination>`_abc"),
///   Ok(("abc", ("name".to_string(), "destination".to_string())))
/// );
/// ```
/// A hyperlink reference may directly embed a destination URI or (since Docutils
/// 0.11) a hyperlink reference within angle brackets `<>` as shown in the
/// following example:
/// ```rst
/// abc `Python home page <http://www.python.org>`_ abc
/// ```
/// The bracketed URI must be preceded by whitespace and be the last text
/// before the end string. For more details see the
/// [reStructuredText Markup
/// Specification](https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#embedded-uris-and-aliases)
/// It returns either `Ok((i, (link_name, link_destination)))` or some error.
pub fn rst_link(i: &str) -> nom::IResult<&str, (String, String)> {
    match rst_parse_link(i) {
        Ok((i, (ln, lt))) => {
            let ln = if let Ok((_, ln_trans)) = rst_escaped_link_name_transform(ln) {
                ln_trans
            } else {
                ln.to_string()
            };
            let lt = if let Ok((_, lt_trans)) = rst_escaped_link_destination_transform(lt) {
                lt_trans
            } else {
                lt.to_string()
            };
            Ok((i, (ln, lt)))
        }
        std::result::Result::Err(nom::Err::Error(nom::error::Error { input: _, code })) => {
            Err(nom::Err::Error(Error::new(i, code)))
        }
        Err(_) => Err(nom::Err::Error(Error::new(i, ErrorKind::EscapedTransform))),
    }
}

/// Parse a RestructuredText link references.
/// The parser expects to start at the beginning of the line.
/// ```
/// use parse_hyperlinks::parser::restructured_text::rst_link_ref;
/// assert_eq!(
///   rst_link_ref("   .. _`name`: destination\nabc"),
///   Ok(("\nabc", ("name".to_string(), "destination".to_string())))
/// );
/// ```
/// Here some examples for link references:
/// ```rst
/// .. _Python home page: http://www.python.org
/// .. _`Python: home page`: http://www.python.org
/// ```
/// See unit test `test_rst_link_ref()` for more examples.
/// It returns either `Ok((i, (link_name, link_destination)))` or some error.
pub fn rst_link_ref(i: &str) -> nom::IResult<&str, (String, String)> {
    let (i, block) = rst_explicit_markup_block(i)?;
    match rst_parse_link_ref(block.as_str()) {
        Ok((_, (ln, lt))) => {
            let ln = if let Ok((_, ln_trans)) = rst_escaped_link_name_transform(ln) {
                ln_trans
            } else {
                ln.to_string()
            };
            let lt = if let Ok((_, lt_trans)) = rst_escaped_link_destination_transform(lt) {
                lt_trans
            } else {
                lt.to_string()
            };
            Ok((i, (ln, lt)))
        }
        std::result::Result::Err(nom::Err::Error(nom::error::Error { input: _, code })) => {
            Err(nom::Err::Error(Error::new(i, code)))
        }
        Err(_) => Err(nom::Err::Error(nom::error::Error::new(
            i,
            ErrorKind::EscapedTransform,
        ))),
    }
}

/// This parser used by `rst_link()`, does all the work that can be
/// done without allocating new strings.
/// Removing of escaped characters is not performed here.
fn rst_parse_link(i: &str) -> nom::IResult<&str, (&str, &str)> {
    let (i, j) = nom::sequence::delimited(
        tag("`"),
        nom::bytes::complete::escaped(
            nom::character::complete::none_of(r#"\`"#),
            '\\',
            nom::character::complete::one_of(r#" `:<>"#),
        ),
        tag("`_"),
    )(i)?;
    // Consume another optional pending `_`, if there is one. This can not fail.
    let (i, _) = nom::combinator::opt(nom::bytes::complete::tag("_"))(i)?;

    // From here on, we only deal with the inner result of the above.
    // Take everything until the first unescaped `<`
    let (j, link_name): (&str, &str) = nom::bytes::complete::escaped(
        nom::character::complete::none_of(r#"\<"#),
        '\\',
        nom::character::complete::one_of(r#" `:<>"#),
    )(j)?;
    // Trim trailing whitespace.
    let link_name = link_name.trim_end();
    let (j, link_destination) = nom::sequence::delimited(
        tag("<"),
        nom::bytes::complete::escaped(
            nom::character::complete::none_of(r#"\<>"#),
            '\\',
            nom::character::complete::one_of(r#" `:<>"#),
        ),
        tag(">"),
    )(j)?;
    // Fail if there are bytes left between `>` and `\``.
    let (_, _) = nom::combinator::eof(j)?;

    Ok((i, (link_name, link_destination)))
}

/// This parser detects the position of the link name and the link destination.
/// It does not perform any transformation.
/// This parser expects to start at the beginning of the line.
/// If the reference name contains any colons, either:
/// * the phrase must be enclosed in backquotes, or
/// * the colon must be backslash escaped.
/// [reStructuredText Markup
/// Specification](https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#hyperlink-targets)
fn rst_parse_link_ref(i: &str) -> nom::IResult<&str, (&str, &str)> {
    let (i, _) = nom::character::complete::char('_')(i)?;
    let (link_destination, link_name) = alt((
        nom::sequence::delimited(
            tag("`"),
            nom::bytes::complete::escaped(
                nom::character::complete::none_of(r#"\`"#),
                '\\',
                nom::character::complete::one_of(r#" `:<>"#),
            ),
            tag("`: "),
        ),
        nom::sequence::terminated(
            nom::bytes::complete::escaped(
                nom::character::complete::none_of(r#"\:"#),
                '\\',
                nom::character::complete::one_of(r#" `:<>"#),
            ),
            tag(": "),
        ),
    ))(i)?;

    Ok(("", (link_name, link_destination)))
}

/// This parses an explicit markup block.
/// The parser expects to start at the beginning of the line.
/// Syntax diagram:
/// ```text
/// +-------+----------------------+
/// | ".. " | in  1                |
/// +-------+ in  2                |
///         |    in  3             |
///         +----------------------+
/// out
/// ```
/// An explicit markup block is a text block:
/// * whose first line begins with ".." followed by whitespace (the "explicit
///   markup start"),
/// * whose second and subsequent lines (if any) are indented relative to the
///   first, and
/// * which ends before an unindented line
/// As with external hyperlink targets, the link block of an indirect
/// hyperlink target may begin on the same line as the explicit markup start
/// or the next line. It may also be split over multiple lines, in which case
/// the lines are joined with whitespace before being normalized.
fn rst_explicit_markup_block(i: &str) -> nom::IResult<&str, String> {
    fn indent<'a>(wsp1: &'a str, wsp2: &'a str) -> impl Fn(&'a str) -> IResult<&'a str, ()> {
        move |i: &str| {
            let (i, _) = nom::character::complete::line_ending(i)?;
            let (i, _) = nom::bytes::complete::tag(wsp1)(i)?;
            let (i, _) = nom::bytes::complete::tag(wsp2)(i)?;
            Ok((i, ()))
        }
    }

    let (i, (wsp1, wsp2)) = nom::sequence::pair(
        nom::character::complete::space0,
        nom::combinator::map(nom::bytes::complete::tag(".. "), |_| "   "),
    )(i)?;

    let (i, v) = nom::multi::separated_list1(
        indent(&wsp1, &wsp2),
        nom::character::complete::not_line_ending,
    )(i)?;

    let mut s = String::new();
    let mut is_first = true;

    for subs in &v {
        if !is_first {
            s.push(' ');
        }
        s.push_str(subs);
        is_first = false;
    }

    Ok((i, s))
}

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

/// Replace the following escaped characters:
///     \\\`\ \:\<\>
/// with:
///     \` :<>
/// Deletes all whitespace, but keeps one space for each `\ `.
fn rst_escaped_link_destination_transform(mut i: &str) -> IResult<&str, String> {
    let mut res = String::new();

    while i != "" {
        let (j, _) = nom::character::complete::space0(i)?;
        let (j, s) = nom::bytes::complete::escaped_transform(
            nom::bytes::complete::is_not("\\ \t"),
            '\\',
            alt((
                value("\\", tag("\\")),
                value("`", tag("`")),
                value(":", tag(":")),
                value("<", tag("<")),
                value(">", tag(">")),
                value(" ", tag(" ")),
            )),
        )(j)?;
        res.push_str(&s);
        i = j;
    }
    Ok(("", res))
}

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

    #[test]
    fn test_rst_link() {
        let expected = (
            "abc",
            (
                "Python home page".to_string(),
                "http://www.python.org".to_string(),
            ),
        );
        assert_eq!(
            rst_link("`Python home page <http://www.python.org>`_abc").unwrap(),
            expected
        );
        assert_eq!(
            rst_link("`Python home page <http://www.python.org>`__abc").unwrap(),
            expected
        );

        let expected = (
            "",
            (
                r#"Python<home> page"#.to_string(),
                "http://www.python.org".to_string(),
            ),
        );
        assert_eq!(
            rst_link(r#"`Python\ \<home\> page <http://www.python.org>`_"#).unwrap(),
            expected
        );

        let expected = (
            "",
            (
                r#"my news at <http://python.org>"#.to_string(),
                "http://news.python.org".to_string(),
            ),
        );
        assert_eq!(
            rst_link(r#"`my news at \<http://python.org\> <http://news.python.org>`_"#).unwrap(),
            expected
        );

        let expected = (
            "",
            (
                r#"my news at <http://python.org>"#.to_string(),
                r#"http://news. <python>.org"#.to_string(),
            ),
        );
        assert_eq!(
            rst_link(r#"`my news at \<http\://python.org\> <http:// news.\ \<python\>.org>`_"#)
                .unwrap(),
            expected
        );
    }

    #[test]
    fn test_rst_link_ref() {
        let expected = (
            "\nabc",
            (
                "Python: home page".to_string(),
                "http://www.python.org".to_string(),
            ),
        );
        assert_eq!(
            rst_link_ref(".. _`Python: home page`: http://www.python.org\nabc").unwrap(),
            expected
        );
        assert_eq!(
            rst_link_ref("  .. _`Python: home page`: http://www.py\n     thon.org    \nabc")
                .unwrap(),
            expected
        );

        let expected = nom::Err::Error(nom::error::Error::new(
            "x .. _`Python: home page`: http://www.python.org\nabc",
            ErrorKind::Tag,
        ));
        assert_eq!(
            rst_link_ref("x .. _`Python: home page`: http://www.python.org\nabc").unwrap_err(),
            expected
        );

        let expected = (
            "",
            (
                "Python: `home page`".to_string(),
                "http://www.python .org".to_string(),
            ),
        );
        assert_eq!(
            rst_link_ref(r#".. _Python\: \`home page\`: http://www.python\ .org"#).unwrap(),
            expected
        );
        assert_eq!(
            rst_link_ref(r#".. _`Python: \`home page\``: http://www.python\ .org"#).unwrap(),
            expected
        );

        let expected = (
            "",
            (
                "my news at <http://python.org>".to_string(),
                "http://news.python.org".to_string(),
            ),
        );
        assert_eq!(
            rst_link_ref(r#".. _`my news at <http://python.org>`: http://news.python.org"#)
                .unwrap(),
            expected
        );
        assert_eq!(
            rst_link_ref(r#".. _`my news at \<http://python.org\>`: http://news.python.org"#)
                .unwrap(),
            expected
        );
        assert_eq!(
            rst_link_ref(r#".. _my news at \<http\://python.org\>: http://news.python.org"#)
                .unwrap(),
            expected
        );

        let expected = (
            "",
            (
                "my news".to_string(),
                "http://news.<python>.org".to_string(),
            ),
        );
        assert_eq!(
            rst_link_ref(r#".. _my news: http://news.<python>.org"#).unwrap(),
            expected
        );
        assert_eq!(
            rst_link_ref(r#".. _my news: http://news.\<python\>.org"#).unwrap(),
            expected
        );
    }

    #[test]
    fn test_rst_parse_link() {
        let expected = ("abc", ("Python home page", "http://www.python.org"));
        assert_eq!(
            rst_parse_link("`Python home page <http://www.python.org>`_abc").unwrap(),
            expected
        );

        let expected = ("", (r#"Python\ \<home\> page"#, "http://www.python.org"));
        assert_eq!(
            rst_parse_link(r#"`Python\ \<home\> page <http://www.python.org>`_"#).unwrap(),
            expected
        );

        let expected = (
            "",
            (
                r#"my news at \<http://python.org\>"#,
                "http://news.python.org",
            ),
        );
        assert_eq!(
            rst_parse_link(r#"`my news at \<http://python.org\> <http://news.python.org>`_"#)
                .unwrap(),
            expected
        );

        let expected = (
            "",
            (
                r#"my news at \<http\://python.org\>"#,
                r#"http:// news.\ \<python\>.org"#,
            ),
        );
        assert_eq!(
            rst_parse_link(
                r#"`my news at \<http\://python.org\> <http:// news.\ \<python\>.org>`_"#
            )
            .unwrap(),
            expected
        );
    }

    #[test]
    fn test_rst_parse_link_ref() {
        let expected = ("", ("Python home page", "http://www.python.org"));
        assert_eq!(
            rst_parse_link_ref("_Python home page: http://www.python.org").unwrap(),
            expected
        );
        assert_eq!(
            rst_parse_link_ref("_`Python home page`: http://www.python.org").unwrap(),
            expected
        );

        let expected = ("", ("Python: home page", "http://www.python.org"));
        assert_eq!(
            rst_parse_link_ref("_`Python: home page`: http://www.python.org").unwrap(),
            expected
        );

        let expected = ("", (r#"Python\: home page"#, "http://www.python.org"));
        assert_eq!(
            rst_parse_link_ref(r#"_Python\: home page: http://www.python.org"#).unwrap(),
            expected
        );

        let expected = (
            "",
            ("my news at <http://python.org>", "http://news.python.org"),
        );
        assert_eq!(
            rst_parse_link_ref(r#"_`my news at <http://python.org>`: http://news.python.org"#)
                .unwrap(),
            expected
        );

        let expected = (
            "",
            (
                r#"my news at \<http://python.org\>"#,
                "http://news.python.org",
            ),
        );
        assert_eq!(
            rst_parse_link_ref(r#"_`my news at \<http://python.org\>`: http://news.python.org"#)
                .unwrap(),
            expected
        );

        let expected = (
            "",
            (
                r#"my news at \<http\://python.org\>"#,
                "http://news.python.org",
            ),
        );
        assert_eq!(
            rst_parse_link_ref(r#"_my news at \<http\://python.org\>: http://news.python.org"#)
                .unwrap(),
            expected
        );
    }

    #[test]
    fn test_rst_explicit_markup_block() {
        assert_eq!(
            rst_explicit_markup_block(".. 11111"),
            Ok(("", "11111".to_string()))
        );
        assert_eq!(
            rst_explicit_markup_block("   .. 11111\nout"),
            Ok(("\nout", "11111".to_string()))
        );
        assert_eq!(
            rst_explicit_markup_block("   .. 11111\n      222222\n      333333\nout"),
            Ok(("\nout", "11111 222222 333333".to_string()))
        );
        assert_eq!(
            rst_explicit_markup_block("   .. first\n      second\n       1indent\nout"),
            Ok(("\nout", "first second  1indent".to_string()))
        );
        assert_eq!(
            rst_explicit_markup_block("   ..first"),
            Err(nom::Err::Error(nom::error::Error::new(
                "..first",
                ErrorKind::Tag
            )))
        );
        assert_eq!(
            rst_explicit_markup_block("x  .. first"),
            Err(nom::Err::Error(nom::error::Error::new(
                "x  .. first",
                ErrorKind::Tag
            )))
        );
    }

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

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