]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/markdown.rs
d14275aeb6bf5e52c50ecbecb0b7e81086cb37bd
[rust.git] / src / librustdoc / html / markdown.rs
1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Markdown formatting for rustdoc
12 //!
13 //! This module implements markdown formatting through the pulldown-cmark
14 //! rust-library. This module exposes all of the
15 //! functionality through a unit-struct, `Markdown`, which has an implementation
16 //! of `fmt::Display`. Example usage:
17 //!
18 //! ```
19 //! #![feature(rustc_private)]
20 //!
21 //! use rustdoc::html::markdown::{IdMap, Markdown, ErrorCodes};
22 //! use std::cell::RefCell;
23 //!
24 //! let s = "My *markdown* _text_";
25 //! let mut id_map = IdMap::new();
26 //! let html = format!("{}", Markdown(s, &[], RefCell::new(&mut id_map), ErrorCodes::Yes));
27 //! // ... something using html
28 //! ```
29
30 #![allow(non_camel_case_types)]
31
32 use rustc_data_structures::fx::FxHashMap;
33 use std::cell::RefCell;
34 use std::collections::VecDeque;
35 use std::default::Default;
36 use std::fmt::{self, Write};
37 use std::borrow::Cow;
38 use std::ops::Range;
39 use std::str;
40 use syntax::edition::Edition;
41
42 use html::toc::TocBuilder;
43 use html::highlight;
44 use test;
45
46 use pulldown_cmark::{html, Event, Tag, Parser};
47 use pulldown_cmark::{Options, OPTION_ENABLE_FOOTNOTES, OPTION_ENABLE_TABLES};
48
49 /// A unit struct which has the `fmt::Display` trait implemented. When
50 /// formatted, this struct will emit the HTML corresponding to the rendered
51 /// version of the contained markdown string.
52 /// The second parameter is a list of link replacements
53 pub struct Markdown<'a>(
54     pub &'a str, pub &'a [(String, String)], pub RefCell<&'a mut IdMap>, pub ErrorCodes);
55 /// A unit struct like `Markdown`, that renders the markdown with a
56 /// table of contents.
57 pub struct MarkdownWithToc<'a>(pub &'a str, pub RefCell<&'a mut IdMap>, pub ErrorCodes);
58 /// A unit struct like `Markdown`, that renders the markdown escaping HTML tags.
59 pub struct MarkdownHtml<'a>(pub &'a str, pub RefCell<&'a mut IdMap>, pub ErrorCodes);
60 /// A unit struct like `Markdown`, that renders only the first paragraph.
61 pub struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [(String, String)]);
62
63 #[derive(Copy, Clone, PartialEq, Debug)]
64 pub enum ErrorCodes {
65     Yes,
66     No,
67 }
68
69 impl ErrorCodes {
70     pub fn from(b: bool) -> Self {
71         match b {
72             true => ErrorCodes::Yes,
73             false => ErrorCodes::No,
74         }
75     }
76
77     pub fn as_bool(self) -> bool {
78         match self {
79             ErrorCodes::Yes => true,
80             ErrorCodes::No => false,
81         }
82     }
83 }
84
85 /// Controls whether a line will be hidden or shown in HTML output.
86 ///
87 /// All lines are used in documentation tests.
88 enum Line<'a> {
89     Hidden(&'a str),
90     Shown(Cow<'a, str>),
91 }
92
93 impl<'a> Line<'a> {
94     fn for_html(self) -> Option<Cow<'a, str>> {
95         match self {
96             Line::Shown(l) => Some(l),
97             Line::Hidden(_) => None,
98         }
99     }
100
101     fn for_code(self) -> Cow<'a, str> {
102         match self {
103             Line::Shown(l) => l,
104             Line::Hidden(l) => Cow::Borrowed(l),
105         }
106     }
107 }
108
109 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
110 // have no easy way of removing a potential single space after the hashes, which
111 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
112 // order to fix it we'd have to iterate to find the first non-# character, and
113 // then reallocate to remove it; which would make us return a String.
114 fn map_line(s: &str) -> Line {
115     let trimmed = s.trim();
116     if trimmed.starts_with("##") {
117         Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
118     } else if trimmed.starts_with("# ") {
119         // # text
120         Line::Hidden(&trimmed[2..])
121     } else if trimmed == "#" {
122         // We cannot handle '#text' because it could be #[attr].
123         Line::Hidden("")
124     } else {
125         Line::Shown(Cow::Borrowed(s))
126     }
127 }
128
129 /// Convert chars from a title for an id.
130 ///
131 /// "Hello, world!" -> "hello-world"
132 fn slugify(c: char) -> Option<char> {
133     if c.is_alphanumeric() || c == '-' || c == '_' {
134         if c.is_ascii() {
135             Some(c.to_ascii_lowercase())
136         } else {
137             Some(c)
138         }
139     } else if c.is_whitespace() && c.is_ascii() {
140         Some('-')
141     } else {
142         None
143     }
144 }
145
146 // Information about the playground if a URL has been specified, containing an
147 // optional crate name and the URL.
148 thread_local!(pub static PLAYGROUND: RefCell<Option<(Option<String>, String)>> = {
149     RefCell::new(None)
150 });
151
152 /// Adds syntax highlighting and playground Run buttons to rust code blocks.
153 struct CodeBlocks<'a, I: Iterator<Item = Event<'a>>> {
154     inner: I,
155     check_error_codes: ErrorCodes,
156 }
157
158 impl<'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'a, I> {
159     fn new(iter: I, error_codes: ErrorCodes) -> Self {
160         CodeBlocks {
161             inner: iter,
162             check_error_codes: error_codes,
163         }
164     }
165 }
166
167 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'a, I> {
168     type Item = Event<'a>;
169
170     fn next(&mut self) -> Option<Self::Item> {
171         let event = self.inner.next();
172         let compile_fail;
173         let ignore;
174         let edition;
175         if let Some(Event::Start(Tag::CodeBlock(lang))) = event {
176             let parse_result = LangString::parse(&lang, self.check_error_codes);
177             if !parse_result.rust {
178                 return Some(Event::Start(Tag::CodeBlock(lang)));
179             }
180             compile_fail = parse_result.compile_fail;
181             ignore = parse_result.ignore;
182             edition = parse_result.edition;
183         } else {
184             return event;
185         }
186
187         let mut origtext = String::new();
188         for event in &mut self.inner {
189             match event {
190                 Event::End(Tag::CodeBlock(..)) => break,
191                 Event::Text(ref s) => {
192                     origtext.push_str(s);
193                 }
194                 _ => {}
195             }
196         }
197         let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
198         let text = lines.collect::<Vec<Cow<str>>>().join("\n");
199         PLAYGROUND.with(|play| {
200             // insert newline to clearly separate it from the
201             // previous block so we can shorten the html output
202             let mut s = String::from("\n");
203             let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
204                 if url.is_empty() {
205                     return None;
206                 }
207                 let test = origtext.lines()
208                     .map(|l| map_line(l).for_code())
209                     .collect::<Vec<Cow<str>>>().join("\n");
210                 let krate = krate.as_ref().map(|s| &**s);
211                 let (test, _) = test::make_test(&test, krate, false,
212                                            &Default::default());
213                 let channel = if test.contains("#![feature(") {
214                     "&amp;version=nightly"
215                 } else {
216                     ""
217                 };
218
219                 let edition_string = if let Some(e @ Edition::Edition2018) = edition {
220                     format!("&amp;edition={}{}", e,
221                             if channel == "&amp;version=nightly" { "" }
222                             else { "&amp;version=nightly" })
223                 } else if let Some(e) = edition {
224                     format!("&amp;edition={}", e)
225                 } else {
226                     "".to_owned()
227                 };
228
229                 // These characters don't need to be escaped in a URI.
230                 // FIXME: use a library function for percent encoding.
231                 fn dont_escape(c: u8) -> bool {
232                     (b'a' <= c && c <= b'z') ||
233                     (b'A' <= c && c <= b'Z') ||
234                     (b'0' <= c && c <= b'9') ||
235                     c == b'-' || c == b'_' || c == b'.' ||
236                     c == b'~' || c == b'!' || c == b'\'' ||
237                     c == b'(' || c == b')' || c == b'*'
238                 }
239                 let mut test_escaped = String::new();
240                 for b in test.bytes() {
241                     if dont_escape(b) {
242                         test_escaped.push(char::from(b));
243                     } else {
244                         write!(test_escaped, "%{:02X}", b).unwrap();
245                     }
246                 }
247                 Some(format!(
248                     r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
249                     url, test_escaped, channel, edition_string
250                 ))
251             });
252
253             let tooltip = if ignore {
254                 Some(("This example is not tested".to_owned(), "ignore"))
255             } else if compile_fail {
256                 Some(("This example deliberately fails to compile".to_owned(), "compile_fail"))
257             } else if let Some(e) = edition {
258                 Some((format!("This code runs with edition {}", e), "edition"))
259             } else {
260                 None
261             };
262
263             if let Some((s1, s2)) = tooltip {
264                 s.push_str(&highlight::render_with_highlighting(
265                     &text,
266                     Some(&format!("rust-example-rendered{}",
267                                   if ignore { " ignore" }
268                                   else if compile_fail { " compile_fail" }
269                                   else if edition.is_some() { " edition " }
270                                   else { "" })),
271                     playground_button.as_ref().map(String::as_str),
272                     Some((s1.as_str(), s2))));
273                 Some(Event::Html(s.into()))
274             } else {
275                 s.push_str(&highlight::render_with_highlighting(
276                     &text,
277                     Some(&format!("rust-example-rendered{}",
278                                   if ignore { " ignore" }
279                                   else if compile_fail { " compile_fail" }
280                                   else if edition.is_some() { " edition " }
281                                   else { "" })),
282                     playground_button.as_ref().map(String::as_str),
283                     None));
284                 Some(Event::Html(s.into()))
285             }
286         })
287     }
288 }
289
290 /// Make headings links with anchor ids and build up TOC.
291 struct LinkReplacer<'a, 'b, I: Iterator<Item = Event<'a>>> {
292     inner: I,
293     links: &'b [(String, String)],
294 }
295
296 impl<'a, 'b, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, 'b, I> {
297     fn new(iter: I, links: &'b [(String, String)]) -> Self {
298         LinkReplacer {
299             inner: iter,
300             links,
301         }
302     }
303 }
304
305 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, 'b, I> {
306     type Item = Event<'a>;
307
308     fn next(&mut self) -> Option<Self::Item> {
309         let event = self.inner.next();
310         if let Some(Event::Start(Tag::Link(dest, text))) = event {
311             if let Some(&(_, ref replace)) = self.links.into_iter().find(|link| &*link.0 == &*dest)
312             {
313                 Some(Event::Start(Tag::Link(replace.to_owned().into(), text)))
314             } else {
315                 Some(Event::Start(Tag::Link(dest, text)))
316             }
317         } else {
318             event
319         }
320     }
321 }
322
323 /// Make headings links with anchor ids and build up TOC.
324 struct HeadingLinks<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> {
325     inner: I,
326     toc: Option<&'b mut TocBuilder>,
327     buf: VecDeque<Event<'a>>,
328     id_map: &'ids mut IdMap,
329 }
330
331 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, 'ids, I> {
332     fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
333         HeadingLinks {
334             inner: iter,
335             toc,
336             buf: VecDeque::new(),
337             id_map: ids,
338         }
339     }
340 }
341
342 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, 'ids, I> {
343     type Item = Event<'a>;
344
345     fn next(&mut self) -> Option<Self::Item> {
346         if let Some(e) = self.buf.pop_front() {
347             return Some(e);
348         }
349
350         let event = self.inner.next();
351         if let Some(Event::Start(Tag::Header(level))) = event {
352             let mut id = String::new();
353             for event in &mut self.inner {
354                 match event {
355                     Event::End(Tag::Header(..)) => break,
356                     Event::Text(ref text) => id.extend(text.chars().filter_map(slugify)),
357                     _ => {},
358                 }
359                 self.buf.push_back(event);
360             }
361             let id = self.id_map.derive(id);
362
363             if let Some(ref mut builder) = self.toc {
364                 let mut html_header = String::new();
365                 html::push_html(&mut html_header, self.buf.iter().cloned());
366                 let sec = builder.push(level as u32, html_header, id.clone());
367                 self.buf.push_front(Event::InlineHtml(format!("{} ", sec).into()));
368             }
369
370             self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
371
372             let start_tags = format!("<h{level} id=\"{id}\" class=\"section-header\">\
373                                       <a href=\"#{id}\">",
374                                      id = id,
375                                      level = level);
376             return Some(Event::InlineHtml(start_tags.into()));
377         }
378         event
379     }
380 }
381
382 /// Extracts just the first paragraph.
383 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
384     inner: I,
385     started: bool,
386     depth: u32,
387 }
388
389 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
390     fn new(iter: I) -> Self {
391         SummaryLine {
392             inner: iter,
393             started: false,
394             depth: 0,
395         }
396     }
397 }
398
399 fn check_if_allowed_tag(t: &Tag) -> bool {
400     match *t {
401         Tag::Paragraph
402         | Tag::CodeBlock(_)
403         | Tag::Item
404         | Tag::Emphasis
405         | Tag::Strong
406         | Tag::Code
407         | Tag::Link(_, _)
408         | Tag::BlockQuote => true,
409         _ => false,
410     }
411 }
412
413 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
414     type Item = Event<'a>;
415
416     fn next(&mut self) -> Option<Self::Item> {
417         if self.started && self.depth == 0 {
418             return None;
419         }
420         if !self.started {
421             self.started = true;
422         }
423         let event = self.inner.next();
424         let mut is_start = true;
425         let is_allowed_tag = match event {
426             Some(Event::Start(ref c)) => {
427                 self.depth += 1;
428                 check_if_allowed_tag(c)
429             }
430             Some(Event::End(ref c)) => {
431                 self.depth -= 1;
432                 is_start = false;
433                 check_if_allowed_tag(c)
434             }
435             _ => true,
436         };
437         if is_allowed_tag == false {
438             if is_start {
439                 Some(Event::Start(Tag::Paragraph))
440             } else {
441                 Some(Event::End(Tag::Paragraph))
442             }
443         } else {
444             event
445         }
446     }
447 }
448
449 /// Moves all footnote definitions to the end and add back links to the
450 /// references.
451 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
452     inner: I,
453     footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
454 }
455
456 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
457     fn new(iter: I) -> Self {
458         Footnotes {
459             inner: iter,
460             footnotes: FxHashMap::default(),
461         }
462     }
463     fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
464         let new_id = self.footnotes.keys().count() + 1;
465         let key = key.to_owned();
466         self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
467     }
468 }
469
470 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
471     type Item = Event<'a>;
472
473     fn next(&mut self) -> Option<Self::Item> {
474         loop {
475             match self.inner.next() {
476                 Some(Event::FootnoteReference(ref reference)) => {
477                     let entry = self.get_entry(&reference);
478                     let reference = format!("<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}\
479                                              </a></sup>",
480                                             (*entry).1);
481                     return Some(Event::Html(reference.into()));
482                 }
483                 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
484                     let mut content = Vec::new();
485                     for event in &mut self.inner {
486                         if let Event::End(Tag::FootnoteDefinition(..)) = event {
487                             break;
488                         }
489                         content.push(event);
490                     }
491                     let entry = self.get_entry(&def);
492                     (*entry).0 = content;
493                 }
494                 Some(e) => return Some(e),
495                 None => {
496                     if !self.footnotes.is_empty() {
497                         let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
498                         v.sort_by(|a, b| a.1.cmp(&b.1));
499                         let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
500                         for (mut content, id) in v {
501                             write!(ret, "<li id=\"fn{}\">", id).unwrap();
502                             let mut is_paragraph = false;
503                             if let Some(&Event::End(Tag::Paragraph)) = content.last() {
504                                 content.pop();
505                                 is_paragraph = true;
506                             }
507                             html::push_html(&mut ret, content.into_iter());
508                             write!(ret,
509                                    "&nbsp;<a href=\"#fnref{}\" rev=\"footnote\">↩</a>",
510                                    id).unwrap();
511                             if is_paragraph {
512                                 ret.push_str("</p>");
513                             }
514                             ret.push_str("</li>");
515                         }
516                         ret.push_str("</ol></div>");
517                         return Some(Event::Html(ret.into()));
518                     } else {
519                         return None;
520                     }
521                 }
522             }
523         }
524     }
525 }
526
527 pub struct TestableCodeError(());
528
529 impl fmt::Display for TestableCodeError {
530     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
531         write!(f, "invalid start of a new code block")
532     }
533 }
534
535 pub fn find_testable_code(
536     doc: &str, tests: &mut test::Collector, error_codes: ErrorCodes,
537 ) -> Result<(), TestableCodeError> {
538     let mut parser = Parser::new(doc);
539     let mut prev_offset = 0;
540     let mut nb_lines = 0;
541     let mut register_header = None;
542     'main: while let Some(event) = parser.next() {
543         match event {
544             Event::Start(Tag::CodeBlock(s)) => {
545                 let block_info = if s.is_empty() {
546                     LangString::all_false()
547                 } else {
548                     LangString::parse(&*s, error_codes)
549                 };
550                 if !block_info.rust {
551                     continue
552                 }
553                 let mut test_s = String::new();
554                 let mut offset = None;
555                 loop {
556                     let event = parser.next();
557                     if let Some(event) = event {
558                         match event {
559                             Event::End(Tag::CodeBlock(_)) => break,
560                             Event::Text(ref s) => {
561                                 test_s.push_str(s);
562                                 if offset.is_none() {
563                                     offset = Some(parser.get_offset());
564                                 }
565                             }
566                             _ => {}
567                         }
568                     } else {
569                         break 'main;
570                     }
571                 }
572                 if let Some(offset) = offset {
573                     let lines = test_s.lines().map(|l| map_line(l).for_code());
574                     let text = lines.collect::<Vec<Cow<str>>>().join("\n");
575                     nb_lines += doc[prev_offset..offset].lines().count();
576                     let line = tests.get_line() + (nb_lines - 1);
577                     tests.add_test(text, block_info, line);
578                     prev_offset = offset;
579                 } else {
580                     return Err(TestableCodeError(()));
581                 }
582             }
583             Event::Start(Tag::Header(level)) => {
584                 register_header = Some(level as u32);
585             }
586             Event::Text(ref s) if register_header.is_some() => {
587                 let level = register_header.unwrap();
588                 if s.is_empty() {
589                     tests.register_header("", level);
590                 } else {
591                     tests.register_header(s, level);
592                 }
593                 register_header = None;
594             }
595             _ => {}
596         }
597     }
598     Ok(())
599 }
600
601 #[derive(Eq, PartialEq, Clone, Debug)]
602 pub struct LangString {
603     original: String,
604     pub should_panic: bool,
605     pub no_run: bool,
606     pub ignore: bool,
607     pub rust: bool,
608     pub test_harness: bool,
609     pub compile_fail: bool,
610     pub error_codes: Vec<String>,
611     pub allow_fail: bool,
612     pub edition: Option<Edition>
613 }
614
615 impl LangString {
616     fn all_false() -> LangString {
617         LangString {
618             original: String::new(),
619             should_panic: false,
620             no_run: false,
621             ignore: false,
622             rust: true,  // NB This used to be `notrust = false`
623             test_harness: false,
624             compile_fail: false,
625             error_codes: Vec::new(),
626             allow_fail: false,
627             edition: None,
628         }
629     }
630
631     fn parse(string: &str, allow_error_code_check: ErrorCodes) -> LangString {
632         let allow_error_code_check = allow_error_code_check.as_bool();
633         let mut seen_rust_tags = false;
634         let mut seen_other_tags = false;
635         let mut data = LangString::all_false();
636
637         data.original = string.to_owned();
638         let tokens = string.split(|c: char|
639             !(c == '_' || c == '-' || c.is_alphanumeric())
640         );
641
642         for token in tokens {
643             match token.trim() {
644                 "" => {},
645                 "should_panic" => {
646                     data.should_panic = true;
647                     seen_rust_tags = seen_other_tags == false;
648                 }
649                 "no_run" => { data.no_run = true; seen_rust_tags = !seen_other_tags; }
650                 "ignore" => { data.ignore = true; seen_rust_tags = !seen_other_tags; }
651                 "allow_fail" => { data.allow_fail = true; seen_rust_tags = !seen_other_tags; }
652                 "rust" => { data.rust = true; seen_rust_tags = true; }
653                 "test_harness" => {
654                     data.test_harness = true;
655                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
656                 }
657                 "compile_fail" => {
658                     data.compile_fail = true;
659                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
660                     data.no_run = true;
661                 }
662                 x if allow_error_code_check && x.starts_with("edition") => {
663                     // allow_error_code_check is true if we're on nightly, which
664                     // is needed for edition support
665                     data.edition = x[7..].parse::<Edition>().ok();
666                 }
667                 x if allow_error_code_check && x.starts_with("E") && x.len() == 5 => {
668                     if x[1..].parse::<u32>().is_ok() {
669                         data.error_codes.push(x.to_owned());
670                         seen_rust_tags = !seen_other_tags || seen_rust_tags;
671                     } else {
672                         seen_other_tags = true;
673                     }
674                 }
675                 _ => { seen_other_tags = true }
676             }
677         }
678
679         data.rust &= !seen_other_tags || seen_rust_tags;
680
681         data
682     }
683 }
684
685 impl<'a> fmt::Display for Markdown<'a> {
686     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
687         let Markdown(md, links, ref ids, codes) = *self;
688         let mut ids = ids.borrow_mut();
689
690         // This is actually common enough to special-case
691         if md.is_empty() { return Ok(()) }
692         let mut opts = Options::empty();
693         opts.insert(OPTION_ENABLE_TABLES);
694         opts.insert(OPTION_ENABLE_FOOTNOTES);
695
696         let replacer = |_: &str, s: &str| {
697             if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
698                 Some((replace.clone(), s.to_owned()))
699             } else {
700                 None
701             }
702         };
703
704         let p = Parser::new_with_broken_link_callback(md, opts, Some(&replacer));
705
706         let mut s = String::with_capacity(md.len() * 3 / 2);
707
708         let p = HeadingLinks::new(p, None, &mut ids);
709         let p = LinkReplacer::new(p, links);
710         let p = CodeBlocks::new(p, codes);
711         let p = Footnotes::new(p);
712         html::push_html(&mut s, p);
713
714         fmt.write_str(&s)
715     }
716 }
717
718 impl<'a> fmt::Display for MarkdownWithToc<'a> {
719     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
720         let MarkdownWithToc(md, ref ids, codes) = *self;
721         let mut ids = ids.borrow_mut();
722
723         let mut opts = Options::empty();
724         opts.insert(OPTION_ENABLE_TABLES);
725         opts.insert(OPTION_ENABLE_FOOTNOTES);
726
727         let p = Parser::new_ext(md, opts);
728
729         let mut s = String::with_capacity(md.len() * 3 / 2);
730
731         let mut toc = TocBuilder::new();
732
733         {
734             let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
735             let p = CodeBlocks::new(p, codes);
736             let p = Footnotes::new(p);
737             html::push_html(&mut s, p);
738         }
739
740         write!(fmt, "<nav id=\"TOC\">{}</nav>", toc.into_toc())?;
741
742         fmt.write_str(&s)
743     }
744 }
745
746 impl<'a> fmt::Display for MarkdownHtml<'a> {
747     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
748         let MarkdownHtml(md, ref ids, codes) = *self;
749         let mut ids = ids.borrow_mut();
750
751         // This is actually common enough to special-case
752         if md.is_empty() { return Ok(()) }
753         let mut opts = Options::empty();
754         opts.insert(OPTION_ENABLE_TABLES);
755         opts.insert(OPTION_ENABLE_FOOTNOTES);
756
757         let p = Parser::new_ext(md, opts);
758
759         // Treat inline HTML as plain text.
760         let p = p.map(|event| match event {
761             Event::Html(text) | Event::InlineHtml(text) => Event::Text(text),
762             _ => event
763         });
764
765         let mut s = String::with_capacity(md.len() * 3 / 2);
766
767         let p = HeadingLinks::new(p, None, &mut ids);
768         let p = CodeBlocks::new(p, codes);
769         let p = Footnotes::new(p);
770         html::push_html(&mut s, p);
771
772         fmt.write_str(&s)
773     }
774 }
775
776 impl<'a> fmt::Display for MarkdownSummaryLine<'a> {
777     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
778         let MarkdownSummaryLine(md, links) = *self;
779         // This is actually common enough to special-case
780         if md.is_empty() { return Ok(()) }
781
782         let replacer = |_: &str, s: &str| {
783             if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
784                 Some((replace.clone(), s.to_owned()))
785             } else {
786                 None
787             }
788         };
789
790         let p = Parser::new_with_broken_link_callback(md, Options::empty(), Some(&replacer));
791
792         let mut s = String::new();
793
794         html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
795
796         fmt.write_str(&s)
797     }
798 }
799
800 pub fn plain_summary_line(md: &str) -> String {
801     struct ParserWrapper<'a> {
802         inner: Parser<'a>,
803         is_in: isize,
804         is_first: bool,
805     }
806
807     impl<'a> Iterator for ParserWrapper<'a> {
808         type Item = String;
809
810         fn next(&mut self) -> Option<String> {
811             let next_event = self.inner.next();
812             if next_event.is_none() {
813                 return None
814             }
815             let next_event = next_event.unwrap();
816             let (ret, is_in) = match next_event {
817                 Event::Start(Tag::Paragraph) => (None, 1),
818                 Event::Start(Tag::Code) => (Some("`".to_owned()), 1),
819                 Event::End(Tag::Code) => (Some("`".to_owned()), -1),
820                 Event::Start(Tag::Header(_)) => (None, 1),
821                 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
822                 Event::End(Tag::Paragraph) | Event::End(Tag::Header(_)) => (None, -1),
823                 _ => (None, 0),
824             };
825             if is_in > 0 || (is_in < 0 && self.is_in > 0) {
826                 self.is_in += is_in;
827             }
828             if ret.is_some() {
829                 self.is_first = false;
830                 ret
831             } else {
832                 Some(String::new())
833             }
834         }
835     }
836     let mut s = String::with_capacity(md.len() * 3 / 2);
837     let mut p = ParserWrapper {
838         inner: Parser::new(md),
839         is_in: 0,
840         is_first: true,
841     };
842     while let Some(t) = p.next() {
843         if !t.is_empty() {
844             s.push_str(&t);
845         }
846     }
847     s
848 }
849
850 pub fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> {
851     if md.is_empty() {
852         return vec![];
853     }
854
855     let mut opts = Options::empty();
856     opts.insert(OPTION_ENABLE_TABLES);
857     opts.insert(OPTION_ENABLE_FOOTNOTES);
858
859     let mut links = vec![];
860     let shortcut_links = RefCell::new(vec![]);
861
862     {
863         let locate = |s: &str| unsafe {
864             let s_start = s.as_ptr();
865             let s_end = s_start.add(s.len());
866             let md_start = md.as_ptr();
867             let md_end = md_start.add(md.len());
868             if md_start <= s_start && s_end <= md_end {
869                 let start = s_start.offset_from(md_start) as usize;
870                 let end = s_end.offset_from(md_start) as usize;
871                 Some(start..end)
872             } else {
873                 None
874             }
875         };
876
877         let push = |_: &str, s: &str| {
878             shortcut_links.borrow_mut().push((s.to_owned(), locate(s)));
879             None
880         };
881         let p = Parser::new_with_broken_link_callback(md, opts,
882             Some(&push));
883
884         // There's no need to thread an IdMap through to here because
885         // the IDs generated aren't going to be emitted anywhere.
886         let mut ids = IdMap::new();
887         let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
888
889         for ev in iter {
890             if let Event::Start(Tag::Link(dest, _)) = ev {
891                 debug!("found link: {}", dest);
892                 links.push(match dest {
893                     Cow::Borrowed(s) => (s.to_owned(), locate(s)),
894                     Cow::Owned(s) => (s, None),
895                 });
896             }
897         }
898     }
899
900     let mut shortcut_links = shortcut_links.into_inner();
901     links.extend(shortcut_links.drain(..));
902
903     links
904 }
905
906 #[derive(Default)]
907 pub struct IdMap {
908     map: FxHashMap<String, usize>,
909 }
910
911 impl IdMap {
912     pub fn new() -> Self {
913         IdMap::default()
914     }
915
916     pub fn populate<I: IntoIterator<Item=String>>(&mut self, ids: I) {
917         for id in ids {
918             let _ = self.derive(id);
919         }
920     }
921
922     pub fn reset(&mut self) {
923         self.map = FxHashMap::default();
924     }
925
926     pub fn derive(&mut self, candidate: String) -> String {
927         let id = match self.map.get_mut(&candidate) {
928             None => candidate,
929             Some(a) => {
930                 let id = format!("{}-{}", candidate, *a);
931                 *a += 1;
932                 id
933             }
934         };
935
936         self.map.insert(id.clone(), 1);
937         id
938     }
939 }
940
941 #[cfg(test)]
942 #[test]
943 fn test_unique_id() {
944     let input = ["foo", "examples", "examples", "method.into_iter","examples",
945                  "method.into_iter", "foo", "main", "search", "methods",
946                  "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
947     let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
948                     "method.into_iter-1", "foo-1", "main", "search", "methods",
949                     "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
950
951     let map = RefCell::new(IdMap::new());
952     let test = || {
953         let mut map = map.borrow_mut();
954         let actual: Vec<String> = input.iter().map(|s| map.derive(s.to_string())).collect();
955         assert_eq!(&actual[..], expected);
956     };
957     test();
958     map.borrow_mut().reset();
959     test();
960 }
961
962 #[cfg(test)]
963 mod tests {
964     use super::{ErrorCodes, LangString, Markdown, MarkdownHtml, IdMap};
965     use super::plain_summary_line;
966     use std::cell::RefCell;
967     use syntax::edition::Edition;
968
969     #[test]
970     fn test_lang_string_parse() {
971         fn t(s: &str,
972             should_panic: bool, no_run: bool, ignore: bool, rust: bool, test_harness: bool,
973             compile_fail: bool, allow_fail: bool, error_codes: Vec<String>,
974              edition: Option<Edition>) {
975             assert_eq!(LangString::parse(s, ErrorCodes::Yes), LangString {
976                 should_panic,
977                 no_run,
978                 ignore,
979                 rust,
980                 test_harness,
981                 compile_fail,
982                 error_codes,
983                 original: s.to_owned(),
984                 allow_fail,
985                 edition,
986             })
987         }
988
989         fn v() -> Vec<String> {
990             Vec::new()
991         }
992
993         // ignore-tidy-linelength
994         // marker                | should_panic | no_run | ignore | rust | test_harness
995         //                       | compile_fail | allow_fail | error_codes | edition
996         t("",                      false,         false,   false,   true,  false, false, false, v(), None);
997         t("rust",                  false,         false,   false,   true,  false, false, false, v(), None);
998         t("sh",                    false,         false,   false,   false, false, false, false, v(), None);
999         t("ignore",                false,         false,   true,    true,  false, false, false, v(), None);
1000         t("should_panic",          true,          false,   false,   true,  false, false, false, v(), None);
1001         t("no_run",                false,         true,    false,   true,  false, false, false, v(), None);
1002         t("test_harness",          false,         false,   false,   true,  true,  false, false, v(), None);
1003         t("compile_fail",          false,         true,    false,   true,  false, true,  false, v(), None);
1004         t("allow_fail",            false,         false,   false,   true,  false, false, true,  v(), None);
1005         t("{.no_run .example}",    false,         true,    false,   true,  false, false, false, v(), None);
1006         t("{.sh .should_panic}",   true,          false,   false,   false, false, false, false, v(), None);
1007         t("{.example .rust}",      false,         false,   false,   true,  false, false, false, v(), None);
1008         t("{.test_harness .rust}", false,         false,   false,   true,  true,  false, false, v(), None);
1009         t("text, no_run",          false,         true,    false,   false, false, false, false, v(), None);
1010         t("text,no_run",           false,         true,    false,   false, false, false, false, v(), None);
1011         t("edition2015",           false,         false,   false,   true,  false, false, false, v(), Some(Edition::Edition2015));
1012         t("edition2018",           false,         false,   false,   true,  false, false, false, v(), Some(Edition::Edition2018));
1013     }
1014
1015     #[test]
1016     fn test_header() {
1017         fn t(input: &str, expect: &str) {
1018             let mut map = IdMap::new();
1019             let output = Markdown(input, &[], RefCell::new(&mut map), ErrorCodes::Yes).to_string();
1020             assert_eq!(output, expect, "original: {}", input);
1021         }
1022
1023         t("# Foo bar", "<h1 id=\"foo-bar\" class=\"section-header\">\
1024           <a href=\"#foo-bar\">Foo bar</a></h1>");
1025         t("## Foo-bar_baz qux", "<h2 id=\"foo-bar_baz-qux\" class=\"section-\
1026           header\"><a href=\"#foo-bar_baz-qux\">Foo-bar_baz qux</a></h2>");
1027         t("### **Foo** *bar* baz!?!& -_qux_-%",
1028           "<h3 id=\"foo-bar-baz--qux-\" class=\"section-header\">\
1029           <a href=\"#foo-bar-baz--qux-\"><strong>Foo</strong> \
1030           <em>bar</em> baz!?!&amp; -<em>qux</em>-%</a></h3>");
1031         t("#### **Foo?** & \\*bar?!*  _`baz`_ ❤ #qux",
1032           "<h4 id=\"foo--bar--baz--qux\" class=\"section-header\">\
1033           <a href=\"#foo--bar--baz--qux\"><strong>Foo?</strong> &amp; *bar?!*  \
1034           <em><code>baz</code></em> ❤ #qux</a></h4>");
1035     }
1036
1037     #[test]
1038     fn test_header_ids_multiple_blocks() {
1039         let mut map = IdMap::new();
1040         fn t(map: &mut IdMap, input: &str, expect: &str) {
1041             let output = Markdown(input, &[], RefCell::new(map), ErrorCodes::Yes).to_string();
1042             assert_eq!(output, expect, "original: {}", input);
1043         }
1044
1045         t(&mut map, "# Example", "<h1 id=\"example\" class=\"section-header\">\
1046             <a href=\"#example\">Example</a></h1>");
1047         t(&mut map, "# Panics", "<h1 id=\"panics\" class=\"section-header\">\
1048             <a href=\"#panics\">Panics</a></h1>");
1049         t(&mut map, "# Example", "<h1 id=\"example-1\" class=\"section-header\">\
1050             <a href=\"#example-1\">Example</a></h1>");
1051         t(&mut map, "# Main", "<h1 id=\"main\" class=\"section-header\">\
1052             <a href=\"#main\">Main</a></h1>");
1053         t(&mut map, "# Example", "<h1 id=\"example-2\" class=\"section-header\">\
1054             <a href=\"#example-2\">Example</a></h1>");
1055         t(&mut map, "# Panics", "<h1 id=\"panics-1\" class=\"section-header\">\
1056             <a href=\"#panics-1\">Panics</a></h1>");
1057     }
1058
1059     #[test]
1060     fn test_plain_summary_line() {
1061         fn t(input: &str, expect: &str) {
1062             let output = plain_summary_line(input);
1063             assert_eq!(output, expect, "original: {}", input);
1064         }
1065
1066         t("hello [Rust](https://www.rust-lang.org) :)", "hello Rust :)");
1067         t("hello [Rust](https://www.rust-lang.org \"Rust\") :)", "hello Rust :)");
1068         t("code `let x = i32;` ...", "code `let x = i32;` ...");
1069         t("type `Type<'static>` ...", "type `Type<'static>` ...");
1070         t("# top header", "top header");
1071         t("## header", "header");
1072     }
1073
1074     #[test]
1075     fn test_markdown_html_escape() {
1076         fn t(input: &str, expect: &str) {
1077             let mut idmap = IdMap::new();
1078             let output = MarkdownHtml(input, RefCell::new(&mut idmap), ErrorCodes::Yes).to_string();
1079             assert_eq!(output, expect, "original: {}", input);
1080         }
1081
1082         t("`Struct<'a, T>`", "<p><code>Struct&lt;'a, T&gt;</code></p>\n");
1083         t("Struct<'a, T>", "<p>Struct&lt;'a, T&gt;</p>\n");
1084         t("Struct<br>", "<p>Struct&lt;br&gt;</p>\n");
1085     }
1086 }