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