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