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