]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/markdown.rs
Rollup merge of #69563 - andre-richter:fix_no_std_match, r=Mark-Simulacrum
[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, CodeBlockKind, 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(kind))) = event {
193             let parse_result = match kind {
194                 CodeBlockKind::Fenced(ref lang) => {
195                     LangString::parse(&lang, self.check_error_codes, false)
196                 }
197                 CodeBlockKind::Indented => LangString::all_false(),
198             };
199             if !parse_result.rust {
200                 return Some(Event::Start(Tag::CodeBlock(kind)));
201             }
202             compile_fail = parse_result.compile_fail;
203             ignore = parse_result.ignore;
204             edition = parse_result.edition;
205         } else {
206             return event;
207         }
208
209         let explicit_edition = edition.is_some();
210         let edition = edition.unwrap_or(self.edition);
211
212         let mut origtext = String::new();
213         for event in &mut self.inner {
214             match event {
215                 Event::End(Tag::CodeBlock(..)) => break,
216                 Event::Text(ref s) => {
217                     origtext.push_str(s);
218                 }
219                 _ => {}
220             }
221         }
222         let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
223         let text = lines.collect::<Vec<Cow<'_, str>>>().join("\n");
224         // insert newline to clearly separate it from the
225         // previous block so we can shorten the html output
226         let mut s = String::from("\n");
227         let playground_button = self.playground.as_ref().and_then(|playground| {
228             let krate = &playground.crate_name;
229             let url = &playground.url;
230             if url.is_empty() {
231                 return None;
232             }
233             let test = origtext
234                 .lines()
235                 .map(|l| map_line(l).for_code())
236                 .collect::<Vec<Cow<'_, str>>>()
237                 .join("\n");
238             let krate = krate.as_ref().map(|s| &**s);
239             let (test, _) = test::make_test(&test, krate, false, &Default::default(), edition);
240             let channel = if test.contains("#![feature(") { "&amp;version=nightly" } else { "" };
241
242             let edition_string = format!("&amp;edition={}", edition);
243
244             // These characters don't need to be escaped in a URI.
245             // FIXME: use a library function for percent encoding.
246             fn dont_escape(c: u8) -> bool {
247                 (b'a' <= c && c <= b'z')
248                     || (b'A' <= c && c <= b'Z')
249                     || (b'0' <= c && c <= b'9')
250                     || c == b'-'
251                     || c == b'_'
252                     || c == b'.'
253                     || c == b'~'
254                     || c == b'!'
255                     || c == b'\''
256                     || c == b'('
257                     || c == b')'
258                     || c == b'*'
259             }
260             let mut test_escaped = String::new();
261             for b in test.bytes() {
262                 if dont_escape(b) {
263                     test_escaped.push(char::from(b));
264                 } else {
265                     write!(test_escaped, "%{:02X}", b).unwrap();
266                 }
267             }
268             Some(format!(
269                 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
270                 url, test_escaped, channel, edition_string
271             ))
272         });
273
274         let tooltip = if ignore != Ignore::None {
275             Some(("This example is not tested".to_owned(), "ignore"))
276         } else if compile_fail {
277             Some(("This example deliberately fails to compile".to_owned(), "compile_fail"))
278         } else if explicit_edition {
279             Some((format!("This code runs with edition {}", edition), "edition"))
280         } else {
281             None
282         };
283
284         if let Some((s1, s2)) = tooltip {
285             s.push_str(&highlight::render_with_highlighting(
286                 &text,
287                 Some(&format!(
288                     "rust-example-rendered{}",
289                     if ignore != Ignore::None {
290                         " ignore"
291                     } else if compile_fail {
292                         " compile_fail"
293                     } else if explicit_edition {
294                         " edition "
295                     } else {
296                         ""
297                     }
298                 )),
299                 playground_button.as_ref().map(String::as_str),
300                 Some((s1.as_str(), s2)),
301             ));
302             Some(Event::Html(s.into()))
303         } else {
304             s.push_str(&highlight::render_with_highlighting(
305                 &text,
306                 Some(&format!(
307                     "rust-example-rendered{}",
308                     if ignore != Ignore::None {
309                         " ignore"
310                     } else if compile_fail {
311                         " compile_fail"
312                     } else if explicit_edition {
313                         " edition "
314                     } else {
315                         ""
316                     }
317                 )),
318                 playground_button.as_ref().map(String::as_str),
319                 None,
320             ));
321             Some(Event::Html(s.into()))
322         }
323     }
324 }
325
326 /// Make headings links with anchor IDs and build up TOC.
327 struct LinkReplacer<'a, 'b, I: Iterator<Item = Event<'a>>> {
328     inner: I,
329     links: &'b [(String, String)],
330 }
331
332 impl<'a, 'b, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, 'b, I> {
333     fn new(iter: I, links: &'b [(String, String)]) -> Self {
334         LinkReplacer { inner: iter, links }
335     }
336 }
337
338 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, 'b, I> {
339     type Item = Event<'a>;
340
341     fn next(&mut self) -> Option<Self::Item> {
342         let event = self.inner.next();
343         if let Some(Event::Start(Tag::Link(kind, dest, text))) = event {
344             if let Some(&(_, ref replace)) = self.links.iter().find(|link| link.0 == *dest) {
345                 Some(Event::Start(Tag::Link(kind, replace.to_owned().into(), text)))
346             } else {
347                 Some(Event::Start(Tag::Link(kind, dest, text)))
348             }
349         } else {
350             event
351         }
352     }
353 }
354
355 /// Make headings links with anchor IDs and build up TOC.
356 struct HeadingLinks<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> {
357     inner: I,
358     toc: Option<&'b mut TocBuilder>,
359     buf: VecDeque<Event<'a>>,
360     id_map: &'ids mut IdMap,
361 }
362
363 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, 'ids, I> {
364     fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
365         HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids }
366     }
367 }
368
369 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, 'ids, I> {
370     type Item = Event<'a>;
371
372     fn next(&mut self) -> Option<Self::Item> {
373         if let Some(e) = self.buf.pop_front() {
374             return Some(e);
375         }
376
377         let event = self.inner.next();
378         if let Some(Event::Start(Tag::Heading(level))) = event {
379             let mut id = String::new();
380             for event in &mut self.inner {
381                 match &event {
382                     Event::End(Tag::Heading(..)) => break,
383                     Event::Text(text) | Event::Code(text) => {
384                         id.extend(text.chars().filter_map(slugify));
385                     }
386                     _ => {}
387                 }
388                 match event {
389                     Event::Start(Tag::Link(_, _, _)) | Event::End(Tag::Link(..)) => {}
390                     event => self.buf.push_back(event),
391                 }
392             }
393             let id = self.id_map.derive(id);
394
395             if let Some(ref mut builder) = self.toc {
396                 let mut html_header = String::new();
397                 html::push_html(&mut html_header, self.buf.iter().cloned());
398                 let sec = builder.push(level as u32, html_header, id.clone());
399                 self.buf.push_front(Event::Html(format!("{} ", sec).into()));
400             }
401
402             self.buf.push_back(Event::Html(format!("</a></h{}>", level).into()));
403
404             let start_tags = format!(
405                 "<h{level} id=\"{id}\" class=\"section-header\">\
406                     <a href=\"#{id}\">",
407                 id = id,
408                 level = level
409             );
410             return Some(Event::Html(start_tags.into()));
411         }
412         event
413     }
414 }
415
416 /// Extracts just the first paragraph.
417 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
418     inner: I,
419     started: bool,
420     depth: u32,
421 }
422
423 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
424     fn new(iter: I) -> Self {
425         SummaryLine { inner: iter, started: false, depth: 0 }
426     }
427 }
428
429 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
430     match *t {
431         Tag::Paragraph
432         | Tag::Item
433         | Tag::Emphasis
434         | Tag::Strong
435         | Tag::Link(..)
436         | Tag::BlockQuote => true,
437         _ => false,
438     }
439 }
440
441 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
442     type Item = Event<'a>;
443
444     fn next(&mut self) -> Option<Self::Item> {
445         if self.started && self.depth == 0 {
446             return None;
447         }
448         if !self.started {
449             self.started = true;
450         }
451         while let Some(event) = self.inner.next() {
452             let mut is_start = true;
453             let is_allowed_tag = match event {
454                 Event::Start(Tag::CodeBlock(_)) | Event::End(Tag::CodeBlock(_)) => {
455                     return None;
456                 }
457                 Event::Start(ref c) => {
458                     self.depth += 1;
459                     check_if_allowed_tag(c)
460                 }
461                 Event::End(ref c) => {
462                     self.depth -= 1;
463                     is_start = false;
464                     check_if_allowed_tag(c)
465                 }
466                 _ => true,
467             };
468             return if !is_allowed_tag {
469                 if is_start {
470                     Some(Event::Start(Tag::Paragraph))
471                 } else {
472                     Some(Event::End(Tag::Paragraph))
473                 }
474             } else {
475                 Some(event)
476             };
477         }
478         None
479     }
480 }
481
482 /// Moves all footnote definitions to the end and add back links to the
483 /// references.
484 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
485     inner: I,
486     footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
487 }
488
489 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
490     fn new(iter: I) -> Self {
491         Footnotes { inner: iter, footnotes: FxHashMap::default() }
492     }
493     fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
494         let new_id = self.footnotes.keys().count() + 1;
495         let key = key.to_owned();
496         self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
497     }
498 }
499
500 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
501     type Item = Event<'a>;
502
503     fn next(&mut self) -> Option<Self::Item> {
504         loop {
505             match self.inner.next() {
506                 Some(Event::FootnoteReference(ref reference)) => {
507                     let entry = self.get_entry(&reference);
508                     let reference = format!(
509                         "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}\
510                                              </a></sup>",
511                         (*entry).1
512                     );
513                     return Some(Event::Html(reference.into()));
514                 }
515                 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
516                     let mut content = Vec::new();
517                     for event in &mut self.inner {
518                         if let Event::End(Tag::FootnoteDefinition(..)) = event {
519                             break;
520                         }
521                         content.push(event);
522                     }
523                     let entry = self.get_entry(&def);
524                     (*entry).0 = content;
525                 }
526                 Some(e) => return Some(e),
527                 None => {
528                     if !self.footnotes.is_empty() {
529                         let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
530                         v.sort_by(|a, b| a.1.cmp(&b.1));
531                         let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
532                         for (mut content, id) in v {
533                             write!(ret, "<li id=\"fn{}\">", id).unwrap();
534                             let mut is_paragraph = false;
535                             if let Some(&Event::End(Tag::Paragraph)) = content.last() {
536                                 content.pop();
537                                 is_paragraph = true;
538                             }
539                             html::push_html(&mut ret, content.into_iter());
540                             write!(ret, "&nbsp;<a href=\"#fnref{}\" rev=\"footnote\">↩</a>", id)
541                                 .unwrap();
542                             if is_paragraph {
543                                 ret.push_str("</p>");
544                             }
545                             ret.push_str("</li>");
546                         }
547                         ret.push_str("</ol></div>");
548                         return Some(Event::Html(ret.into()));
549                     } else {
550                         return None;
551                     }
552                 }
553             }
554         }
555     }
556 }
557
558 pub fn find_testable_code<T: test::Tester>(
559     doc: &str,
560     tests: &mut T,
561     error_codes: ErrorCodes,
562     enable_per_target_ignores: bool,
563 ) {
564     let mut parser = Parser::new(doc).into_offset_iter();
565     let mut prev_offset = 0;
566     let mut nb_lines = 0;
567     let mut register_header = None;
568     while let Some((event, offset)) = parser.next() {
569         match event {
570             Event::Start(Tag::CodeBlock(kind)) => {
571                 let block_info = match kind {
572                     CodeBlockKind::Fenced(ref lang) => {
573                         if lang.is_empty() {
574                             LangString::all_false()
575                         } else {
576                             LangString::parse(lang, error_codes, enable_per_target_ignores)
577                         }
578                     }
579                     CodeBlockKind::Indented => LangString::all_false(),
580                 };
581                 if !block_info.rust {
582                     continue;
583                 }
584
585                 let mut test_s = String::new();
586
587                 while let Some((Event::Text(s), _)) = parser.next() {
588                     test_s.push_str(&s);
589                 }
590                 let text = test_s
591                     .lines()
592                     .map(|l| map_line(l).for_code())
593                     .collect::<Vec<Cow<'_, str>>>()
594                     .join("\n");
595
596                 nb_lines += doc[prev_offset..offset.start].lines().count();
597                 let line = tests.get_line() + nb_lines + 1;
598                 tests.add_test(text, block_info, line);
599                 prev_offset = offset.start;
600             }
601             Event::Start(Tag::Heading(level)) => {
602                 register_header = Some(level as u32);
603             }
604             Event::Text(ref s) if register_header.is_some() => {
605                 let level = register_header.unwrap();
606                 if s.is_empty() {
607                     tests.register_header("", level);
608                 } else {
609                     tests.register_header(s, level);
610                 }
611                 register_header = None;
612             }
613             _ => {}
614         }
615     }
616 }
617
618 #[derive(Eq, PartialEq, Clone, Debug)]
619 pub struct LangString {
620     original: String,
621     pub should_panic: bool,
622     pub no_run: bool,
623     pub ignore: Ignore,
624     pub rust: bool,
625     pub test_harness: bool,
626     pub compile_fail: bool,
627     pub error_codes: Vec<String>,
628     pub allow_fail: bool,
629     pub edition: Option<Edition>,
630 }
631
632 #[derive(Eq, PartialEq, Clone, Debug)]
633 pub enum Ignore {
634     All,
635     None,
636     Some(Vec<String>),
637 }
638
639 impl LangString {
640     fn all_false() -> LangString {
641         LangString {
642             original: String::new(),
643             should_panic: false,
644             no_run: false,
645             ignore: Ignore::None,
646             rust: true, // NB This used to be `notrust = false`
647             test_harness: false,
648             compile_fail: false,
649             error_codes: Vec::new(),
650             allow_fail: false,
651             edition: None,
652         }
653     }
654
655     fn parse(
656         string: &str,
657         allow_error_code_check: ErrorCodes,
658         enable_per_target_ignores: bool,
659     ) -> LangString {
660         let allow_error_code_check = allow_error_code_check.as_bool();
661         let mut seen_rust_tags = false;
662         let mut seen_other_tags = false;
663         let mut data = LangString::all_false();
664         let mut ignores = vec![];
665
666         data.original = string.to_owned();
667         let tokens = string.split(|c: char| !(c == '_' || c == '-' || c.is_alphanumeric()));
668
669         for token in tokens {
670             match token.trim() {
671                 "" => {}
672                 "should_panic" => {
673                     data.should_panic = true;
674                     seen_rust_tags = !seen_other_tags;
675                 }
676                 "no_run" => {
677                     data.no_run = true;
678                     seen_rust_tags = !seen_other_tags;
679                 }
680                 "ignore" => {
681                     data.ignore = Ignore::All;
682                     seen_rust_tags = !seen_other_tags;
683                 }
684                 x if x.starts_with("ignore-") => {
685                     if enable_per_target_ignores {
686                         ignores.push(x.trim_start_matches("ignore-").to_owned());
687                         seen_rust_tags = !seen_other_tags;
688                     }
689                 }
690                 "allow_fail" => {
691                     data.allow_fail = true;
692                     seen_rust_tags = !seen_other_tags;
693                 }
694                 "rust" => {
695                     data.rust = true;
696                     seen_rust_tags = true;
697                 }
698                 "test_harness" => {
699                     data.test_harness = true;
700                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
701                 }
702                 "compile_fail" => {
703                     data.compile_fail = true;
704                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
705                     data.no_run = true;
706                 }
707                 x if x.starts_with("edition") => {
708                     data.edition = x[7..].parse::<Edition>().ok();
709                 }
710                 x if allow_error_code_check && x.starts_with('E') && x.len() == 5 => {
711                     if x[1..].parse::<u32>().is_ok() {
712                         data.error_codes.push(x.to_owned());
713                         seen_rust_tags = !seen_other_tags || seen_rust_tags;
714                     } else {
715                         seen_other_tags = true;
716                     }
717                 }
718                 _ => seen_other_tags = true,
719             }
720         }
721         // ignore-foo overrides ignore
722         if !ignores.is_empty() {
723             data.ignore = Ignore::Some(ignores);
724         }
725
726         data.rust &= !seen_other_tags || seen_rust_tags;
727
728         data
729     }
730 }
731
732 impl Markdown<'_> {
733     pub fn to_string(self) -> String {
734         let Markdown(md, links, mut ids, codes, edition, playground) = self;
735
736         // This is actually common enough to special-case
737         if md.is_empty() {
738             return String::new();
739         }
740         let replacer = |_: &str, s: &str| {
741             if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
742                 Some((replace.clone(), s.to_owned()))
743             } else {
744                 None
745             }
746         };
747
748         let p = Parser::new_with_broken_link_callback(md, opts(), Some(&replacer));
749
750         let mut s = String::with_capacity(md.len() * 3 / 2);
751
752         let p = HeadingLinks::new(p, None, &mut ids);
753         let p = LinkReplacer::new(p, links);
754         let p = CodeBlocks::new(p, codes, edition, playground);
755         let p = Footnotes::new(p);
756         html::push_html(&mut s, p);
757
758         s
759     }
760 }
761
762 impl MarkdownWithToc<'_> {
763     pub fn to_string(self) -> String {
764         let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
765
766         let p = Parser::new_ext(md, opts());
767
768         let mut s = String::with_capacity(md.len() * 3 / 2);
769
770         let mut toc = TocBuilder::new();
771
772         {
773             let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
774             let p = CodeBlocks::new(p, codes, edition, playground);
775             let p = Footnotes::new(p);
776             html::push_html(&mut s, p);
777         }
778
779         format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
780     }
781 }
782
783 impl MarkdownHtml<'_> {
784     pub fn to_string(self) -> String {
785         let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
786
787         // This is actually common enough to special-case
788         if md.is_empty() {
789             return String::new();
790         }
791         let p = Parser::new_ext(md, opts());
792
793         // Treat inline HTML as plain text.
794         let p = p.map(|event| match event {
795             Event::Html(text) => Event::Text(text),
796             _ => event,
797         });
798
799         let mut s = String::with_capacity(md.len() * 3 / 2);
800
801         let p = HeadingLinks::new(p, None, &mut ids);
802         let p = CodeBlocks::new(p, codes, edition, playground);
803         let p = Footnotes::new(p);
804         html::push_html(&mut s, p);
805
806         s
807     }
808 }
809
810 impl MarkdownSummaryLine<'_> {
811     pub fn to_string(self) -> String {
812         let MarkdownSummaryLine(md, links) = self;
813         // This is actually common enough to special-case
814         if md.is_empty() {
815             return String::new();
816         }
817
818         let replacer = |_: &str, s: &str| {
819             if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
820                 Some((replace.clone(), s.to_owned()))
821             } else {
822                 None
823             }
824         };
825
826         let p = Parser::new_with_broken_link_callback(md, Options::empty(), Some(&replacer));
827
828         let mut s = String::new();
829
830         html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
831
832         s
833     }
834 }
835
836 pub fn plain_summary_line(md: &str) -> String {
837     struct ParserWrapper<'a> {
838         inner: Parser<'a>,
839         is_in: isize,
840         is_first: bool,
841     }
842
843     impl<'a> Iterator for ParserWrapper<'a> {
844         type Item = String;
845
846         fn next(&mut self) -> Option<String> {
847             let next_event = self.inner.next();
848             if next_event.is_none() {
849                 return None;
850             }
851             let next_event = next_event.unwrap();
852             let (ret, is_in) = match next_event {
853                 Event::Start(Tag::Paragraph) => (None, 1),
854                 Event::Start(Tag::Heading(_)) => (None, 1),
855                 Event::Code(code) => (Some(format!("`{}`", code)), 0),
856                 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
857                 Event::End(Tag::Paragraph) | Event::End(Tag::Heading(_)) => (None, -1),
858                 _ => (None, 0),
859             };
860             if is_in > 0 || (is_in < 0 && self.is_in > 0) {
861                 self.is_in += is_in;
862             }
863             if ret.is_some() {
864                 self.is_first = false;
865                 ret
866             } else {
867                 Some(String::new())
868             }
869         }
870     }
871     let mut s = String::with_capacity(md.len() * 3 / 2);
872     let mut p = ParserWrapper { inner: Parser::new(md), is_in: 0, is_first: true };
873     while let Some(t) = p.next() {
874         if !t.is_empty() {
875             s.push_str(&t);
876         }
877     }
878     s
879 }
880
881 pub fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> {
882     if md.is_empty() {
883         return vec![];
884     }
885
886     let mut links = vec![];
887     let shortcut_links = RefCell::new(vec![]);
888
889     {
890         let locate = |s: &str| unsafe {
891             let s_start = s.as_ptr();
892             let s_end = s_start.add(s.len());
893             let md_start = md.as_ptr();
894             let md_end = md_start.add(md.len());
895             if md_start <= s_start && s_end <= md_end {
896                 let start = s_start.offset_from(md_start) as usize;
897                 let end = s_end.offset_from(md_start) as usize;
898                 Some(start..end)
899             } else {
900                 None
901             }
902         };
903
904         let push = |_: &str, s: &str| {
905             shortcut_links.borrow_mut().push((s.to_owned(), locate(s)));
906             None
907         };
908         let p = Parser::new_with_broken_link_callback(md, opts(), Some(&push));
909
910         // There's no need to thread an IdMap through to here because
911         // the IDs generated aren't going to be emitted anywhere.
912         let mut ids = IdMap::new();
913         let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
914
915         for ev in iter {
916             if let Event::Start(Tag::Link(_, dest, _)) = ev {
917                 debug!("found link: {}", dest);
918                 links.push(match dest {
919                     CowStr::Borrowed(s) => (s.to_owned(), locate(s)),
920                     s @ CowStr::Boxed(..) | s @ CowStr::Inlined(..) => (s.into_string(), None),
921                 });
922             }
923         }
924     }
925
926     let mut shortcut_links = shortcut_links.into_inner();
927     links.extend(shortcut_links.drain(..));
928
929     links
930 }
931
932 #[derive(Debug)]
933 crate struct RustCodeBlock {
934     /// The range in the markdown that the code block occupies. Note that this includes the fences
935     /// for fenced code blocks.
936     pub range: Range<usize>,
937     /// The range in the markdown that the code within the code block occupies.
938     pub code: Range<usize>,
939     pub is_fenced: bool,
940     pub syntax: Option<String>,
941 }
942
943 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
944 /// untagged (and assumed to be rust).
945 crate fn rust_code_blocks(md: &str) -> Vec<RustCodeBlock> {
946     let mut code_blocks = vec![];
947
948     if md.is_empty() {
949         return code_blocks;
950     }
951
952     let mut p = Parser::new_ext(md, opts()).into_offset_iter();
953
954     while let Some((event, offset)) = p.next() {
955         match event {
956             Event::Start(Tag::CodeBlock(syntax)) => {
957                 let (syntax, code_start, code_end, range, is_fenced) = match syntax {
958                     CodeBlockKind::Fenced(syntax) => {
959                         let syntax = syntax.as_ref();
960                         let lang_string = if syntax.is_empty() {
961                             LangString::all_false()
962                         } else {
963                             LangString::parse(&*syntax, ErrorCodes::Yes, false)
964                         };
965                         if !lang_string.rust {
966                             continue;
967                         }
968                         let syntax = if syntax.is_empty() { None } else { Some(syntax.to_owned()) };
969                         let (code_start, mut code_end) = match p.next() {
970                             Some((Event::Text(_), offset)) => (offset.start, offset.end),
971                             Some((_, sub_offset)) => {
972                                 let code = Range { start: sub_offset.start, end: sub_offset.start };
973                                 code_blocks.push(RustCodeBlock {
974                                     is_fenced: true,
975                                     range: offset,
976                                     code,
977                                     syntax,
978                                 });
979                                 continue;
980                             }
981                             None => {
982                                 let code = Range { start: offset.end, end: offset.end };
983                                 code_blocks.push(RustCodeBlock {
984                                     is_fenced: true,
985                                     range: offset,
986                                     code,
987                                     syntax,
988                                 });
989                                 continue;
990                             }
991                         };
992                         while let Some((Event::Text(_), offset)) = p.next() {
993                             code_end = offset.end;
994                         }
995                         (syntax, code_start, code_end, offset, true)
996                     }
997                     CodeBlockKind::Indented => {
998                         // The ending of the offset goes too far sometime so we reduce it by one in
999                         // these cases.
1000                         if offset.end > offset.start
1001                             && md.get(offset.end..=offset.end) == Some(&"\n")
1002                         {
1003                             (
1004                                 None,
1005                                 offset.start,
1006                                 offset.end,
1007                                 Range { start: offset.start, end: offset.end - 1 },
1008                                 false,
1009                             )
1010                         } else {
1011                             (None, offset.start, offset.end, offset, false)
1012                         }
1013                     }
1014                 };
1015
1016                 code_blocks.push(RustCodeBlock {
1017                     is_fenced,
1018                     range,
1019                     code: Range { start: code_start, end: code_end },
1020                     syntax,
1021                 });
1022             }
1023             _ => (),
1024         }
1025     }
1026
1027     code_blocks
1028 }
1029
1030 #[derive(Clone, Default, Debug)]
1031 pub struct IdMap {
1032     map: FxHashMap<String, usize>,
1033 }
1034
1035 impl IdMap {
1036     pub fn new() -> Self {
1037         IdMap::default()
1038     }
1039
1040     pub fn populate<I: IntoIterator<Item = String>>(&mut self, ids: I) {
1041         for id in ids {
1042             let _ = self.derive(id);
1043         }
1044     }
1045
1046     pub fn reset(&mut self) {
1047         self.map = FxHashMap::default();
1048     }
1049
1050     pub fn derive(&mut self, candidate: String) -> String {
1051         let id = match self.map.get_mut(&candidate) {
1052             None => candidate,
1053             Some(a) => {
1054                 let id = format!("{}-{}", candidate, *a);
1055                 *a += 1;
1056                 id
1057             }
1058         };
1059
1060         self.map.insert(id.clone(), 1);
1061         id
1062     }
1063 }