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