]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/markdown.rs
rustdoc: Fix handling of compile errors when running `rustdoc --test`
[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                 self.buf.push_back(event);
384             }
385             let id = self.id_map.derive(id);
386
387             if let Some(ref mut builder) = self.toc {
388                 let mut html_header = String::new();
389                 html::push_html(&mut html_header, self.buf.iter().cloned());
390                 let sec = builder.push(level as u32, html_header, id.clone());
391                 self.buf.push_front(Event::InlineHtml(format!("{} ", sec).into()));
392             }
393
394             self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
395
396             let start_tags = format!(
397                 "<h{level} id=\"{id}\" class=\"section-header\">\
398                                       <a href=\"#{id}\">",
399                 id = id,
400                 level = level
401             );
402             return Some(Event::InlineHtml(start_tags.into()));
403         }
404         event
405     }
406 }
407
408 /// Extracts just the first paragraph.
409 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
410     inner: I,
411     started: bool,
412     depth: u32,
413 }
414
415 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
416     fn new(iter: I) -> Self {
417         SummaryLine { inner: iter, started: false, depth: 0 }
418     }
419 }
420
421 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
422     match *t {
423         Tag::Paragraph
424         | Tag::Item
425         | Tag::Emphasis
426         | Tag::Strong
427         | Tag::Link(..)
428         | Tag::BlockQuote => true,
429         _ => false,
430     }
431 }
432
433 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
434     type Item = Event<'a>;
435
436     fn next(&mut self) -> Option<Self::Item> {
437         if self.started && self.depth == 0 {
438             return None;
439         }
440         if !self.started {
441             self.started = true;
442         }
443         while let Some(event) = self.inner.next() {
444             let mut is_start = true;
445             let is_allowed_tag = match event {
446                 Event::Start(Tag::CodeBlock(_)) | Event::End(Tag::CodeBlock(_)) => {
447                     return None;
448                 }
449                 Event::Start(ref c) => {
450                     self.depth += 1;
451                     check_if_allowed_tag(c)
452                 }
453                 Event::End(ref c) => {
454                     self.depth -= 1;
455                     is_start = false;
456                     check_if_allowed_tag(c)
457                 }
458                 _ => true,
459             };
460             return if is_allowed_tag == false {
461                 if is_start {
462                     Some(Event::Start(Tag::Paragraph))
463                 } else {
464                     Some(Event::End(Tag::Paragraph))
465                 }
466             } else {
467                 Some(event)
468             };
469         }
470         None
471     }
472 }
473
474 /// Moves all footnote definitions to the end and add back links to the
475 /// references.
476 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
477     inner: I,
478     footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
479 }
480
481 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
482     fn new(iter: I) -> Self {
483         Footnotes { inner: iter, footnotes: FxHashMap::default() }
484     }
485     fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
486         let new_id = self.footnotes.keys().count() + 1;
487         let key = key.to_owned();
488         self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
489     }
490 }
491
492 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
493     type Item = Event<'a>;
494
495     fn next(&mut self) -> Option<Self::Item> {
496         loop {
497             match self.inner.next() {
498                 Some(Event::FootnoteReference(ref reference)) => {
499                     let entry = self.get_entry(&reference);
500                     let reference = format!(
501                         "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}\
502                                              </a></sup>",
503                         (*entry).1
504                     );
505                     return Some(Event::Html(reference.into()));
506                 }
507                 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
508                     let mut content = Vec::new();
509                     for event in &mut self.inner {
510                         if let Event::End(Tag::FootnoteDefinition(..)) = event {
511                             break;
512                         }
513                         content.push(event);
514                     }
515                     let entry = self.get_entry(&def);
516                     (*entry).0 = content;
517                 }
518                 Some(e) => return Some(e),
519                 None => {
520                     if !self.footnotes.is_empty() {
521                         let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
522                         v.sort_by(|a, b| a.1.cmp(&b.1));
523                         let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
524                         for (mut content, id) in v {
525                             write!(ret, "<li id=\"fn{}\">", id).unwrap();
526                             let mut is_paragraph = false;
527                             if let Some(&Event::End(Tag::Paragraph)) = content.last() {
528                                 content.pop();
529                                 is_paragraph = true;
530                             }
531                             html::push_html(&mut ret, content.into_iter());
532                             write!(ret, "&nbsp;<a href=\"#fnref{}\" rev=\"footnote\">↩</a>", id)
533                                 .unwrap();
534                             if is_paragraph {
535                                 ret.push_str("</p>");
536                             }
537                             ret.push_str("</li>");
538                         }
539                         ret.push_str("</ol></div>");
540                         return Some(Event::Html(ret.into()));
541                     } else {
542                         return None;
543                     }
544                 }
545             }
546         }
547     }
548 }
549
550 pub fn find_testable_code<T: test::Tester>(
551     doc: &str,
552     tests: &mut T,
553     error_codes: ErrorCodes,
554     enable_per_target_ignores: bool,
555 ) {
556     let mut parser = Parser::new(doc);
557     let mut prev_offset = 0;
558     let mut nb_lines = 0;
559     let mut register_header = None;
560     while let Some(event) = parser.next() {
561         match event {
562             Event::Start(Tag::CodeBlock(s)) => {
563                 let offset = parser.get_offset();
564
565                 let block_info = if s.is_empty() {
566                     LangString::all_false()
567                 } else {
568                     LangString::parse(&*s, error_codes, enable_per_target_ignores)
569                 };
570                 if !block_info.rust {
571                     continue;
572                 }
573                 let mut test_s = String::new();
574
575                 while let Some(Event::Text(s)) = parser.next() {
576                     test_s.push_str(&s);
577                 }
578
579                 let text = test_s
580                     .lines()
581                     .map(|l| map_line(l).for_code())
582                     .collect::<Vec<Cow<'_, str>>>()
583                     .join("\n");
584                 nb_lines += doc[prev_offset..offset].lines().count();
585                 let line = tests.get_line() + nb_lines;
586                 tests.add_test(text, block_info, line);
587                 prev_offset = offset;
588             }
589             Event::Start(Tag::Header(level)) => {
590                 register_header = Some(level as u32);
591             }
592             Event::Text(ref s) if register_header.is_some() => {
593                 let level = register_header.unwrap();
594                 if s.is_empty() {
595                     tests.register_header("", level);
596                 } else {
597                     tests.register_header(s, level);
598                 }
599                 register_header = None;
600             }
601             _ => {}
602         }
603     }
604 }
605
606 #[derive(Eq, PartialEq, Clone, Debug)]
607 pub struct LangString {
608     original: String,
609     pub should_panic: bool,
610     pub no_run: bool,
611     pub ignore: Ignore,
612     pub rust: bool,
613     pub test_harness: bool,
614     pub compile_fail: bool,
615     pub error_codes: Vec<String>,
616     pub allow_fail: bool,
617     pub edition: Option<Edition>,
618 }
619
620 #[derive(Eq, PartialEq, Clone, Debug)]
621 pub enum Ignore {
622     All,
623     None,
624     Some(Vec<String>),
625 }
626
627 impl LangString {
628     fn all_false() -> LangString {
629         LangString {
630             original: String::new(),
631             should_panic: false,
632             no_run: false,
633             ignore: Ignore::None,
634             rust: true, // NB This used to be `notrust = false`
635             test_harness: false,
636             compile_fail: false,
637             error_codes: Vec::new(),
638             allow_fail: false,
639             edition: None,
640         }
641     }
642
643     fn parse(
644         string: &str,
645         allow_error_code_check: ErrorCodes,
646         enable_per_target_ignores: bool,
647     ) -> LangString {
648         let allow_error_code_check = allow_error_code_check.as_bool();
649         let mut seen_rust_tags = false;
650         let mut seen_other_tags = false;
651         let mut data = LangString::all_false();
652         let mut ignores = vec![];
653
654         data.original = string.to_owned();
655         let tokens = string.split(|c: char| !(c == '_' || c == '-' || c.is_alphanumeric()));
656
657         for token in tokens {
658             match token.trim() {
659                 "" => {}
660                 "should_panic" => {
661                     data.should_panic = true;
662                     seen_rust_tags = seen_other_tags == false;
663                 }
664                 "no_run" => {
665                     data.no_run = true;
666                     seen_rust_tags = !seen_other_tags;
667                 }
668                 "ignore" => {
669                     data.ignore = Ignore::All;
670                     seen_rust_tags = !seen_other_tags;
671                 }
672                 x if x.starts_with("ignore-") => {
673                     if enable_per_target_ignores {
674                         ignores.push(x.trim_start_matches("ignore-").to_owned());
675                         seen_rust_tags = !seen_other_tags;
676                     }
677                 }
678                 "allow_fail" => {
679                     data.allow_fail = true;
680                     seen_rust_tags = !seen_other_tags;
681                 }
682                 "rust" => {
683                     data.rust = true;
684                     seen_rust_tags = true;
685                 }
686                 "test_harness" => {
687                     data.test_harness = true;
688                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
689                 }
690                 "compile_fail" => {
691                     data.compile_fail = true;
692                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
693                     data.no_run = true;
694                 }
695                 x if x.starts_with("edition") => {
696                     data.edition = x[7..].parse::<Edition>().ok();
697                 }
698                 x if allow_error_code_check && x.starts_with("E") && x.len() == 5 => {
699                     if x[1..].parse::<u32>().is_ok() {
700                         data.error_codes.push(x.to_owned());
701                         seen_rust_tags = !seen_other_tags || seen_rust_tags;
702                     } else {
703                         seen_other_tags = true;
704                     }
705                 }
706                 _ => seen_other_tags = true,
707             }
708         }
709         // ignore-foo overrides ignore
710         if !ignores.is_empty() {
711             data.ignore = Ignore::Some(ignores);
712         }
713
714         data.rust &= !seen_other_tags || seen_rust_tags;
715
716         data
717     }
718 }
719
720 impl Markdown<'_> {
721     pub fn to_string(self) -> String {
722         let Markdown(md, links, mut ids, codes, edition, playground) = self;
723
724         // This is actually common enough to special-case
725         if md.is_empty() {
726             return String::new();
727         }
728         let replacer = |_: &str, s: &str| {
729             if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
730                 Some((replace.clone(), s.to_owned()))
731             } else {
732                 None
733             }
734         };
735
736         let p = Parser::new_with_broken_link_callback(md, opts(), Some(&replacer));
737
738         let mut s = String::with_capacity(md.len() * 3 / 2);
739
740         let p = HeadingLinks::new(p, None, &mut ids);
741         let p = LinkReplacer::new(p, links);
742         let p = CodeBlocks::new(p, codes, edition, playground);
743         let p = Footnotes::new(p);
744         html::push_html(&mut s, p);
745
746         s
747     }
748 }
749
750 impl MarkdownWithToc<'_> {
751     pub fn to_string(self) -> String {
752         let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
753
754         let p = Parser::new_ext(md, opts());
755
756         let mut s = String::with_capacity(md.len() * 3 / 2);
757
758         let mut toc = TocBuilder::new();
759
760         {
761             let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
762             let p = CodeBlocks::new(p, codes, edition, playground);
763             let p = Footnotes::new(p);
764             html::push_html(&mut s, p);
765         }
766
767         format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
768     }
769 }
770
771 impl MarkdownHtml<'_> {
772     pub fn to_string(self) -> String {
773         let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
774
775         // This is actually common enough to special-case
776         if md.is_empty() {
777             return String::new();
778         }
779         let p = Parser::new_ext(md, opts());
780
781         // Treat inline HTML as plain text.
782         let p = p.map(|event| match event {
783             Event::Html(text) | Event::InlineHtml(text) => Event::Text(text),
784             _ => event,
785         });
786
787         let mut s = String::with_capacity(md.len() * 3 / 2);
788
789         let p = HeadingLinks::new(p, None, &mut ids);
790         let p = CodeBlocks::new(p, codes, edition, playground);
791         let p = Footnotes::new(p);
792         html::push_html(&mut s, p);
793
794         s
795     }
796 }
797
798 impl MarkdownSummaryLine<'_> {
799     pub fn to_string(self) -> String {
800         let MarkdownSummaryLine(md, links) = self;
801         // This is actually common enough to special-case
802         if md.is_empty() {
803             return String::new();
804         }
805
806         let replacer = |_: &str, s: &str| {
807             if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
808                 Some((replace.clone(), s.to_owned()))
809             } else {
810                 None
811             }
812         };
813
814         let p = Parser::new_with_broken_link_callback(md, Options::empty(), Some(&replacer));
815
816         let mut s = String::new();
817
818         html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
819
820         s
821     }
822 }
823
824 pub fn plain_summary_line(md: &str) -> String {
825     struct ParserWrapper<'a> {
826         inner: Parser<'a>,
827         is_in: isize,
828         is_first: bool,
829     }
830
831     impl<'a> Iterator for ParserWrapper<'a> {
832         type Item = String;
833
834         fn next(&mut self) -> Option<String> {
835             let next_event = self.inner.next();
836             if next_event.is_none() {
837                 return None;
838             }
839             let next_event = next_event.unwrap();
840             let (ret, is_in) = match next_event {
841                 Event::Start(Tag::Paragraph) => (None, 1),
842                 Event::Start(Tag::Header(_)) => (None, 1),
843                 Event::Code(code) => (Some(format!("`{}`", code)), 0),
844                 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
845                 Event::End(Tag::Paragraph) | Event::End(Tag::Header(_)) => (None, -1),
846                 _ => (None, 0),
847             };
848             if is_in > 0 || (is_in < 0 && self.is_in > 0) {
849                 self.is_in += is_in;
850             }
851             if ret.is_some() {
852                 self.is_first = false;
853                 ret
854             } else {
855                 Some(String::new())
856             }
857         }
858     }
859     let mut s = String::with_capacity(md.len() * 3 / 2);
860     let mut p = ParserWrapper { inner: Parser::new(md), is_in: 0, is_first: true };
861     while let Some(t) = p.next() {
862         if !t.is_empty() {
863             s.push_str(&t);
864         }
865     }
866     s
867 }
868
869 pub fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> {
870     if md.is_empty() {
871         return vec![];
872     }
873
874     let mut links = vec![];
875     let shortcut_links = RefCell::new(vec![]);
876
877     {
878         let locate = |s: &str| unsafe {
879             let s_start = s.as_ptr();
880             let s_end = s_start.add(s.len());
881             let md_start = md.as_ptr();
882             let md_end = md_start.add(md.len());
883             if md_start <= s_start && s_end <= md_end {
884                 let start = s_start.offset_from(md_start) as usize;
885                 let end = s_end.offset_from(md_start) as usize;
886                 Some(start..end)
887             } else {
888                 None
889             }
890         };
891
892         let push = |_: &str, s: &str| {
893             shortcut_links.borrow_mut().push((s.to_owned(), locate(s)));
894             None
895         };
896         let p = Parser::new_with_broken_link_callback(md, opts(), Some(&push));
897
898         // There's no need to thread an IdMap through to here because
899         // the IDs generated aren't going to be emitted anywhere.
900         let mut ids = IdMap::new();
901         let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
902
903         for ev in iter {
904             if let Event::Start(Tag::Link(_, dest, _)) = ev {
905                 debug!("found link: {}", dest);
906                 links.push(match dest {
907                     CowStr::Borrowed(s) => (s.to_owned(), locate(s)),
908                     s @ CowStr::Boxed(..) | s @ CowStr::Inlined(..) => (s.into_string(), None),
909                 });
910             }
911         }
912     }
913
914     let mut shortcut_links = shortcut_links.into_inner();
915     links.extend(shortcut_links.drain(..));
916
917     links
918 }
919
920 #[derive(Debug)]
921 crate struct RustCodeBlock {
922     /// The range in the markdown that the code block occupies. Note that this includes the fences
923     /// for fenced code blocks.
924     pub range: Range<usize>,
925     /// The range in the markdown that the code within the code block occupies.
926     pub code: Range<usize>,
927     pub is_fenced: bool,
928     pub syntax: Option<String>,
929 }
930
931 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
932 /// untagged (and assumed to be rust).
933 crate fn rust_code_blocks(md: &str) -> Vec<RustCodeBlock> {
934     let mut code_blocks = vec![];
935
936     if md.is_empty() {
937         return code_blocks;
938     }
939
940     let mut p = Parser::new_ext(md, opts());
941
942     let mut code_block_start = 0;
943     let mut code_start = 0;
944     let mut is_fenced = false;
945     let mut previous_offset = 0;
946     let mut in_rust_code_block = false;
947     while let Some(event) = p.next() {
948         let offset = p.get_offset();
949
950         match event {
951             Event::Start(Tag::CodeBlock(syntax)) => {
952                 let lang_string = if syntax.is_empty() {
953                     LangString::all_false()
954                 } else {
955                     LangString::parse(&*syntax, ErrorCodes::Yes, false)
956                 };
957
958                 if lang_string.rust {
959                     in_rust_code_block = true;
960
961                     code_start = offset;
962                     code_block_start = match md[previous_offset..offset].find("```") {
963                         Some(fence_idx) => {
964                             is_fenced = true;
965                             previous_offset + fence_idx
966                         }
967                         None => {
968                             is_fenced = false;
969                             offset
970                         }
971                     };
972                 }
973             }
974             Event::End(Tag::CodeBlock(syntax)) if in_rust_code_block => {
975                 in_rust_code_block = false;
976
977                 let code_block_end = if is_fenced {
978                     let fence_str = &md[previous_offset..offset].chars().rev().collect::<String>();
979                     fence_str
980                         .find("```")
981                         .map(|fence_idx| offset - fence_idx)
982                         .unwrap_or_else(|| offset)
983                 } else if md.as_bytes().get(offset).map(|b| *b == b'\n').unwrap_or_default() {
984                     offset - 1
985                 } else {
986                     offset
987                 };
988
989                 let code_end = if is_fenced { previous_offset } else { code_block_end };
990
991                 code_blocks.push(RustCodeBlock {
992                     is_fenced,
993                     range: Range { start: code_block_start, end: code_block_end },
994                     code: Range { start: code_start, end: code_end },
995                     syntax: if !syntax.is_empty() { Some(syntax.into_string()) } else { None },
996                 });
997             }
998             _ => (),
999         }
1000
1001         previous_offset = offset;
1002     }
1003
1004     code_blocks
1005 }
1006
1007 #[derive(Clone, Default, Debug)]
1008 pub struct IdMap {
1009     map: FxHashMap<String, usize>,
1010 }
1011
1012 impl IdMap {
1013     pub fn new() -> Self {
1014         IdMap::default()
1015     }
1016
1017     pub fn populate<I: IntoIterator<Item = String>>(&mut self, ids: I) {
1018         for id in ids {
1019             let _ = self.derive(id);
1020         }
1021     }
1022
1023     pub fn reset(&mut self) {
1024         self.map = FxHashMap::default();
1025     }
1026
1027     pub fn derive(&mut self, candidate: String) -> String {
1028         let id = match self.map.get_mut(&candidate) {
1029             None => candidate,
1030             Some(a) => {
1031                 let id = format!("{}-{}", candidate, *a);
1032                 *a += 1;
1033                 id
1034             }
1035         };
1036
1037         self.map.insert(id.clone(), 1);
1038         id
1039     }
1040 }