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