]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/markdown.rs
Apply suggestions from code review
[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.into_string();
17 //! // ... something using html
18 //! ```
19
20 use rustc_data_structures::fx::FxHashMap;
21 use rustc_hir::def_id::DefId;
22 use rustc_hir::HirId;
23 use rustc_middle::ty::TyCtxt;
24 use rustc_span::edition::Edition;
25 use rustc_span::Span;
26
27 use std::borrow::Cow;
28 use std::cell::RefCell;
29 use std::collections::VecDeque;
30 use std::default::Default;
31 use std::fmt::Write;
32 use std::ops::{ControlFlow, Range};
33 use std::str;
34
35 use crate::clean::RenderedLink;
36 use crate::doctest;
37 use crate::html::escape::Escape;
38 use crate::html::format::Buffer;
39 use crate::html::highlight;
40 use crate::html::length_limit::HtmlWithLimit;
41 use crate::html::toc::TocBuilder;
42
43 use pulldown_cmark::{
44     html, BrokenLink, CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag,
45 };
46
47 #[cfg(test)]
48 mod tests;
49
50 /// Options for rendering Markdown in the main body of documentation.
51 pub(crate) fn main_body_opts() -> Options {
52     Options::ENABLE_TABLES
53         | Options::ENABLE_FOOTNOTES
54         | Options::ENABLE_STRIKETHROUGH
55         | Options::ENABLE_TASKLISTS
56         | Options::ENABLE_SMART_PUNCTUATION
57 }
58
59 /// Options for rendering Markdown in summaries (e.g., in search results).
60 pub(crate) fn summary_opts() -> Options {
61     Options::ENABLE_TABLES
62         | Options::ENABLE_FOOTNOTES
63         | Options::ENABLE_STRIKETHROUGH
64         | Options::ENABLE_TASKLISTS
65         | Options::ENABLE_SMART_PUNCTUATION
66 }
67
68 /// When `to_string` is called, this struct will emit the HTML corresponding to
69 /// the rendered version of the contained markdown string.
70 pub struct Markdown<'a>(
71     pub &'a str,
72     /// A list of link replacements.
73     pub &'a [RenderedLink],
74     /// The current list of used header IDs.
75     pub &'a mut IdMap,
76     /// Whether to allow the use of explicit error codes in doctest lang strings.
77     pub ErrorCodes,
78     /// Default edition to use when parsing doctests (to add a `fn main`).
79     pub Edition,
80     pub &'a Option<Playground>,
81 );
82 /// A tuple struct like `Markdown` that renders the markdown with a table of contents.
83 crate struct MarkdownWithToc<'a>(
84     crate &'a str,
85     crate &'a mut IdMap,
86     crate ErrorCodes,
87     crate Edition,
88     crate &'a Option<Playground>,
89 );
90 /// A tuple struct like `Markdown` that renders the markdown escaping HTML tags.
91 crate struct MarkdownHtml<'a>(
92     crate &'a str,
93     crate &'a mut IdMap,
94     crate ErrorCodes,
95     crate Edition,
96     crate &'a Option<Playground>,
97 );
98 /// A tuple struct like `Markdown` that renders only the first paragraph.
99 crate struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [RenderedLink]);
100
101 #[derive(Copy, Clone, PartialEq, Debug)]
102 pub enum ErrorCodes {
103     Yes,
104     No,
105 }
106
107 impl ErrorCodes {
108     crate fn from(b: bool) -> Self {
109         match b {
110             true => ErrorCodes::Yes,
111             false => ErrorCodes::No,
112         }
113     }
114
115     crate fn as_bool(self) -> bool {
116         match self {
117             ErrorCodes::Yes => true,
118             ErrorCodes::No => false,
119         }
120     }
121 }
122
123 /// Controls whether a line will be hidden or shown in HTML output.
124 ///
125 /// All lines are used in documentation tests.
126 enum Line<'a> {
127     Hidden(&'a str),
128     Shown(Cow<'a, str>),
129 }
130
131 impl<'a> Line<'a> {
132     fn for_html(self) -> Option<Cow<'a, str>> {
133         match self {
134             Line::Shown(l) => Some(l),
135             Line::Hidden(_) => None,
136         }
137     }
138
139     fn for_code(self) -> Cow<'a, str> {
140         match self {
141             Line::Shown(l) => l,
142             Line::Hidden(l) => Cow::Borrowed(l),
143         }
144     }
145 }
146
147 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
148 // have no easy way of removing a potential single space after the hashes, which
149 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
150 // order to fix it we'd have to iterate to find the first non-# character, and
151 // then reallocate to remove it; which would make us return a String.
152 fn map_line(s: &str) -> Line<'_> {
153     let trimmed = s.trim();
154     if trimmed.starts_with("##") {
155         Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
156     } else if let Some(stripped) = trimmed.strip_prefix("# ") {
157         // # text
158         Line::Hidden(&stripped)
159     } else if trimmed == "#" {
160         // We cannot handle '#text' because it could be #[attr].
161         Line::Hidden("")
162     } else {
163         Line::Shown(Cow::Borrowed(s))
164     }
165 }
166
167 /// Convert chars from a title for an id.
168 ///
169 /// "Hello, world!" -> "hello-world"
170 fn slugify(c: char) -> Option<char> {
171     if c.is_alphanumeric() || c == '-' || c == '_' {
172         if c.is_ascii() { Some(c.to_ascii_lowercase()) } else { Some(c) }
173     } else if c.is_whitespace() && c.is_ascii() {
174         Some('-')
175     } else {
176         None
177     }
178 }
179
180 #[derive(Clone, Debug)]
181 pub struct Playground {
182     pub crate_name: Option<String>,
183     pub url: String,
184 }
185
186 /// Adds syntax highlighting and playground Run buttons to Rust code blocks.
187 struct CodeBlocks<'p, 'a, I: Iterator<Item = Event<'a>>> {
188     inner: I,
189     check_error_codes: ErrorCodes,
190     edition: Edition,
191     // Information about the playground if a URL has been specified, containing an
192     // optional crate name and the URL.
193     playground: &'p Option<Playground>,
194 }
195
196 impl<'p, 'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'p, 'a, I> {
197     fn new(
198         iter: I,
199         error_codes: ErrorCodes,
200         edition: Edition,
201         playground: &'p Option<Playground>,
202     ) -> Self {
203         CodeBlocks { inner: iter, check_error_codes: error_codes, edition, playground }
204     }
205 }
206
207 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
208     type Item = Event<'a>;
209
210     fn next(&mut self) -> Option<Self::Item> {
211         let event = self.inner.next();
212         let compile_fail;
213         let should_panic;
214         let ignore;
215         let edition;
216         let kind = if let Some(Event::Start(Tag::CodeBlock(kind))) = event {
217             kind
218         } else {
219             return event;
220         };
221
222         let mut origtext = String::new();
223         for event in &mut self.inner {
224             match event {
225                 Event::End(Tag::CodeBlock(..)) => break,
226                 Event::Text(ref s) => {
227                     origtext.push_str(s);
228                 }
229                 _ => {}
230             }
231         }
232         let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
233         let text = lines.collect::<Vec<Cow<'_, str>>>().join("\n");
234
235         let parse_result = match kind {
236             CodeBlockKind::Fenced(ref lang) => {
237                 let parse_result =
238                     LangString::parse_without_check(&lang, self.check_error_codes, false);
239                 if !parse_result.rust {
240                     return Some(Event::Html(
241                         format!(
242                             "<div class=\"example-wrap\">\
243                                  <pre class=\"language-{}\"><code>{}</code></pre>\
244                              </div>",
245                             lang,
246                             Escape(&text),
247                         )
248                         .into(),
249                     ));
250                 }
251                 parse_result
252             }
253             CodeBlockKind::Indented => Default::default(),
254         };
255
256         compile_fail = parse_result.compile_fail;
257         should_panic = parse_result.should_panic;
258         ignore = parse_result.ignore;
259         edition = parse_result.edition;
260
261         let explicit_edition = edition.is_some();
262         let edition = edition.unwrap_or(self.edition);
263
264         let playground_button = self.playground.as_ref().and_then(|playground| {
265             let krate = &playground.crate_name;
266             let url = &playground.url;
267             if url.is_empty() {
268                 return None;
269             }
270             let test = origtext
271                 .lines()
272                 .map(|l| map_line(l).for_code())
273                 .collect::<Vec<Cow<'_, str>>>()
274                 .join("\n");
275             let krate = krate.as_ref().map(|s| &**s);
276             let (test, _, _) =
277                 doctest::make_test(&test, krate, false, &Default::default(), edition, None);
278             let channel = if test.contains("#![feature(") { "&amp;version=nightly" } else { "" };
279
280             let edition_string = format!("&amp;edition={}", edition);
281
282             // These characters don't need to be escaped in a URI.
283             // FIXME: use a library function for percent encoding.
284             fn dont_escape(c: u8) -> bool {
285                 (b'a' <= c && c <= b'z')
286                     || (b'A' <= c && c <= b'Z')
287                     || (b'0' <= c && c <= b'9')
288                     || c == b'-'
289                     || c == b'_'
290                     || c == b'.'
291                     || c == b'~'
292                     || c == b'!'
293                     || c == b'\''
294                     || c == b'('
295                     || c == b')'
296                     || c == b'*'
297             }
298             let mut test_escaped = String::new();
299             for b in test.bytes() {
300                 if dont_escape(b) {
301                     test_escaped.push(char::from(b));
302                 } else {
303                     write!(test_escaped, "%{:02X}", b).unwrap();
304                 }
305             }
306             Some(format!(
307                 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
308                 url, test_escaped, channel, edition_string
309             ))
310         });
311
312         let tooltip = if ignore != Ignore::None {
313             Some((None, "ignore"))
314         } else if compile_fail {
315             Some((None, "compile_fail"))
316         } else if should_panic {
317             Some((None, "should_panic"))
318         } else if explicit_edition {
319             Some((Some(edition), "edition"))
320         } else {
321             None
322         };
323
324         // insert newline to clearly separate it from the
325         // previous block so we can shorten the html output
326         let mut s = Buffer::new();
327         s.push_str("\n");
328         highlight::render_with_highlighting(
329             &text,
330             &mut s,
331             Some(&format!(
332                 "rust-example-rendered{}",
333                 if let Some((_, class)) = tooltip { format!(" {}", class) } else { String::new() }
334             )),
335             playground_button.as_deref(),
336             tooltip,
337             edition,
338             None,
339             None,
340         );
341         Some(Event::Html(s.into_inner().into()))
342     }
343 }
344
345 /// Make headings links with anchor IDs and build up TOC.
346 struct LinkReplacer<'a, I: Iterator<Item = Event<'a>>> {
347     inner: I,
348     links: &'a [RenderedLink],
349     shortcut_link: Option<&'a RenderedLink>,
350 }
351
352 impl<'a, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, I> {
353     fn new(iter: I, links: &'a [RenderedLink]) -> Self {
354         LinkReplacer { inner: iter, links, shortcut_link: None }
355     }
356 }
357
358 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
359     type Item = Event<'a>;
360
361     fn next(&mut self) -> Option<Self::Item> {
362         let mut event = self.inner.next();
363
364         // Replace intra-doc links and remove disambiguators from shortcut links (`[fn@f]`).
365         match &mut event {
366             // This is a shortcut link that was resolved by the broken_link_callback: `[fn@f]`
367             // Remove any disambiguator.
368             Some(Event::Start(Tag::Link(
369                 // [fn@f] or [fn@f][]
370                 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
371                 dest,
372                 title,
373             ))) => {
374                 debug!("saw start of shortcut link to {} with title {}", dest, title);
375                 // If this is a shortcut link, it was resolved by the broken_link_callback.
376                 // So the URL will already be updated properly.
377                 let link = self.links.iter().find(|&link| *link.href == **dest);
378                 // Since this is an external iterator, we can't replace the inner text just yet.
379                 // Store that we saw a link so we know to replace it later.
380                 if let Some(link) = link {
381                     trace!("it matched");
382                     assert!(self.shortcut_link.is_none(), "shortcut links cannot be nested");
383                     self.shortcut_link = Some(link);
384                 }
385             }
386             // Now that we're done with the shortcut link, don't replace any more text.
387             Some(Event::End(Tag::Link(
388                 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
389                 dest,
390                 _,
391             ))) => {
392                 debug!("saw end of shortcut link to {}", dest);
393                 if self.links.iter().any(|link| *link.href == **dest) {
394                     assert!(self.shortcut_link.is_some(), "saw closing link without opening tag");
395                     self.shortcut_link = None;
396                 }
397             }
398             // Handle backticks in inline code blocks, but only if we're in the middle of a shortcut link.
399             // [`fn@f`]
400             Some(Event::Code(text)) => {
401                 trace!("saw code {}", text);
402                 if let Some(link) = self.shortcut_link {
403                     trace!("original text was {}", link.original_text);
404                     // NOTE: this only replaces if the code block is the *entire* text.
405                     // If only part of the link has code highlighting, the disambiguator will not be removed.
406                     // e.g. [fn@`f`]
407                     // This is a limitation from `collect_intra_doc_links`: it passes a full link,
408                     // and does not distinguish at all between code blocks.
409                     // So we could never be sure we weren't replacing too much:
410                     // [fn@my_`f`unc] is treated the same as [my_func()] in that pass.
411                     //
412                     // NOTE: &[1..len() - 1] is to strip the backticks
413                     if **text == link.original_text[1..link.original_text.len() - 1] {
414                         debug!("replacing {} with {}", text, link.new_text);
415                         *text = CowStr::Borrowed(&link.new_text);
416                     }
417                 }
418             }
419             // Replace plain text in links, but only in the middle of a shortcut link.
420             // [fn@f]
421             Some(Event::Text(text)) => {
422                 trace!("saw text {}", text);
423                 if let Some(link) = self.shortcut_link {
424                     trace!("original text was {}", link.original_text);
425                     // NOTE: same limitations as `Event::Code`
426                     if **text == *link.original_text {
427                         debug!("replacing {} with {}", text, link.new_text);
428                         *text = CowStr::Borrowed(&link.new_text);
429                     }
430                 }
431             }
432             // If this is a link, but not a shortcut link,
433             // replace the URL, since the broken_link_callback was not called.
434             Some(Event::Start(Tag::Link(_, dest, _))) => {
435                 if let Some(link) = self.links.iter().find(|&link| *link.original_text == **dest) {
436                     *dest = CowStr::Borrowed(link.href.as_ref());
437                 }
438             }
439             // Anything else couldn't have been a valid Rust path, so no need to replace the text.
440             _ => {}
441         }
442
443         // Yield the modified event
444         event
445     }
446 }
447
448 /// Wrap HTML tables into `<div>` to prevent having the doc blocks width being too big.
449 struct TableWrapper<'a, I: Iterator<Item = Event<'a>>> {
450     inner: I,
451     stored_events: VecDeque<Event<'a>>,
452 }
453
454 impl<'a, I: Iterator<Item = Event<'a>>> TableWrapper<'a, I> {
455     fn new(iter: I) -> Self {
456         Self { inner: iter, stored_events: VecDeque::new() }
457     }
458 }
459
460 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for TableWrapper<'a, I> {
461     type Item = Event<'a>;
462
463     fn next(&mut self) -> Option<Self::Item> {
464         if let Some(first) = self.stored_events.pop_front() {
465             return Some(first);
466         }
467
468         let event = self.inner.next()?;
469
470         Some(match event {
471             Event::Start(Tag::Table(t)) => {
472                 self.stored_events.push_back(Event::Start(Tag::Table(t)));
473                 Event::Html(CowStr::Borrowed("<div>"))
474             }
475             Event::End(Tag::Table(t)) => {
476                 self.stored_events.push_back(Event::Html(CowStr::Borrowed("</div>")));
477                 Event::End(Tag::Table(t))
478             }
479             e => e,
480         })
481     }
482 }
483
484 type SpannedEvent<'a> = (Event<'a>, Range<usize>);
485
486 /// Make headings links with anchor IDs and build up TOC.
487 struct HeadingLinks<'a, 'b, 'ids, I> {
488     inner: I,
489     toc: Option<&'b mut TocBuilder>,
490     buf: VecDeque<SpannedEvent<'a>>,
491     id_map: &'ids mut IdMap,
492 }
493
494 impl<'a, 'b, 'ids, I> HeadingLinks<'a, 'b, 'ids, I> {
495     fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
496         HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids }
497     }
498 }
499
500 impl<'a, 'b, 'ids, I: Iterator<Item = SpannedEvent<'a>>> Iterator
501     for HeadingLinks<'a, 'b, 'ids, I>
502 {
503     type Item = SpannedEvent<'a>;
504
505     fn next(&mut self) -> Option<Self::Item> {
506         if let Some(e) = self.buf.pop_front() {
507             return Some(e);
508         }
509
510         let event = self.inner.next();
511         if let Some((Event::Start(Tag::Heading(level)), _)) = event {
512             let mut id = String::new();
513             for event in &mut self.inner {
514                 match &event.0 {
515                     Event::End(Tag::Heading(..)) => break,
516                     Event::Start(Tag::Link(_, _, _)) | Event::End(Tag::Link(..)) => {}
517                     Event::Text(text) | Event::Code(text) => {
518                         id.extend(text.chars().filter_map(slugify));
519                         self.buf.push_back(event);
520                     }
521                     _ => self.buf.push_back(event),
522                 }
523             }
524             let id = self.id_map.derive(id);
525
526             if let Some(ref mut builder) = self.toc {
527                 let mut html_header = String::new();
528                 html::push_html(&mut html_header, self.buf.iter().map(|(ev, _)| ev.clone()));
529                 let sec = builder.push(level as u32, html_header, id.clone());
530                 self.buf.push_front((Event::Html(format!("{} ", sec).into()), 0..0));
531             }
532
533             self.buf.push_back((Event::Html(format!("</a></h{}>", level).into()), 0..0));
534
535             let start_tags = format!(
536                 "<h{level} id=\"{id}\" class=\"section-header\">\
537                     <a href=\"#{id}\">",
538                 id = id,
539                 level = level
540             );
541             return Some((Event::Html(start_tags.into()), 0..0));
542         }
543         event
544     }
545 }
546
547 /// Extracts just the first paragraph.
548 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
549     inner: I,
550     started: bool,
551     depth: u32,
552 }
553
554 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
555     fn new(iter: I) -> Self {
556         SummaryLine { inner: iter, started: false, depth: 0 }
557     }
558 }
559
560 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
561     matches!(
562         t,
563         Tag::Paragraph | Tag::Item | Tag::Emphasis | Tag::Strong | Tag::Link(..) | Tag::BlockQuote
564     )
565 }
566
567 fn is_forbidden_tag(t: &Tag<'_>) -> bool {
568     matches!(t, Tag::CodeBlock(_) | Tag::Table(_) | Tag::TableHead | Tag::TableRow | Tag::TableCell)
569 }
570
571 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
572     type Item = Event<'a>;
573
574     fn next(&mut self) -> Option<Self::Item> {
575         if self.started && self.depth == 0 {
576             return None;
577         }
578         if !self.started {
579             self.started = true;
580         }
581         if let Some(event) = self.inner.next() {
582             let mut is_start = true;
583             let is_allowed_tag = match event {
584                 Event::Start(ref c) => {
585                     if is_forbidden_tag(c) {
586                         return None;
587                     }
588                     self.depth += 1;
589                     check_if_allowed_tag(c)
590                 }
591                 Event::End(ref c) => {
592                     if is_forbidden_tag(c) {
593                         return None;
594                     }
595                     self.depth -= 1;
596                     is_start = false;
597                     check_if_allowed_tag(c)
598                 }
599                 _ => true,
600             };
601             return if !is_allowed_tag {
602                 if is_start {
603                     Some(Event::Start(Tag::Paragraph))
604                 } else {
605                     Some(Event::End(Tag::Paragraph))
606                 }
607             } else {
608                 Some(event)
609             };
610         }
611         None
612     }
613 }
614
615 /// Moves all footnote definitions to the end and add back links to the
616 /// references.
617 struct Footnotes<'a, I> {
618     inner: I,
619     footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
620 }
621
622 impl<'a, I> Footnotes<'a, I> {
623     fn new(iter: I) -> Self {
624         Footnotes { inner: iter, footnotes: FxHashMap::default() }
625     }
626
627     fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
628         let new_id = self.footnotes.keys().count() + 1;
629         let key = key.to_owned();
630         self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
631     }
632 }
633
634 impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for Footnotes<'a, I> {
635     type Item = SpannedEvent<'a>;
636
637     fn next(&mut self) -> Option<Self::Item> {
638         loop {
639             match self.inner.next() {
640                 Some((Event::FootnoteReference(ref reference), range)) => {
641                     let entry = self.get_entry(&reference);
642                     let reference = format!(
643                         "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}</a></sup>",
644                         (*entry).1
645                     );
646                     return Some((Event::Html(reference.into()), range));
647                 }
648                 Some((Event::Start(Tag::FootnoteDefinition(def)), _)) => {
649                     let mut content = Vec::new();
650                     for (event, _) in &mut self.inner {
651                         if let Event::End(Tag::FootnoteDefinition(..)) = event {
652                             break;
653                         }
654                         content.push(event);
655                     }
656                     let entry = self.get_entry(&def);
657                     (*entry).0 = content;
658                 }
659                 Some(e) => return Some(e),
660                 None => {
661                     if !self.footnotes.is_empty() {
662                         let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
663                         v.sort_by(|a, b| a.1.cmp(&b.1));
664                         let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
665                         for (mut content, id) in v {
666                             write!(ret, "<li id=\"fn{}\">", id).unwrap();
667                             let mut is_paragraph = false;
668                             if let Some(&Event::End(Tag::Paragraph)) = content.last() {
669                                 content.pop();
670                                 is_paragraph = true;
671                             }
672                             html::push_html(&mut ret, content.into_iter());
673                             write!(ret, "&nbsp;<a href=\"#fnref{}\">↩</a>", id).unwrap();
674                             if is_paragraph {
675                                 ret.push_str("</p>");
676                             }
677                             ret.push_str("</li>");
678                         }
679                         ret.push_str("</ol></div>");
680                         return Some((Event::Html(ret.into()), 0..0));
681                     } else {
682                         return None;
683                     }
684                 }
685             }
686         }
687     }
688 }
689
690 crate fn find_testable_code<T: doctest::Tester>(
691     doc: &str,
692     tests: &mut T,
693     error_codes: ErrorCodes,
694     enable_per_target_ignores: bool,
695     extra_info: Option<&ExtraInfo<'_>>,
696 ) {
697     let mut parser = Parser::new(doc).into_offset_iter();
698     let mut prev_offset = 0;
699     let mut nb_lines = 0;
700     let mut register_header = None;
701     while let Some((event, offset)) = parser.next() {
702         match event {
703             Event::Start(Tag::CodeBlock(kind)) => {
704                 let block_info = match kind {
705                     CodeBlockKind::Fenced(ref lang) => {
706                         if lang.is_empty() {
707                             Default::default()
708                         } else {
709                             LangString::parse(
710                                 lang,
711                                 error_codes,
712                                 enable_per_target_ignores,
713                                 extra_info,
714                             )
715                         }
716                     }
717                     CodeBlockKind::Indented => Default::default(),
718                 };
719                 if !block_info.rust {
720                     continue;
721                 }
722
723                 let mut test_s = String::new();
724
725                 while let Some((Event::Text(s), _)) = parser.next() {
726                     test_s.push_str(&s);
727                 }
728                 let text = test_s
729                     .lines()
730                     .map(|l| map_line(l).for_code())
731                     .collect::<Vec<Cow<'_, str>>>()
732                     .join("\n");
733
734                 nb_lines += doc[prev_offset..offset.start].lines().count();
735                 // If there are characters between the preceding line ending and
736                 // this code block, `str::lines` will return an additional line,
737                 // which we subtract here.
738                 if nb_lines != 0 && !&doc[prev_offset..offset.start].ends_with("\n") {
739                     nb_lines -= 1;
740                 }
741                 let line = tests.get_line() + nb_lines + 1;
742                 tests.add_test(text, block_info, line);
743                 prev_offset = offset.start;
744             }
745             Event::Start(Tag::Heading(level)) => {
746                 register_header = Some(level as u32);
747             }
748             Event::Text(ref s) if register_header.is_some() => {
749                 let level = register_header.unwrap();
750                 if s.is_empty() {
751                     tests.register_header("", level);
752                 } else {
753                     tests.register_header(s, level);
754                 }
755                 register_header = None;
756             }
757             _ => {}
758         }
759     }
760 }
761
762 crate struct ExtraInfo<'tcx> {
763     id: ExtraInfoId,
764     sp: Span,
765     tcx: TyCtxt<'tcx>,
766 }
767
768 enum ExtraInfoId {
769     Hir(HirId),
770     Def(DefId),
771 }
772
773 impl<'tcx> ExtraInfo<'tcx> {
774     crate fn new(tcx: TyCtxt<'tcx>, hir_id: HirId, sp: Span) -> ExtraInfo<'tcx> {
775         ExtraInfo { id: ExtraInfoId::Hir(hir_id), sp, tcx }
776     }
777
778     crate fn new_did(tcx: TyCtxt<'tcx>, did: DefId, sp: Span) -> ExtraInfo<'tcx> {
779         ExtraInfo { id: ExtraInfoId::Def(did), sp, tcx }
780     }
781
782     fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) {
783         let hir_id = match self.id {
784             ExtraInfoId::Hir(hir_id) => hir_id,
785             ExtraInfoId::Def(item_did) => {
786                 match item_did.as_local() {
787                     Some(item_did) => self.tcx.hir().local_def_id_to_hir_id(item_did),
788                     None => {
789                         // If non-local, no need to check anything.
790                         return;
791                     }
792                 }
793             }
794         };
795         self.tcx.struct_span_lint_hir(
796             crate::lint::INVALID_CODEBLOCK_ATTRIBUTES,
797             hir_id,
798             self.sp,
799             |lint| {
800                 let mut diag = lint.build(msg);
801                 diag.help(help);
802                 diag.emit();
803             },
804         );
805     }
806 }
807
808 #[derive(Eq, PartialEq, Clone, Debug)]
809 crate struct LangString {
810     original: String,
811     crate should_panic: bool,
812     crate no_run: bool,
813     crate ignore: Ignore,
814     crate rust: bool,
815     crate test_harness: bool,
816     crate compile_fail: bool,
817     crate error_codes: Vec<String>,
818     crate allow_fail: bool,
819     crate edition: Option<Edition>,
820 }
821
822 #[derive(Eq, PartialEq, Clone, Debug)]
823 crate enum Ignore {
824     All,
825     None,
826     Some(Vec<String>),
827 }
828
829 impl Default for LangString {
830     fn default() -> Self {
831         Self {
832             original: String::new(),
833             should_panic: false,
834             no_run: false,
835             ignore: Ignore::None,
836             rust: true,
837             test_harness: false,
838             compile_fail: false,
839             error_codes: Vec::new(),
840             allow_fail: false,
841             edition: None,
842         }
843     }
844 }
845
846 impl LangString {
847     fn parse_without_check(
848         string: &str,
849         allow_error_code_check: ErrorCodes,
850         enable_per_target_ignores: bool,
851     ) -> LangString {
852         Self::parse(string, allow_error_code_check, enable_per_target_ignores, None)
853     }
854
855     fn tokens(string: &str) -> impl Iterator<Item = &str> {
856         // Pandoc, which Rust once used for generating documentation,
857         // expects lang strings to be surrounded by `{}` and for each token
858         // to be proceeded by a `.`. Since some of these lang strings are still
859         // loose in the wild, we strip a pair of surrounding `{}` from the lang
860         // string and a leading `.` from each token.
861
862         let string = string.trim();
863
864         let first = string.chars().next();
865         let last = string.chars().last();
866
867         let string = if first == Some('{') && last == Some('}') {
868             &string[1..string.len() - 1]
869         } else {
870             string
871         };
872
873         string
874             .split(|c| c == ',' || c == ' ' || c == '\t')
875             .map(str::trim)
876             .map(|token| if token.chars().next() == Some('.') { &token[1..] } else { token })
877             .filter(|token| !token.is_empty())
878     }
879
880     fn parse(
881         string: &str,
882         allow_error_code_check: ErrorCodes,
883         enable_per_target_ignores: bool,
884         extra: Option<&ExtraInfo<'_>>,
885     ) -> LangString {
886         let allow_error_code_check = allow_error_code_check.as_bool();
887         let mut seen_rust_tags = false;
888         let mut seen_other_tags = false;
889         let mut data = LangString::default();
890         let mut ignores = vec![];
891
892         data.original = string.to_owned();
893
894         let tokens = Self::tokens(string).collect::<Vec<&str>>();
895
896         for token in tokens {
897             match token {
898                 "should_panic" => {
899                     data.should_panic = true;
900                     seen_rust_tags = !seen_other_tags;
901                 }
902                 "no_run" => {
903                     data.no_run = true;
904                     seen_rust_tags = !seen_other_tags;
905                 }
906                 "ignore" => {
907                     data.ignore = Ignore::All;
908                     seen_rust_tags = !seen_other_tags;
909                 }
910                 x if x.starts_with("ignore-") => {
911                     if enable_per_target_ignores {
912                         ignores.push(x.trim_start_matches("ignore-").to_owned());
913                         seen_rust_tags = !seen_other_tags;
914                     }
915                 }
916                 "allow_fail" => {
917                     data.allow_fail = true;
918                     seen_rust_tags = !seen_other_tags;
919                 }
920                 "rust" => {
921                     data.rust = true;
922                     seen_rust_tags = true;
923                 }
924                 "test_harness" => {
925                     data.test_harness = true;
926                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
927                 }
928                 "compile_fail" => {
929                     data.compile_fail = true;
930                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
931                     data.no_run = true;
932                 }
933                 x if x.starts_with("edition") => {
934                     data.edition = x[7..].parse::<Edition>().ok();
935                 }
936                 x if allow_error_code_check && x.starts_with('E') && x.len() == 5 => {
937                     if x[1..].parse::<u32>().is_ok() {
938                         data.error_codes.push(x.to_owned());
939                         seen_rust_tags = !seen_other_tags || seen_rust_tags;
940                     } else {
941                         seen_other_tags = true;
942                     }
943                 }
944                 x if extra.is_some() => {
945                     let s = x.to_lowercase();
946                     match if s == "compile-fail" || s == "compile_fail" || s == "compilefail" {
947                         Some((
948                             "compile_fail",
949                             "the code block will either not be tested if not marked as a rust one \
950                              or won't fail if it compiles successfully",
951                         ))
952                     } else if s == "should-panic" || s == "should_panic" || s == "shouldpanic" {
953                         Some((
954                             "should_panic",
955                             "the code block will either not be tested if not marked as a rust one \
956                              or won't fail if it doesn't panic when running",
957                         ))
958                     } else if s == "no-run" || s == "no_run" || s == "norun" {
959                         Some((
960                             "no_run",
961                             "the code block will either not be tested if not marked as a rust one \
962                              or will be run (which you might not want)",
963                         ))
964                     } else if s == "allow-fail" || s == "allow_fail" || s == "allowfail" {
965                         Some((
966                             "allow_fail",
967                             "the code block will either not be tested if not marked as a rust one \
968                              or will be run (which you might not want)",
969                         ))
970                     } else if s == "test-harness" || s == "test_harness" || s == "testharness" {
971                         Some((
972                             "test_harness",
973                             "the code block will either not be tested if not marked as a rust one \
974                              or the code will be wrapped inside a main function",
975                         ))
976                     } else {
977                         None
978                     } {
979                         Some((flag, help)) => {
980                             if let Some(ref extra) = extra {
981                                 extra.error_invalid_codeblock_attr(
982                                     &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag),
983                                     help,
984                                 );
985                             }
986                         }
987                         None => {}
988                     }
989                     seen_other_tags = true;
990                 }
991                 _ => seen_other_tags = true,
992             }
993         }
994
995         // ignore-foo overrides ignore
996         if !ignores.is_empty() {
997             data.ignore = Ignore::Some(ignores);
998         }
999
1000         data.rust &= !seen_other_tags || seen_rust_tags;
1001
1002         data
1003     }
1004 }
1005
1006 impl Markdown<'_> {
1007     pub fn into_string(self) -> String {
1008         let Markdown(md, links, mut ids, codes, edition, playground) = self;
1009
1010         // This is actually common enough to special-case
1011         if md.is_empty() {
1012             return String::new();
1013         }
1014         let mut replacer = |broken_link: BrokenLink<'_>| {
1015             if let Some(link) =
1016                 links.iter().find(|link| &*link.original_text == broken_link.reference)
1017             {
1018                 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1019             } else {
1020                 None
1021             }
1022         };
1023
1024         let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(&mut replacer));
1025         let p = p.into_offset_iter();
1026
1027         let mut s = String::with_capacity(md.len() * 3 / 2);
1028
1029         let p = HeadingLinks::new(p, None, &mut ids);
1030         let p = Footnotes::new(p);
1031         let p = LinkReplacer::new(p.map(|(ev, _)| ev), links);
1032         let p = TableWrapper::new(p);
1033         let p = CodeBlocks::new(p, codes, edition, playground);
1034         html::push_html(&mut s, p);
1035
1036         s
1037     }
1038 }
1039
1040 impl MarkdownWithToc<'_> {
1041     crate fn into_string(self) -> String {
1042         let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
1043
1044         let p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
1045
1046         let mut s = String::with_capacity(md.len() * 3 / 2);
1047
1048         let mut toc = TocBuilder::new();
1049
1050         {
1051             let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
1052             let p = Footnotes::new(p);
1053             let p = TableWrapper::new(p.map(|(ev, _)| ev));
1054             let p = CodeBlocks::new(p, codes, edition, playground);
1055             html::push_html(&mut s, p);
1056         }
1057
1058         format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
1059     }
1060 }
1061
1062 impl MarkdownHtml<'_> {
1063     crate fn into_string(self) -> String {
1064         let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
1065
1066         // This is actually common enough to special-case
1067         if md.is_empty() {
1068             return String::new();
1069         }
1070         let p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
1071
1072         // Treat inline HTML as plain text.
1073         let p = p.map(|event| match event.0 {
1074             Event::Html(text) => (Event::Text(text), event.1),
1075             _ => event,
1076         });
1077
1078         let mut s = String::with_capacity(md.len() * 3 / 2);
1079
1080         let p = HeadingLinks::new(p, None, &mut ids);
1081         let p = Footnotes::new(p);
1082         let p = TableWrapper::new(p.map(|(ev, _)| ev));
1083         let p = CodeBlocks::new(p, codes, edition, playground);
1084         html::push_html(&mut s, p);
1085
1086         s
1087     }
1088 }
1089
1090 impl MarkdownSummaryLine<'_> {
1091     crate fn into_string(self) -> String {
1092         let MarkdownSummaryLine(md, links) = self;
1093         // This is actually common enough to special-case
1094         if md.is_empty() {
1095             return String::new();
1096         }
1097
1098         let mut replacer = |broken_link: BrokenLink<'_>| {
1099             if let Some(link) =
1100                 links.iter().find(|link| &*link.original_text == broken_link.reference)
1101             {
1102                 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1103             } else {
1104                 None
1105             }
1106         };
1107
1108         let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1109
1110         let mut s = String::new();
1111
1112         html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
1113
1114         s
1115     }
1116 }
1117
1118 /// Renders a subset of Markdown in the first paragraph of the provided Markdown.
1119 ///
1120 /// - *Italics*, **bold**, and `inline code` styles **are** rendered.
1121 /// - Headings and links are stripped (though the text *is* rendered).
1122 /// - HTML, code blocks, and everything else are ignored.
1123 ///
1124 /// Returns a tuple of the rendered HTML string and whether the output was shortened
1125 /// due to the provided `length_limit`.
1126 fn markdown_summary_with_limit(
1127     md: &str,
1128     link_names: &[RenderedLink],
1129     length_limit: usize,
1130 ) -> (String, bool) {
1131     if md.is_empty() {
1132         return (String::new(), false);
1133     }
1134
1135     let mut replacer = |broken_link: BrokenLink<'_>| {
1136         if let Some(link) =
1137             link_names.iter().find(|link| &*link.original_text == broken_link.reference)
1138         {
1139             Some((link.href.as_str().into(), link.new_text.as_str().into()))
1140         } else {
1141             None
1142         }
1143     };
1144
1145     let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1146     let mut p = LinkReplacer::new(p, link_names);
1147
1148     let mut buf = HtmlWithLimit::new(length_limit);
1149     let mut stopped_early = false;
1150     p.try_for_each(|event| {
1151         match &event {
1152             Event::Text(text) => {
1153                 let r =
1154                     text.split_inclusive(char::is_whitespace).try_for_each(|word| buf.push(word));
1155                 if r.is_break() {
1156                     stopped_early = true;
1157                 }
1158                 return r;
1159             }
1160             Event::Code(code) => {
1161                 buf.open_tag("code");
1162                 let r = buf.push(code);
1163                 if r.is_break() {
1164                     stopped_early = true;
1165                 } else {
1166                     buf.close_tag();
1167                 }
1168                 return r;
1169             }
1170             Event::Start(tag) => match tag {
1171                 Tag::Emphasis => buf.open_tag("em"),
1172                 Tag::Strong => buf.open_tag("strong"),
1173                 Tag::CodeBlock(..) => return ControlFlow::BREAK,
1174                 _ => {}
1175             },
1176             Event::End(tag) => match tag {
1177                 Tag::Emphasis | Tag::Strong => buf.close_tag(),
1178                 Tag::Paragraph | Tag::Heading(..) => return ControlFlow::BREAK,
1179                 _ => {}
1180             },
1181             Event::HardBreak | Event::SoftBreak => buf.push(" ")?,
1182             _ => {}
1183         };
1184         ControlFlow::CONTINUE
1185     });
1186
1187     (buf.finish(), stopped_early)
1188 }
1189
1190 /// Renders a shortened first paragraph of the given Markdown as a subset of Markdown,
1191 /// making it suitable for contexts like the search index.
1192 ///
1193 /// Will shorten to 59 or 60 characters, including an ellipsis (…) if it was shortened.
1194 ///
1195 /// See [`markdown_summary_with_limit`] for details about what is rendered and what is not.
1196 crate fn short_markdown_summary(markdown: &str, link_names: &[RenderedLink]) -> String {
1197     let (mut s, was_shortened) = markdown_summary_with_limit(markdown, link_names, 59);
1198
1199     if was_shortened {
1200         s.push('…');
1201     }
1202
1203     s
1204 }
1205
1206 /// Renders the first paragraph of the provided markdown as plain text.
1207 /// Useful for alt-text.
1208 ///
1209 /// - Headings, links, and formatting are stripped.
1210 /// - Inline code is rendered as-is, surrounded by backticks.
1211 /// - HTML and code blocks are ignored.
1212 crate fn plain_text_summary(md: &str) -> String {
1213     if md.is_empty() {
1214         return String::new();
1215     }
1216
1217     let mut s = String::with_capacity(md.len() * 3 / 2);
1218
1219     for event in Parser::new_ext(md, summary_opts()) {
1220         match &event {
1221             Event::Text(text) => s.push_str(text),
1222             Event::Code(code) => {
1223                 s.push('`');
1224                 s.push_str(code);
1225                 s.push('`');
1226             }
1227             Event::HardBreak | Event::SoftBreak => s.push(' '),
1228             Event::Start(Tag::CodeBlock(..)) => break,
1229             Event::End(Tag::Paragraph) => break,
1230             Event::End(Tag::Heading(..)) => break,
1231             _ => (),
1232         }
1233     }
1234
1235     s
1236 }
1237
1238 #[derive(Debug)]
1239 crate struct MarkdownLink {
1240     pub kind: LinkType,
1241     pub link: String,
1242     pub range: Range<usize>,
1243 }
1244
1245 crate fn markdown_links(md: &str) -> Vec<MarkdownLink> {
1246     if md.is_empty() {
1247         return vec![];
1248     }
1249
1250     let links = RefCell::new(vec![]);
1251
1252     // FIXME: remove this function once pulldown_cmark can provide spans for link definitions.
1253     let locate = |s: &str, fallback: Range<usize>| unsafe {
1254         let s_start = s.as_ptr();
1255         let s_end = s_start.add(s.len());
1256         let md_start = md.as_ptr();
1257         let md_end = md_start.add(md.len());
1258         if md_start <= s_start && s_end <= md_end {
1259             let start = s_start.offset_from(md_start) as usize;
1260             let end = s_end.offset_from(md_start) as usize;
1261             start..end
1262         } else {
1263             fallback
1264         }
1265     };
1266
1267     let span_for_link = |link: &CowStr<'_>, span: Range<usize>| {
1268         // For diagnostics, we want to underline the link's definition but `span` will point at
1269         // where the link is used. This is a problem for reference-style links, where the definition
1270         // is separate from the usage.
1271         match link {
1272             // `Borrowed` variant means the string (the link's destination) may come directly from
1273             // the markdown text and we can locate the original link destination.
1274             // NOTE: LinkReplacer also provides `Borrowed` but possibly from other sources,
1275             // so `locate()` can fall back to use `span`.
1276             CowStr::Borrowed(s) => locate(s, span),
1277
1278             // For anything else, we can only use the provided range.
1279             CowStr::Boxed(_) | CowStr::Inlined(_) => span,
1280         }
1281     };
1282
1283     let mut push = |link: BrokenLink<'_>| {
1284         let span = span_for_link(&CowStr::Borrowed(link.reference), link.span);
1285         links.borrow_mut().push(MarkdownLink {
1286             kind: LinkType::ShortcutUnknown,
1287             link: link.reference.to_owned(),
1288             range: span,
1289         });
1290         None
1291     };
1292     let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(&mut push))
1293         .into_offset_iter();
1294
1295     // There's no need to thread an IdMap through to here because
1296     // the IDs generated aren't going to be emitted anywhere.
1297     let mut ids = IdMap::new();
1298     let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
1299
1300     for ev in iter {
1301         if let Event::Start(Tag::Link(kind, dest, _)) = ev.0 {
1302             debug!("found link: {}", dest);
1303             let span = span_for_link(&dest, ev.1);
1304             links.borrow_mut().push(MarkdownLink { kind, link: dest.into_string(), range: span });
1305         }
1306     }
1307
1308     links.into_inner()
1309 }
1310
1311 #[derive(Debug)]
1312 crate struct RustCodeBlock {
1313     /// The range in the markdown that the code block occupies. Note that this includes the fences
1314     /// for fenced code blocks.
1315     crate range: Range<usize>,
1316     /// The range in the markdown that the code within the code block occupies.
1317     crate code: Range<usize>,
1318     crate is_fenced: bool,
1319     crate syntax: Option<String>,
1320     crate is_ignore: bool,
1321 }
1322
1323 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1324 /// untagged (and assumed to be rust).
1325 crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_>) -> Vec<RustCodeBlock> {
1326     let mut code_blocks = vec![];
1327
1328     if md.is_empty() {
1329         return code_blocks;
1330     }
1331
1332     let mut p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
1333
1334     while let Some((event, offset)) = p.next() {
1335         if let Event::Start(Tag::CodeBlock(syntax)) = event {
1336             let (syntax, code_start, code_end, range, is_fenced, is_ignore) = match syntax {
1337                 CodeBlockKind::Fenced(syntax) => {
1338                     let syntax = syntax.as_ref();
1339                     let lang_string = if syntax.is_empty() {
1340                         Default::default()
1341                     } else {
1342                         LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info))
1343                     };
1344                     if !lang_string.rust {
1345                         continue;
1346                     }
1347                     let is_ignore = lang_string.ignore != Ignore::None;
1348                     let syntax = if syntax.is_empty() { None } else { Some(syntax.to_owned()) };
1349                     let (code_start, mut code_end) = match p.next() {
1350                         Some((Event::Text(_), offset)) => (offset.start, offset.end),
1351                         Some((_, sub_offset)) => {
1352                             let code = Range { start: sub_offset.start, end: sub_offset.start };
1353                             code_blocks.push(RustCodeBlock {
1354                                 is_fenced: true,
1355                                 range: offset,
1356                                 code,
1357                                 syntax,
1358                                 is_ignore,
1359                             });
1360                             continue;
1361                         }
1362                         None => {
1363                             let code = Range { start: offset.end, end: offset.end };
1364                             code_blocks.push(RustCodeBlock {
1365                                 is_fenced: true,
1366                                 range: offset,
1367                                 code,
1368                                 syntax,
1369                                 is_ignore,
1370                             });
1371                             continue;
1372                         }
1373                     };
1374                     while let Some((Event::Text(_), offset)) = p.next() {
1375                         code_end = offset.end;
1376                     }
1377                     (syntax, code_start, code_end, offset, true, is_ignore)
1378                 }
1379                 CodeBlockKind::Indented => {
1380                     // The ending of the offset goes too far sometime so we reduce it by one in
1381                     // these cases.
1382                     if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") {
1383                         (
1384                             None,
1385                             offset.start,
1386                             offset.end,
1387                             Range { start: offset.start, end: offset.end - 1 },
1388                             false,
1389                             false,
1390                         )
1391                     } else {
1392                         (None, offset.start, offset.end, offset, false, false)
1393                     }
1394                 }
1395             };
1396
1397             code_blocks.push(RustCodeBlock {
1398                 is_fenced,
1399                 range,
1400                 code: Range { start: code_start, end: code_end },
1401                 syntax,
1402                 is_ignore,
1403             });
1404         }
1405     }
1406
1407     code_blocks
1408 }
1409
1410 #[derive(Clone, Default, Debug)]
1411 pub struct IdMap {
1412     map: FxHashMap<String, usize>,
1413 }
1414
1415 fn init_id_map() -> FxHashMap<String, usize> {
1416     let mut map = FxHashMap::default();
1417     // This is the list of IDs used in Javascript.
1418     map.insert("help".to_owned(), 1);
1419     // This is the list of IDs used in HTML generated in Rust (including the ones
1420     // used in tera template files).
1421     map.insert("mainThemeStyle".to_owned(), 1);
1422     map.insert("themeStyle".to_owned(), 1);
1423     map.insert("theme-picker".to_owned(), 1);
1424     map.insert("theme-choices".to_owned(), 1);
1425     map.insert("settings-menu".to_owned(), 1);
1426     map.insert("help-button".to_owned(), 1);
1427     map.insert("main".to_owned(), 1);
1428     map.insert("search".to_owned(), 1);
1429     map.insert("crate-search".to_owned(), 1);
1430     map.insert("render-detail".to_owned(), 1);
1431     map.insert("toggle-all-docs".to_owned(), 1);
1432     map.insert("all-types".to_owned(), 1);
1433     map.insert("default-settings".to_owned(), 1);
1434     map.insert("rustdoc-vars".to_owned(), 1);
1435     map.insert("sidebar-vars".to_owned(), 1);
1436     map.insert("copy-path".to_owned(), 1);
1437     map.insert("TOC".to_owned(), 1);
1438     // This is the list of IDs used by rustdoc sections (but still generated by
1439     // rustdoc).
1440     map.insert("fields".to_owned(), 1);
1441     map.insert("variants".to_owned(), 1);
1442     map.insert("implementors-list".to_owned(), 1);
1443     map.insert("synthetic-implementors-list".to_owned(), 1);
1444     map.insert("foreign-impls".to_owned(), 1);
1445     map.insert("implementations".to_owned(), 1);
1446     map.insert("trait-implementations".to_owned(), 1);
1447     map.insert("synthetic-implementations".to_owned(), 1);
1448     map.insert("blanket-implementations".to_owned(), 1);
1449     map.insert("associated-types".to_owned(), 1);
1450     map.insert("associated-const".to_owned(), 1);
1451     map.insert("required-methods".to_owned(), 1);
1452     map.insert("provided-methods".to_owned(), 1);
1453     map.insert("implementors".to_owned(), 1);
1454     map.insert("synthetic-implementors".to_owned(), 1);
1455     map.insert("trait-implementations-list".to_owned(), 1);
1456     map.insert("synthetic-implementations-list".to_owned(), 1);
1457     map.insert("blanket-implementations-list".to_owned(), 1);
1458     map.insert("deref-methods".to_owned(), 1);
1459     map
1460 }
1461
1462 impl IdMap {
1463     pub fn new() -> Self {
1464         IdMap { map: init_id_map() }
1465     }
1466
1467     crate fn derive<S: AsRef<str> + ToString>(&mut self, candidate: S) -> String {
1468         let id = match self.map.get_mut(candidate.as_ref()) {
1469             None => candidate.to_string(),
1470             Some(a) => {
1471                 let id = format!("{}-{}", candidate.as_ref(), *a);
1472                 *a += 1;
1473                 id
1474             }
1475         };
1476
1477         self.map.insert(id.clone(), 1);
1478         id
1479     }
1480 }