]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/markdown.rs
Rollup merge of #88632 - camelid:md-opts, r=CraftSpider
[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 type SpannedEvent<'a> = (Event<'a>, Range<usize>);
449
450 /// Make headings links with anchor IDs and build up TOC.
451 struct HeadingLinks<'a, 'b, 'ids, I> {
452     inner: I,
453     toc: Option<&'b mut TocBuilder>,
454     buf: VecDeque<SpannedEvent<'a>>,
455     id_map: &'ids mut IdMap,
456 }
457
458 impl<'a, 'b, 'ids, I> HeadingLinks<'a, 'b, 'ids, I> {
459     fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
460         HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids }
461     }
462 }
463
464 impl<'a, 'b, 'ids, I: Iterator<Item = SpannedEvent<'a>>> Iterator
465     for HeadingLinks<'a, 'b, 'ids, I>
466 {
467     type Item = SpannedEvent<'a>;
468
469     fn next(&mut self) -> Option<Self::Item> {
470         if let Some(e) = self.buf.pop_front() {
471             return Some(e);
472         }
473
474         let event = self.inner.next();
475         if let Some((Event::Start(Tag::Heading(level)), _)) = event {
476             let mut id = String::new();
477             for event in &mut self.inner {
478                 match &event.0 {
479                     Event::End(Tag::Heading(..)) => break,
480                     Event::Start(Tag::Link(_, _, _)) | Event::End(Tag::Link(..)) => {}
481                     Event::Text(text) | Event::Code(text) => {
482                         id.extend(text.chars().filter_map(slugify));
483                         self.buf.push_back(event);
484                     }
485                     _ => self.buf.push_back(event),
486                 }
487             }
488             let id = self.id_map.derive(id);
489
490             if let Some(ref mut builder) = self.toc {
491                 let mut html_header = String::new();
492                 html::push_html(&mut html_header, self.buf.iter().map(|(ev, _)| ev.clone()));
493                 let sec = builder.push(level as u32, html_header, id.clone());
494                 self.buf.push_front((Event::Html(format!("{} ", sec).into()), 0..0));
495             }
496
497             self.buf.push_back((Event::Html(format!("</a></h{}>", level).into()), 0..0));
498
499             let start_tags = format!(
500                 "<h{level} id=\"{id}\" class=\"section-header\">\
501                     <a href=\"#{id}\">",
502                 id = id,
503                 level = level
504             );
505             return Some((Event::Html(start_tags.into()), 0..0));
506         }
507         event
508     }
509 }
510
511 /// Extracts just the first paragraph.
512 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
513     inner: I,
514     started: bool,
515     depth: u32,
516 }
517
518 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
519     fn new(iter: I) -> Self {
520         SummaryLine { inner: iter, started: false, depth: 0 }
521     }
522 }
523
524 fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
525     matches!(
526         t,
527         Tag::Paragraph | Tag::Item | Tag::Emphasis | Tag::Strong | Tag::Link(..) | Tag::BlockQuote
528     )
529 }
530
531 fn is_forbidden_tag(t: &Tag<'_>) -> bool {
532     matches!(t, Tag::CodeBlock(_) | Tag::Table(_) | Tag::TableHead | Tag::TableRow | Tag::TableCell)
533 }
534
535 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
536     type Item = Event<'a>;
537
538     fn next(&mut self) -> Option<Self::Item> {
539         if self.started && self.depth == 0 {
540             return None;
541         }
542         if !self.started {
543             self.started = true;
544         }
545         if let Some(event) = self.inner.next() {
546             let mut is_start = true;
547             let is_allowed_tag = match event {
548                 Event::Start(ref c) => {
549                     if is_forbidden_tag(c) {
550                         return None;
551                     }
552                     self.depth += 1;
553                     check_if_allowed_tag(c)
554                 }
555                 Event::End(ref c) => {
556                     if is_forbidden_tag(c) {
557                         return None;
558                     }
559                     self.depth -= 1;
560                     is_start = false;
561                     check_if_allowed_tag(c)
562                 }
563                 _ => true,
564             };
565             return if !is_allowed_tag {
566                 if is_start {
567                     Some(Event::Start(Tag::Paragraph))
568                 } else {
569                     Some(Event::End(Tag::Paragraph))
570                 }
571             } else {
572                 Some(event)
573             };
574         }
575         None
576     }
577 }
578
579 /// Moves all footnote definitions to the end and add back links to the
580 /// references.
581 struct Footnotes<'a, I> {
582     inner: I,
583     footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
584 }
585
586 impl<'a, I> Footnotes<'a, I> {
587     fn new(iter: I) -> Self {
588         Footnotes { inner: iter, footnotes: FxHashMap::default() }
589     }
590
591     fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
592         let new_id = self.footnotes.keys().count() + 1;
593         let key = key.to_owned();
594         self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
595     }
596 }
597
598 impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for Footnotes<'a, I> {
599     type Item = SpannedEvent<'a>;
600
601     fn next(&mut self) -> Option<Self::Item> {
602         loop {
603             match self.inner.next() {
604                 Some((Event::FootnoteReference(ref reference), range)) => {
605                     let entry = self.get_entry(&reference);
606                     let reference = format!(
607                         "<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}</a></sup>",
608                         (*entry).1
609                     );
610                     return Some((Event::Html(reference.into()), range));
611                 }
612                 Some((Event::Start(Tag::FootnoteDefinition(def)), _)) => {
613                     let mut content = Vec::new();
614                     for (event, _) in &mut self.inner {
615                         if let Event::End(Tag::FootnoteDefinition(..)) = event {
616                             break;
617                         }
618                         content.push(event);
619                     }
620                     let entry = self.get_entry(&def);
621                     (*entry).0 = content;
622                 }
623                 Some(e) => return Some(e),
624                 None => {
625                     if !self.footnotes.is_empty() {
626                         let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
627                         v.sort_by(|a, b| a.1.cmp(&b.1));
628                         let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
629                         for (mut content, id) in v {
630                             write!(ret, "<li id=\"fn{}\">", id).unwrap();
631                             let mut is_paragraph = false;
632                             if let Some(&Event::End(Tag::Paragraph)) = content.last() {
633                                 content.pop();
634                                 is_paragraph = true;
635                             }
636                             html::push_html(&mut ret, content.into_iter());
637                             write!(ret, "&nbsp;<a href=\"#fnref{}\">↩</a>", id).unwrap();
638                             if is_paragraph {
639                                 ret.push_str("</p>");
640                             }
641                             ret.push_str("</li>");
642                         }
643                         ret.push_str("</ol></div>");
644                         return Some((Event::Html(ret.into()), 0..0));
645                     } else {
646                         return None;
647                     }
648                 }
649             }
650         }
651     }
652 }
653
654 crate fn find_testable_code<T: doctest::Tester>(
655     doc: &str,
656     tests: &mut T,
657     error_codes: ErrorCodes,
658     enable_per_target_ignores: bool,
659     extra_info: Option<&ExtraInfo<'_>>,
660 ) {
661     let mut parser = Parser::new(doc).into_offset_iter();
662     let mut prev_offset = 0;
663     let mut nb_lines = 0;
664     let mut register_header = None;
665     while let Some((event, offset)) = parser.next() {
666         match event {
667             Event::Start(Tag::CodeBlock(kind)) => {
668                 let block_info = match kind {
669                     CodeBlockKind::Fenced(ref lang) => {
670                         if lang.is_empty() {
671                             Default::default()
672                         } else {
673                             LangString::parse(
674                                 lang,
675                                 error_codes,
676                                 enable_per_target_ignores,
677                                 extra_info,
678                             )
679                         }
680                     }
681                     CodeBlockKind::Indented => Default::default(),
682                 };
683                 if !block_info.rust {
684                     continue;
685                 }
686
687                 let mut test_s = String::new();
688
689                 while let Some((Event::Text(s), _)) = parser.next() {
690                     test_s.push_str(&s);
691                 }
692                 let text = test_s
693                     .lines()
694                     .map(|l| map_line(l).for_code())
695                     .collect::<Vec<Cow<'_, str>>>()
696                     .join("\n");
697
698                 nb_lines += doc[prev_offset..offset.start].lines().count();
699                 // If there are characters between the preceding line ending and
700                 // this code block, `str::lines` will return an additional line,
701                 // which we subtract here.
702                 if nb_lines != 0 && !&doc[prev_offset..offset.start].ends_with("\n") {
703                     nb_lines -= 1;
704                 }
705                 let line = tests.get_line() + nb_lines + 1;
706                 tests.add_test(text, block_info, line);
707                 prev_offset = offset.start;
708             }
709             Event::Start(Tag::Heading(level)) => {
710                 register_header = Some(level as u32);
711             }
712             Event::Text(ref s) if register_header.is_some() => {
713                 let level = register_header.unwrap();
714                 if s.is_empty() {
715                     tests.register_header("", level);
716                 } else {
717                     tests.register_header(s, level);
718                 }
719                 register_header = None;
720             }
721             _ => {}
722         }
723     }
724 }
725
726 crate struct ExtraInfo<'tcx> {
727     id: ExtraInfoId,
728     sp: Span,
729     tcx: TyCtxt<'tcx>,
730 }
731
732 enum ExtraInfoId {
733     Hir(HirId),
734     Def(DefId),
735 }
736
737 impl<'tcx> ExtraInfo<'tcx> {
738     crate fn new(tcx: TyCtxt<'tcx>, hir_id: HirId, sp: Span) -> ExtraInfo<'tcx> {
739         ExtraInfo { id: ExtraInfoId::Hir(hir_id), sp, tcx }
740     }
741
742     crate fn new_did(tcx: TyCtxt<'tcx>, did: DefId, sp: Span) -> ExtraInfo<'tcx> {
743         ExtraInfo { id: ExtraInfoId::Def(did), sp, tcx }
744     }
745
746     fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) {
747         let hir_id = match self.id {
748             ExtraInfoId::Hir(hir_id) => hir_id,
749             ExtraInfoId::Def(item_did) => {
750                 match item_did.as_local() {
751                     Some(item_did) => self.tcx.hir().local_def_id_to_hir_id(item_did),
752                     None => {
753                         // If non-local, no need to check anything.
754                         return;
755                     }
756                 }
757             }
758         };
759         self.tcx.struct_span_lint_hir(
760             crate::lint::INVALID_CODEBLOCK_ATTRIBUTES,
761             hir_id,
762             self.sp,
763             |lint| {
764                 let mut diag = lint.build(msg);
765                 diag.help(help);
766                 diag.emit();
767             },
768         );
769     }
770 }
771
772 #[derive(Eq, PartialEq, Clone, Debug)]
773 crate struct LangString {
774     original: String,
775     crate should_panic: bool,
776     crate no_run: bool,
777     crate ignore: Ignore,
778     crate rust: bool,
779     crate test_harness: bool,
780     crate compile_fail: bool,
781     crate error_codes: Vec<String>,
782     crate allow_fail: bool,
783     crate edition: Option<Edition>,
784 }
785
786 #[derive(Eq, PartialEq, Clone, Debug)]
787 crate enum Ignore {
788     All,
789     None,
790     Some(Vec<String>),
791 }
792
793 impl Default for LangString {
794     fn default() -> Self {
795         Self {
796             original: String::new(),
797             should_panic: false,
798             no_run: false,
799             ignore: Ignore::None,
800             rust: true,
801             test_harness: false,
802             compile_fail: false,
803             error_codes: Vec::new(),
804             allow_fail: false,
805             edition: None,
806         }
807     }
808 }
809
810 impl LangString {
811     fn parse_without_check(
812         string: &str,
813         allow_error_code_check: ErrorCodes,
814         enable_per_target_ignores: bool,
815     ) -> LangString {
816         Self::parse(string, allow_error_code_check, enable_per_target_ignores, None)
817     }
818
819     fn tokens(string: &str) -> impl Iterator<Item = &str> {
820         // Pandoc, which Rust once used for generating documentation,
821         // expects lang strings to be surrounded by `{}` and for each token
822         // to be proceeded by a `.`. Since some of these lang strings are still
823         // loose in the wild, we strip a pair of surrounding `{}` from the lang
824         // string and a leading `.` from each token.
825
826         let string = string.trim();
827
828         let first = string.chars().next();
829         let last = string.chars().last();
830
831         let string = if first == Some('{') && last == Some('}') {
832             &string[1..string.len() - 1]
833         } else {
834             string
835         };
836
837         string
838             .split(|c| c == ',' || c == ' ' || c == '\t')
839             .map(str::trim)
840             .map(|token| if token.chars().next() == Some('.') { &token[1..] } else { token })
841             .filter(|token| !token.is_empty())
842     }
843
844     fn parse(
845         string: &str,
846         allow_error_code_check: ErrorCodes,
847         enable_per_target_ignores: bool,
848         extra: Option<&ExtraInfo<'_>>,
849     ) -> LangString {
850         let allow_error_code_check = allow_error_code_check.as_bool();
851         let mut seen_rust_tags = false;
852         let mut seen_other_tags = false;
853         let mut data = LangString::default();
854         let mut ignores = vec![];
855
856         data.original = string.to_owned();
857
858         let tokens = Self::tokens(string).collect::<Vec<&str>>();
859
860         for token in tokens {
861             match token {
862                 "should_panic" => {
863                     data.should_panic = true;
864                     seen_rust_tags = !seen_other_tags;
865                 }
866                 "no_run" => {
867                     data.no_run = true;
868                     seen_rust_tags = !seen_other_tags;
869                 }
870                 "ignore" => {
871                     data.ignore = Ignore::All;
872                     seen_rust_tags = !seen_other_tags;
873                 }
874                 x if x.starts_with("ignore-") => {
875                     if enable_per_target_ignores {
876                         ignores.push(x.trim_start_matches("ignore-").to_owned());
877                         seen_rust_tags = !seen_other_tags;
878                     }
879                 }
880                 "allow_fail" => {
881                     data.allow_fail = true;
882                     seen_rust_tags = !seen_other_tags;
883                 }
884                 "rust" => {
885                     data.rust = true;
886                     seen_rust_tags = true;
887                 }
888                 "test_harness" => {
889                     data.test_harness = true;
890                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
891                 }
892                 "compile_fail" => {
893                     data.compile_fail = true;
894                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
895                     data.no_run = true;
896                 }
897                 x if x.starts_with("edition") => {
898                     data.edition = x[7..].parse::<Edition>().ok();
899                 }
900                 x if allow_error_code_check && x.starts_with('E') && x.len() == 5 => {
901                     if x[1..].parse::<u32>().is_ok() {
902                         data.error_codes.push(x.to_owned());
903                         seen_rust_tags = !seen_other_tags || seen_rust_tags;
904                     } else {
905                         seen_other_tags = true;
906                     }
907                 }
908                 x if extra.is_some() => {
909                     let s = x.to_lowercase();
910                     match if s == "compile-fail" || s == "compile_fail" || s == "compilefail" {
911                         Some((
912                             "compile_fail",
913                             "the code block will either not be tested if not marked as a rust one \
914                              or won't fail if it compiles successfully",
915                         ))
916                     } else if s == "should-panic" || s == "should_panic" || s == "shouldpanic" {
917                         Some((
918                             "should_panic",
919                             "the code block will either not be tested if not marked as a rust one \
920                              or won't fail if it doesn't panic when running",
921                         ))
922                     } else if s == "no-run" || s == "no_run" || s == "norun" {
923                         Some((
924                             "no_run",
925                             "the code block will either not be tested if not marked as a rust one \
926                              or will be run (which you might not want)",
927                         ))
928                     } else if s == "allow-fail" || s == "allow_fail" || s == "allowfail" {
929                         Some((
930                             "allow_fail",
931                             "the code block will either not be tested if not marked as a rust one \
932                              or will be run (which you might not want)",
933                         ))
934                     } else if s == "test-harness" || s == "test_harness" || s == "testharness" {
935                         Some((
936                             "test_harness",
937                             "the code block will either not be tested if not marked as a rust one \
938                              or the code will be wrapped inside a main function",
939                         ))
940                     } else {
941                         None
942                     } {
943                         Some((flag, help)) => {
944                             if let Some(ref extra) = extra {
945                                 extra.error_invalid_codeblock_attr(
946                                     &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag),
947                                     help,
948                                 );
949                             }
950                         }
951                         None => {}
952                     }
953                     seen_other_tags = true;
954                 }
955                 _ => seen_other_tags = true,
956             }
957         }
958
959         // ignore-foo overrides ignore
960         if !ignores.is_empty() {
961             data.ignore = Ignore::Some(ignores);
962         }
963
964         data.rust &= !seen_other_tags || seen_rust_tags;
965
966         data
967     }
968 }
969
970 impl Markdown<'_> {
971     pub fn into_string(self) -> String {
972         let Markdown(md, links, mut ids, codes, edition, playground) = self;
973
974         // This is actually common enough to special-case
975         if md.is_empty() {
976             return String::new();
977         }
978         let mut replacer = |broken_link: BrokenLink<'_>| {
979             if let Some(link) =
980                 links.iter().find(|link| &*link.original_text == broken_link.reference)
981             {
982                 Some((link.href.as_str().into(), link.new_text.as_str().into()))
983             } else {
984                 None
985             }
986         };
987
988         let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(&mut replacer));
989         let p = p.into_offset_iter();
990
991         let mut s = String::with_capacity(md.len() * 3 / 2);
992
993         let p = HeadingLinks::new(p, None, &mut ids);
994         let p = Footnotes::new(p);
995         let p = LinkReplacer::new(p.map(|(ev, _)| ev), links);
996         let p = CodeBlocks::new(p, codes, edition, playground);
997         html::push_html(&mut s, p);
998
999         s
1000     }
1001 }
1002
1003 impl MarkdownWithToc<'_> {
1004     crate fn into_string(self) -> String {
1005         let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
1006
1007         let p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
1008
1009         let mut s = String::with_capacity(md.len() * 3 / 2);
1010
1011         let mut toc = TocBuilder::new();
1012
1013         {
1014             let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
1015             let p = Footnotes::new(p);
1016             let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
1017             html::push_html(&mut s, p);
1018         }
1019
1020         format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
1021     }
1022 }
1023
1024 impl MarkdownHtml<'_> {
1025     crate fn into_string(self) -> String {
1026         let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
1027
1028         // This is actually common enough to special-case
1029         if md.is_empty() {
1030             return String::new();
1031         }
1032         let p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
1033
1034         // Treat inline HTML as plain text.
1035         let p = p.map(|event| match event.0 {
1036             Event::Html(text) => (Event::Text(text), event.1),
1037             _ => event,
1038         });
1039
1040         let mut s = String::with_capacity(md.len() * 3 / 2);
1041
1042         let p = HeadingLinks::new(p, None, &mut ids);
1043         let p = Footnotes::new(p);
1044         let p = CodeBlocks::new(p.map(|(ev, _)| ev), codes, edition, playground);
1045         html::push_html(&mut s, p);
1046
1047         s
1048     }
1049 }
1050
1051 impl MarkdownSummaryLine<'_> {
1052     crate fn into_string(self) -> String {
1053         let MarkdownSummaryLine(md, links) = self;
1054         // This is actually common enough to special-case
1055         if md.is_empty() {
1056             return String::new();
1057         }
1058
1059         let mut replacer = |broken_link: BrokenLink<'_>| {
1060             if let Some(link) =
1061                 links.iter().find(|link| &*link.original_text == broken_link.reference)
1062             {
1063                 Some((link.href.as_str().into(), link.new_text.as_str().into()))
1064             } else {
1065                 None
1066             }
1067         };
1068
1069         let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1070
1071         let mut s = String::new();
1072
1073         html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
1074
1075         s
1076     }
1077 }
1078
1079 /// Renders a subset of Markdown in the first paragraph of the provided Markdown.
1080 ///
1081 /// - *Italics*, **bold**, and `inline code` styles **are** rendered.
1082 /// - Headings and links are stripped (though the text *is* rendered).
1083 /// - HTML, code blocks, and everything else are ignored.
1084 ///
1085 /// Returns a tuple of the rendered HTML string and whether the output was shortened
1086 /// due to the provided `length_limit`.
1087 fn markdown_summary_with_limit(
1088     md: &str,
1089     link_names: &[RenderedLink],
1090     length_limit: usize,
1091 ) -> (String, bool) {
1092     if md.is_empty() {
1093         return (String::new(), false);
1094     }
1095
1096     let mut replacer = |broken_link: BrokenLink<'_>| {
1097         if let Some(link) =
1098             link_names.iter().find(|link| &*link.original_text == broken_link.reference)
1099         {
1100             Some((link.href.as_str().into(), link.new_text.as_str().into()))
1101         } else {
1102             None
1103         }
1104     };
1105
1106     let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1107     let mut p = LinkReplacer::new(p, link_names);
1108
1109     let mut buf = HtmlWithLimit::new(length_limit);
1110     let mut stopped_early = false;
1111     p.try_for_each(|event| {
1112         match &event {
1113             Event::Text(text) => {
1114                 let r =
1115                     text.split_inclusive(char::is_whitespace).try_for_each(|word| buf.push(word));
1116                 if r.is_break() {
1117                     stopped_early = true;
1118                 }
1119                 return r;
1120             }
1121             Event::Code(code) => {
1122                 buf.open_tag("code");
1123                 let r = buf.push(code);
1124                 if r.is_break() {
1125                     stopped_early = true;
1126                 } else {
1127                     buf.close_tag();
1128                 }
1129                 return r;
1130             }
1131             Event::Start(tag) => match tag {
1132                 Tag::Emphasis => buf.open_tag("em"),
1133                 Tag::Strong => buf.open_tag("strong"),
1134                 Tag::CodeBlock(..) => return ControlFlow::BREAK,
1135                 _ => {}
1136             },
1137             Event::End(tag) => match tag {
1138                 Tag::Emphasis | Tag::Strong => buf.close_tag(),
1139                 Tag::Paragraph | Tag::Heading(..) => return ControlFlow::BREAK,
1140                 _ => {}
1141             },
1142             Event::HardBreak | Event::SoftBreak => buf.push(" ")?,
1143             _ => {}
1144         };
1145         ControlFlow::CONTINUE
1146     });
1147
1148     (buf.finish(), stopped_early)
1149 }
1150
1151 /// Renders a shortened first paragraph of the given Markdown as a subset of Markdown,
1152 /// making it suitable for contexts like the search index.
1153 ///
1154 /// Will shorten to 59 or 60 characters, including an ellipsis (…) if it was shortened.
1155 ///
1156 /// See [`markdown_summary_with_limit`] for details about what is rendered and what is not.
1157 crate fn short_markdown_summary(markdown: &str, link_names: &[RenderedLink]) -> String {
1158     let (mut s, was_shortened) = markdown_summary_with_limit(markdown, link_names, 59);
1159
1160     if was_shortened {
1161         s.push('…');
1162     }
1163
1164     s
1165 }
1166
1167 /// Renders the first paragraph of the provided markdown as plain text.
1168 /// Useful for alt-text.
1169 ///
1170 /// - Headings, links, and formatting are stripped.
1171 /// - Inline code is rendered as-is, surrounded by backticks.
1172 /// - HTML and code blocks are ignored.
1173 crate fn plain_text_summary(md: &str) -> String {
1174     if md.is_empty() {
1175         return String::new();
1176     }
1177
1178     let mut s = String::with_capacity(md.len() * 3 / 2);
1179
1180     for event in Parser::new_ext(md, summary_opts()) {
1181         match &event {
1182             Event::Text(text) => s.push_str(text),
1183             Event::Code(code) => {
1184                 s.push('`');
1185                 s.push_str(code);
1186                 s.push('`');
1187             }
1188             Event::HardBreak | Event::SoftBreak => s.push(' '),
1189             Event::Start(Tag::CodeBlock(..)) => break,
1190             Event::End(Tag::Paragraph) => break,
1191             Event::End(Tag::Heading(..)) => break,
1192             _ => (),
1193         }
1194     }
1195
1196     s
1197 }
1198
1199 #[derive(Debug)]
1200 crate struct MarkdownLink {
1201     pub kind: LinkType,
1202     pub link: String,
1203     pub range: Range<usize>,
1204 }
1205
1206 crate fn markdown_links(md: &str) -> Vec<MarkdownLink> {
1207     if md.is_empty() {
1208         return vec![];
1209     }
1210
1211     let links = RefCell::new(vec![]);
1212
1213     // FIXME: remove this function once pulldown_cmark can provide spans for link definitions.
1214     let locate = |s: &str, fallback: Range<usize>| unsafe {
1215         let s_start = s.as_ptr();
1216         let s_end = s_start.add(s.len());
1217         let md_start = md.as_ptr();
1218         let md_end = md_start.add(md.len());
1219         if md_start <= s_start && s_end <= md_end {
1220             let start = s_start.offset_from(md_start) as usize;
1221             let end = s_end.offset_from(md_start) as usize;
1222             start..end
1223         } else {
1224             fallback
1225         }
1226     };
1227
1228     let span_for_link = |link: &CowStr<'_>, span: Range<usize>| {
1229         // For diagnostics, we want to underline the link's definition but `span` will point at
1230         // where the link is used. This is a problem for reference-style links, where the definition
1231         // is separate from the usage.
1232         match link {
1233             // `Borrowed` variant means the string (the link's destination) may come directly from
1234             // the markdown text and we can locate the original link destination.
1235             // NOTE: LinkReplacer also provides `Borrowed` but possibly from other sources,
1236             // so `locate()` can fall back to use `span`.
1237             CowStr::Borrowed(s) => locate(s, span),
1238
1239             // For anything else, we can only use the provided range.
1240             CowStr::Boxed(_) | CowStr::Inlined(_) => span,
1241         }
1242     };
1243
1244     let mut push = |link: BrokenLink<'_>| {
1245         let span = span_for_link(&CowStr::Borrowed(link.reference), link.span);
1246         links.borrow_mut().push(MarkdownLink {
1247             kind: LinkType::ShortcutUnknown,
1248             link: link.reference.to_owned(),
1249             range: span,
1250         });
1251         None
1252     };
1253     let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(&mut push))
1254         .into_offset_iter();
1255
1256     // There's no need to thread an IdMap through to here because
1257     // the IDs generated aren't going to be emitted anywhere.
1258     let mut ids = IdMap::new();
1259     let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
1260
1261     for ev in iter {
1262         if let Event::Start(Tag::Link(kind, dest, _)) = ev.0 {
1263             debug!("found link: {}", dest);
1264             let span = span_for_link(&dest, ev.1);
1265             links.borrow_mut().push(MarkdownLink { kind, link: dest.into_string(), range: span });
1266         }
1267     }
1268
1269     links.into_inner()
1270 }
1271
1272 #[derive(Debug)]
1273 crate struct RustCodeBlock {
1274     /// The range in the markdown that the code block occupies. Note that this includes the fences
1275     /// for fenced code blocks.
1276     crate range: Range<usize>,
1277     /// The range in the markdown that the code within the code block occupies.
1278     crate code: Range<usize>,
1279     crate is_fenced: bool,
1280     crate syntax: Option<String>,
1281     crate is_ignore: bool,
1282 }
1283
1284 /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
1285 /// untagged (and assumed to be rust).
1286 crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_>) -> Vec<RustCodeBlock> {
1287     let mut code_blocks = vec![];
1288
1289     if md.is_empty() {
1290         return code_blocks;
1291     }
1292
1293     let mut p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
1294
1295     while let Some((event, offset)) = p.next() {
1296         if let Event::Start(Tag::CodeBlock(syntax)) = event {
1297             let (syntax, code_start, code_end, range, is_fenced, is_ignore) = match syntax {
1298                 CodeBlockKind::Fenced(syntax) => {
1299                     let syntax = syntax.as_ref();
1300                     let lang_string = if syntax.is_empty() {
1301                         Default::default()
1302                     } else {
1303                         LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info))
1304                     };
1305                     if !lang_string.rust {
1306                         continue;
1307                     }
1308                     let is_ignore = lang_string.ignore != Ignore::None;
1309                     let syntax = if syntax.is_empty() { None } else { Some(syntax.to_owned()) };
1310                     let (code_start, mut code_end) = match p.next() {
1311                         Some((Event::Text(_), offset)) => (offset.start, offset.end),
1312                         Some((_, sub_offset)) => {
1313                             let code = Range { start: sub_offset.start, end: sub_offset.start };
1314                             code_blocks.push(RustCodeBlock {
1315                                 is_fenced: true,
1316                                 range: offset,
1317                                 code,
1318                                 syntax,
1319                                 is_ignore,
1320                             });
1321                             continue;
1322                         }
1323                         None => {
1324                             let code = Range { start: offset.end, end: offset.end };
1325                             code_blocks.push(RustCodeBlock {
1326                                 is_fenced: true,
1327                                 range: offset,
1328                                 code,
1329                                 syntax,
1330                                 is_ignore,
1331                             });
1332                             continue;
1333                         }
1334                     };
1335                     while let Some((Event::Text(_), offset)) = p.next() {
1336                         code_end = offset.end;
1337                     }
1338                     (syntax, code_start, code_end, offset, true, is_ignore)
1339                 }
1340                 CodeBlockKind::Indented => {
1341                     // The ending of the offset goes too far sometime so we reduce it by one in
1342                     // these cases.
1343                     if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") {
1344                         (
1345                             None,
1346                             offset.start,
1347                             offset.end,
1348                             Range { start: offset.start, end: offset.end - 1 },
1349                             false,
1350                             false,
1351                         )
1352                     } else {
1353                         (None, offset.start, offset.end, offset, false, false)
1354                     }
1355                 }
1356             };
1357
1358             code_blocks.push(RustCodeBlock {
1359                 is_fenced,
1360                 range,
1361                 code: Range { start: code_start, end: code_end },
1362                 syntax,
1363                 is_ignore,
1364             });
1365         }
1366     }
1367
1368     code_blocks
1369 }
1370
1371 #[derive(Clone, Default, Debug)]
1372 pub struct IdMap {
1373     map: FxHashMap<String, usize>,
1374 }
1375
1376 fn init_id_map() -> FxHashMap<String, usize> {
1377     let mut map = FxHashMap::default();
1378     // This is the list of IDs used in Javascript.
1379     map.insert("help".to_owned(), 1);
1380     // This is the list of IDs used in HTML generated in Rust (including the ones
1381     // used in tera template files).
1382     map.insert("mainThemeStyle".to_owned(), 1);
1383     map.insert("themeStyle".to_owned(), 1);
1384     map.insert("theme-picker".to_owned(), 1);
1385     map.insert("theme-choices".to_owned(), 1);
1386     map.insert("settings-menu".to_owned(), 1);
1387     map.insert("help-button".to_owned(), 1);
1388     map.insert("main".to_owned(), 1);
1389     map.insert("search".to_owned(), 1);
1390     map.insert("crate-search".to_owned(), 1);
1391     map.insert("render-detail".to_owned(), 1);
1392     map.insert("toggle-all-docs".to_owned(), 1);
1393     map.insert("all-types".to_owned(), 1);
1394     map.insert("default-settings".to_owned(), 1);
1395     map.insert("rustdoc-vars".to_owned(), 1);
1396     map.insert("sidebar-vars".to_owned(), 1);
1397     map.insert("copy-path".to_owned(), 1);
1398     map.insert("TOC".to_owned(), 1);
1399     // This is the list of IDs used by rustdoc sections (but still generated by
1400     // rustdoc).
1401     map.insert("fields".to_owned(), 1);
1402     map.insert("variants".to_owned(), 1);
1403     map.insert("implementors-list".to_owned(), 1);
1404     map.insert("synthetic-implementors-list".to_owned(), 1);
1405     map.insert("foreign-impls".to_owned(), 1);
1406     map.insert("implementations".to_owned(), 1);
1407     map.insert("trait-implementations".to_owned(), 1);
1408     map.insert("synthetic-implementations".to_owned(), 1);
1409     map.insert("blanket-implementations".to_owned(), 1);
1410     map.insert("associated-types".to_owned(), 1);
1411     map.insert("associated-const".to_owned(), 1);
1412     map.insert("required-methods".to_owned(), 1);
1413     map.insert("provided-methods".to_owned(), 1);
1414     map.insert("implementors".to_owned(), 1);
1415     map.insert("synthetic-implementors".to_owned(), 1);
1416     map.insert("trait-implementations-list".to_owned(), 1);
1417     map.insert("synthetic-implementations-list".to_owned(), 1);
1418     map.insert("blanket-implementations-list".to_owned(), 1);
1419     map.insert("deref-methods".to_owned(), 1);
1420     map
1421 }
1422
1423 impl IdMap {
1424     pub fn new() -> Self {
1425         IdMap { map: init_id_map() }
1426     }
1427
1428     crate fn derive<S: AsRef<str> + ToString>(&mut self, candidate: S) -> String {
1429         let id = match self.map.get_mut(candidate.as_ref()) {
1430             None => candidate.to_string(),
1431             Some(a) => {
1432                 let id = format!("{}-{}", candidate.as_ref(), *a);
1433                 *a += 1;
1434                 id
1435             }
1436         };
1437
1438         self.map.insert(id.clone(), 1);
1439         id
1440     }
1441 }