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