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